{"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 - Visualizing Players with Heltmets\nThis notebook shows how to visualize player tracking data of NFL play videos provided in the [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:56:21.952734Z","iopub.execute_input":"2022-12-26T05:56:21.953182Z","iopub.status.idle":"2022-12-26T05:56:21.961170Z","shell.execute_reply.started":"2022-12-26T05:56:21.953137Z","shell.execute_reply":"2022-12-26T05:56:21.959694Z"},"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:56:26.822248Z","iopub.execute_input":"2022-12-26T05:56:26.822667Z","iopub.status.idle":"2022-12-26T05:56:26.828256Z","shell.execute_reply.started":"2022-12-26T05:56:26.822634Z","shell.execute_reply":"2022-12-26T05:56:26.827464Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# TRAIN_PLAYER_TRACKING\n\ntrain_player_tracking_data = pd.read_csv(TRAIN_PLAYER_TRACKING)\nprint(train_player_tracking_data.shape)\ntrain_player_tracking_data.head()","metadata":{"execution":{"iopub.status.busy":"2022-12-26T05:56:41.820666Z","iopub.execute_input":"2022-12-26T05:56:41.821062Z","iopub.status.idle":"2022-12-26T05:56:45.758983Z","shell.execute_reply.started":"2022-12-26T05:56:41.821019Z","shell.execute_reply":"2022-12-26T05:56:45.758182Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_football_field(fig, ax, line_color='black', field_color='white'):\n    \"\"\"\n    Function that plots the football field for viewing players.\n    \"\"\"\n    \n    # set field dimensions\n    plt.xlim(0,120)\n    plt.ylim(0,53.3)\n    \n    # adding rectangles to the field\n    for i in range(12):\n        rect = patches.Rectangle((10*i,0), 10, 53.3, linewidth=1, edgecolor=line_color, facecolor=field_color)\n        ax.add_patch(rect)\n    \n    # configure axes\n    ax.tick_params(\n        axis='both',\n        which='both',\n        direction='in',\n        pad=-40,\n        length = 5,\n        bottom=True,\n        top=True,\n        labeltop=True,\n        labelbottom=True,\n        left=False,\n        right=False,\n        labelleft=False,\n        labelright=False,\n        color=line_color)\n    \n    # set ticks on the side of the field\n    ax.set_xticks([i for i in range(10,111)])\n    \n    # setting yard marking\n    label_set = []\n    for i in range(1,10):\n        if i<=5:\n            label_set += [\" \" for j in range(9)] + [str(i*10)]\n        else:\n            label_set += [\" \" for j in range(9)] + [str((10-i)*10)]\n    label_set =  [\" \"] + label_set + [\" \" for j in range(10)]\n    ax.set_xticklabels(label_set, fontsize=20, color=line_color)\n    \n    \n    return fig, ax","metadata":{"execution":{"iopub.status.busy":"2022-12-26T05:56:55.623994Z","iopub.execute_input":"2022-12-26T05:56:55.624387Z","iopub.status.idle":"2022-12-26T05:56:55.637352Z","shell.execute_reply.started":"2022-12-26T05:56:55.624355Z","shell.execute_reply":"2022-12-26T05:56:55.636285Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def populate_field(play_name:str, step:np.int64, player_tracking_data:pd.DataFrame, home_color:str='violet', away_color:str='coral'):\n    \"\"\"\n    populates the field with player tracking data of a play_name and step.\n    \"\"\"\n    # subset data to current play and step \n    step_info = player_tracking_data.query(\"game_play==@play_name and step==@step \").copy()\n    \n    # create new field\n    fig, ax= plt.subplots(figsize=(12, 5.33))\n    fig, ax  = create_football_field(fig, ax)\n    \n    # set title\n    ax.set_title(f'Tracking data for {play_name} at step {step}')\n    \n    # populate field with players\n    for row in step_info.iterrows():\n        if row[1]['team'] == 'home':\n            color = home_color\n        else:\n            color = away_color\n        marker1 = MarkerStyle(r'$\\spadesuit$')\n        marker1._transform.rotate_deg(360-row[1]['orientation'])\n        ax.scatter(row[1]['x_position'], row[1]['y_position'], marker=marker1, s=150, color=color)    \n    \n    plt.close()\n    return fig, ax","metadata":{"execution":{"iopub.status.busy":"2022-12-26T05:57:03.697809Z","iopub.execute_input":"2022-12-26T05:57:03.698226Z","iopub.status.idle":"2022-12-26T05:57:03.708195Z","shell.execute_reply.started":"2022-12-26T05:57:03.698188Z","shell.execute_reply":"2022-12-26T05:57:03.706906Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, ax = populate_field(play_name='58168_003392', step=1, player_tracking_data=train_player_tracking_data)\nfig","metadata":{"execution":{"iopub.status.busy":"2022-12-26T05:57:10.107729Z","iopub.execute_input":"2022-12-26T05:57:10.108150Z","iopub.status.idle":"2022-12-26T05:57:13.598940Z","shell.execute_reply.started":"2022-12-26T05:57:10.108104Z","shell.execute_reply":"2022-12-26T05:57:13.597781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# arguments\nplay_name = '58168_003392'\ndata = train_player_tracking_data.copy()\n\n# total number of frames at 10hz\nframes = len(data.query(\"game_play==@play_name\")['step'].unique())\n\n# frequency modifier factor [min_val:1, max_val:10] (reduce this for smoother tracking but longer rendering time)\nfreq_mod_fac = 5\n# to reduce rendering time we change the frequency to (10/freq_mod_fac)Hz\nframes = int(frames/freq_mod_fac)\ninterval_ms = 100*freq_mod_fac\n\n\n# initialize figure\nfig, ax = plt.subplots(figsize=(12, 5.33))\nfig, ax = create_football_field(fig, ax)\n\ndef animate(i:int, play_name:str, player_tracking_data:pd.DataFrame, frames, home_color:str='violet', away_color:str='coral'):\n    \"\"\"\n    Function to animate player tracking data\n    \"\"\"\n    # create fresh field\n    ax.clear()\n    create_football_field(fig, ax)\n    \n    # find appropriate\n    play_info = player_tracking_data.query(\"game_play==@play_name\").copy()\n    step_list = np.linspace(play_info['step'].min(), play_info['step'].max(), frames)\n    step = int(step_list[i])\n    \n    # subset data to step info\n    step_info = play_info.query(\"step==@step\").copy()\n    \n    # iterate step info to populate field\n    for row in step_info.iterrows():\n        if row[1]['team'] == 'home':\n            color = home_color\n        else:\n            color = away_color\n        marker1 = MarkerStyle(r'$\\spadesuit$')\n        marker1._transform.rotate_deg(360-row[1]['orientation'])\n        ax.scatter(row[1]['x_position'], row[1]['y_position'], marker=marker1, s=150, color=color)\n    \n    # set axis title\n    ax.set_title(f'Tracking data for {play_name} at step {step}')\n\n# animate\nanim = animation.FuncAnimation(fig, animate, fargs=(play_name, data, frames),frames=frames, repeat=False, interval=interval_ms)\n\n# embed html video to notebook\nvideo = anim.to_html5_video()\nhtml = IPython.display.HTML(video)\ndisplay(html)\nplt.close()","metadata":{"execution":{"iopub.status.busy":"2022-12-26T05:57:22.109451Z","iopub.execute_input":"2022-12-26T05:57:22.110535Z","iopub.status.idle":"2022-12-26T05:59:07.486981Z","shell.execute_reply.started":"2022-12-26T05:57:22.110470Z","shell.execute_reply":"2022-12-26T05:59:07.485670Z"},"trusted":true},"execution_count":null,"outputs":[]}]}