{"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":"**Links**\n\n1. [Exploratory Data Analysis (EDA) notebook](https://www.kaggle.com/code/samuelcortinhas/rsna-fracture-detection-in-depth-eda)\n2. [Extracting Vertebrae C1, ..., C7](https://www.kaggle.com/code/samuelcortinhas/extracting-vertebrae-c1-c7)\n3. [Dataset containing extracted metadata](https://www.kaggle.com/datasets/samuelcortinhas/rsna-2022-spine-fracture-detection-metadata)","metadata":{}},{"cell_type":"markdown","source":"**Libraries**","metadata":{}},{"cell_type":"code","source":"! pip install python-gdcm\n! pip install pylibjpeg pylibjpeg-libjpeg pydicom","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2022-08-19T13:17:38.437428Z","iopub.execute_input":"2022-08-19T13:17:38.437899Z","iopub.status.idle":"2022-08-19T13:18:00.630572Z","shell.execute_reply.started":"2022-08-19T13:17:38.437792Z","shell.execute_reply":"2022-08-19T13:18:00.629543Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom matplotlib import animation, rc; rc('animation', html='jshtml')\nimport re\nimport os\nimport cv2\nimport gc\nfrom glob import glob\nimport pydicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut","metadata":{"_kg_hide-input":false,"execution":{"iopub.status.busy":"2022-08-19T13:18:00.631987Z","iopub.execute_input":"2022-08-19T13:18:00.632332Z","iopub.status.idle":"2022-08-19T13:18:00.842249Z","shell.execute_reply.started":"2022-08-19T13:18:00.632301Z","shell.execute_reply":"2022-08-19T13:18:00.841152Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Animation function**","metadata":{}},{"cell_type":"code","source":"def create_animation(patient_id, drc='train_images', save_dir=\"/kaggle/working/animations\", save=False, fps=10):\n    # Get paths\n    base_path = \"../input/rsna-2022-cervical-spine-fracture-detection\"\n    dcm_paths = glob(f\"{base_path}/{drc}/{patient_id}/*\")\n    def atoi(text):\n        return int(text) if text.isdigit() else text\n    def natural_keys(text):\n        return [atoi(c) for c in re.split(r'(\\d+)', text)]\n    dcm_paths.sort(key=natural_keys)\n    \n    # Get images\n    files = [pydicom.dcmread(path) for path in dcm_paths]\n    images = [apply_voi_lut(file.pixel_array, file) for file in files]\n    \n    # Optimise memory\n    images_small = [np.clip(cv2.resize(img,dsize=[256,256]),-32768,32767).astype('int16') for img in images]\n    \n    # Stack images\n    animation_arr = np.stack(images_small, axis=0)\n\n    del images, images_small\n    gc.collect()\n    \n    # Initialise plot\n    fig = plt.figure(figsize=(3,3))  # if size is too big then gif gets truncated\n    im = plt.imshow(animation_arr[0], cmap='bone')\n    plt.axis('off')\n    plt.title(f\"{patient_id}\", fontweight=\"bold\")\n    \n    # Load next frame\n    def animate_func(i):\n        im.set_array(animation_arr[i])\n        return [im]\n    plt.close()\n    \n    # Animation function\n    anim = animation.FuncAnimation(fig, animate_func, frames = animation_arr.shape[0], interval = 1000//fps)\n    \n    # Save\n    if save:\n        os.makedirs(save_dir, exist_ok=True)\n        anim.save(os.path.join(save_dir, f\"patient_{patient_id}.gif\"), fps=10, writer='imagemagick')\n        \n    return anim","metadata":{"execution":{"iopub.status.busy":"2022-08-19T13:18:00.843712Z","iopub.execute_input":"2022-08-19T13:18:00.844146Z","iopub.status.idle":"2022-08-19T13:18:00.859138Z","shell.execute_reply.started":"2022-08-19T13:18:00.844103Z","shell.execute_reply":"2022-08-19T13:18:00.857899Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Examples**","metadata":{}},{"cell_type":"code","source":"train_df = pd.read_csv('../input/rsna-2022-cervical-spine-fracture-detection/train.csv')\n#train_df['StudyInstanceUID'].unique()[:10]","metadata":{"execution":{"iopub.status.busy":"2022-08-19T13:18:00.861643Z","iopub.execute_input":"2022-08-19T13:18:00.861989Z","iopub.status.idle":"2022-08-19T13:18:00.878839Z","shell.execute_reply.started":"2022-08-19T13:18:00.861958Z","shell.execute_reply":"2022-08-19T13:18:00.877397Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ~ 30 secs\ncreate_animation('1.2.826.0.1.3680043.18659', fps=10)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T13:18:00.880309Z","iopub.execute_input":"2022-08-19T13:18:00.880693Z","iopub.status.idle":"2022-08-19T13:18:15.150463Z","shell.execute_reply.started":"2022-08-19T13:18:00.880659Z","shell.execute_reply":"2022-08-19T13:18:15.148427Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ~ 30 secs\ncreate_animation('1.2.826.0.1.3680043.4859', fps=20)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T13:18:15.152816Z","iopub.execute_input":"2022-08-19T13:18:15.153958Z","iopub.status.idle":"2022-08-19T13:18:28.318954Z","shell.execute_reply.started":"2022-08-19T13:18:15.153884Z","shell.execute_reply":"2022-08-19T13:18:28.315234Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ~ 30 secs\ncreate_animation('1.2.826.0.1.3680043.17364', fps=30)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T13:18:28.320259Z","iopub.execute_input":"2022-08-19T13:18:28.321178Z","iopub.status.idle":"2022-08-19T13:18:45.895254Z","shell.execute_reply.started":"2022-08-19T13:18:28.321137Z","shell.execute_reply":"2022-08-19T13:18:45.893457Z"},"trusted":true},"execution_count":null,"outputs":[]}]}