{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# NFL Player Contact Detection\n [1st and Future - Player Contact Detection Competiton](https://www.kaggle.com/competitions/nfl-player-contact-detection).","metadata":{}},{"cell_type":"code","source":"# import dependencies\nimport numpy as np\nimport pandas as pd\nimport os\nimport cv2\nimport subprocess\n\n# IPython\nimport IPython\nfrom IPython.display import Video, display\n\n# matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nfrom matplotlib.markers import MarkerStyle\nimport matplotlib.animation as animation","metadata":{"execution":{"iopub.status.busy":"2022-12-26T05:50:22.507934Z","iopub.execute_input":"2022-12-26T05:50:22.508441Z","iopub.status.idle":"2022-12-26T05:50:22.7652Z","shell.execute_reply.started":"2022-12-26T05:50:22.508328Z","shell.execute_reply":"2022-12-26T05:50:22.764298Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# paths\n\nTEST_DIR = '/kaggle/input/nfl-player-contact-detection/test'\nTRAIN_DIR = '/kaggle/input/nfl-player-contact-detection/train'\n\nTEST_BASELINE_HELMETS = '/kaggle/input/nfl-player-contact-detection/test_baseline_helmets.csv'\nTRAIN_BASELINE_HELMETS = '/kaggle/input/nfl-player-contact-detection/train_baseline_helmets.csv'\n\nTEST_PLAYER_TRACKING = '/kaggle/input/nfl-player-contact-detection/test_player_tracking.csv'\nTRAIN_PLAYER_TRACKING = '/kaggle/input/nfl-player-contact-detection/train_player_tracking.csv'\n\nTEST_VIDEO_METADATA = '/kaggle/input/nfl-player-contact-detection/test_video_metadata.csv'\nTRAIN_VIDEO_METADATA = '/kaggle/input/nfl-player-contact-detection/train_video_metadata.csv'\n\nTRAIN_LABELS = '/kaggle/input/nfl-player-contact-detection/train_labels.csv'\nSAMPLE_SUBMISSION = '/kaggle/input/nfl-player-contact-detection/sample_submission.csv'","metadata":{"execution":{"iopub.status.busy":"2022-12-26T05:50:34.564415Z","iopub.execute_input":"2022-12-26T05:50:34.564777Z","iopub.status.idle":"2022-12-26T05:50:34.570494Z","shell.execute_reply.started":"2022-12-26T05:50:34.564734Z","shell.execute_reply":"2022-12-26T05:50:34.569293Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# TRAIN_BASELINE_HELMETS\n\ntrain_baseline_helmets_data = pd.read_csv(TRAIN_BASELINE_HELMETS)\nprint(train_baseline_helmets_data.shape)\ntrain_baseline_helmets_data.head()","metadata":{"execution":{"iopub.status.busy":"2022-12-26T05:50:34.975834Z","iopub.execute_input":"2022-12-26T05:50:34.97619Z","iopub.status.idle":"2022-12-26T05:50:41.197368Z","shell.execute_reply.started":"2022-12-26T05:50:34.976158Z","shell.execute_reply":"2022-12-26T05:50:41.1963Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def play_video(video_path: str):\n    frac = 0.65 # scaling factor for display \n    display(\n        Video(data=video_path, embed=True, height=int(720*frac), width=int(1280*frac))\n    )","metadata":{"execution":{"iopub.status.busy":"2022-12-26T05:50:41.199279Z","iopub.execute_input":"2022-12-26T05:50:41.200077Z","iopub.status.idle":"2022-12-26T05:50:41.205467Z","shell.execute_reply.started":"2022-12-26T05:50:41.20002Z","shell.execute_reply":"2022-12-26T05:50:41.204105Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"video_path = '/kaggle/input/nfl-player-contact-detection/train/58168_003392_Endzone.mp4'\nplay_video(video_path)","metadata":{"execution":{"iopub.status.busy":"2022-12-26T05:50:41.206937Z","iopub.execute_input":"2022-12-26T05:50:41.207244Z","iopub.status.idle":"2022-12-26T05:50:41.360346Z","shell.execute_reply.started":"2022-12-26T05:50:41.207216Z","shell.execute_reply":"2022-12-26T05:50:41.355658Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def annotate_video_with_helmets(video_path: str, baseline_boxes:pd.DataFrame, verbose=True) -> str:\n    \"\"\"\n    Annotates a video with baseline model boxes and labels.\n    \"\"\"\n    video_name = video_path.split('/')[-1]\n    play_name = video_name.split('.')[0]\n    HELMET_COLOR = (0, 0, 0) # black\n    baseline_boxes = baseline_boxes.query(\"video==@video_name\").copy()\n    \n    # verbose\n    if verbose==True:\n        print(f\"Running for {video_name}\")\n    \n    # VideoCapture Object\n    cap  = cv2.VideoCapture(video_path)\n    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n    fps = cap.get(cv2.CAP_PROP_FPS)\n    \n    # VideoWriter Object\n    output_path = \"labeled_\" + video_name\n    tmp_output_path = \"tmp_\" + output_path\n    out = cv2.VideoWriter(tmp_output_path, cv2.VideoWriter_fourcc(*'MP4V'), \n                          fps, (width, height))\n    \n    # check  if camera opened successfully\n    if cap.isOpened() == False:\n        print('Error opening file')\n        \n    # read until video is complete\n    frame  = 1\n    while(cap.isOpened()):\n        # capture frame by frame\n        ret, img = cap.read()\n        \n        if ret==True:\n            # add play_name text\n            cv2.putText(img, play_name,\n                       (int(0.01*width), int(0.05*height)),\n                        cv2.FONT_HERSHEY_SIMPLEX,\n                        1,\n                        HELMET_COLOR,\n                        1\n                       )\n            \n            # add frame counter\n            cv2.putText(img, \"Frame: \"+str(frame),\n                       (int(0.75*width), int(0.05*height)),\n                        cv2.FONT_HERSHEY_SIMPLEX,\n                        1,\n                        HELMET_COLOR,\n                        1\n                       )\n\n            # adding helmet bounding boxes and player tags\n            bbox_set = baseline_boxes.query(\"frame==@frame\")\n            for i, annot in enumerate(zip(np.array(bbox_set[['player_label','left','width','top','height']]))):\n                player_label, bbox_left, bbox_width, bbox_top, bbox_height = annot[0]\n                # add helmet bbox\n                cv2.rectangle(img, \n                              (bbox_left,bbox_top), (bbox_left+bbox_width, bbox_top+bbox_height),\n                              HELMET_COLOR,\n                              1\n                             )\n                # add player label\n                cv2.putText(img, player_label,\n                       (bbox_left+10, bbox_top+10),\n                        cv2.FONT_HERSHEY_SIMPLEX,\n                        1,\n                        HELMET_COLOR,\n                        1\n                       )\n            \n            frame += 1\n            out.write(img) \n                \n        # break the loop   \n        else: \n            break\n        \n        \n    out.release()\n    \n    # Not all browsers support the codec, we will re-load the file at tmp_output_path\n    # and convert to a codec that is more broadly readable using ffmpeg\n    if os.path.exists(output_path):\n        os.remove(output_path)\n    subprocess.run(\n        [\n            \"ffmpeg\",\n            \"-i\",\n            tmp_output_path,\n            \"-crf\",\n            \"18\",\n            \"-preset\",\n            \"veryfast\",\n            \"-hide_banner\",\n            \"-loglevel\",\n            \"error\",\n            \"-vcodec\",\n            \"libx264\",\n            output_path,\n        ]\n    )\n    os.remove(tmp_output_path)\n    \n    return output_path","metadata":{"execution":{"iopub.status.busy":"2022-12-26T05:50:41.362445Z","iopub.execute_input":"2022-12-26T05:50:41.362749Z","iopub.status.idle":"2022-12-26T05:50:41.380358Z","shell.execute_reply.started":"2022-12-26T05:50:41.362726Z","shell.execute_reply":"2022-12-26T05:50:41.379069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path = annotate_video_with_helmets(video_path, train_baseline_helmets_data)\nplay_video(path)","metadata":{"execution":{"iopub.status.busy":"2022-12-26T05:50:41.382091Z","iopub.execute_input":"2022-12-26T05:50:41.38246Z","iopub.status.idle":"2022-12-26T05:50:56.097364Z","shell.execute_reply.started":"2022-12-26T05:50:41.382427Z","shell.execute_reply":"2022-12-26T05:50:56.096174Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(path)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Resources: \nhttps://www.kaggle.com/code/dariussingh/nfl-visualizing-players-with-heltmets","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}