{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":36363,"databundleVersionId":4050810,"sourceType":"competition"}],"dockerImageVersionId":30698,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pip install torch torchvision","metadata":{"execution":{"iopub.status.busy":"2024-05-14T06:25:17.44258Z","iopub.execute_input":"2024-05-14T06:25:17.443068Z","iopub.status.idle":"2024-05-14T06:25:27.509176Z","shell.execute_reply.started":"2024-05-14T06:25:17.443039Z","shell.execute_reply":"2024-05-14T06:25:27.50791Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pip install pydicom","metadata":{"execution":{"iopub.status.busy":"2024-05-14T06:25:27.51508Z","iopub.execute_input":"2024-05-14T06:25:27.515433Z","iopub.status.idle":"2024-05-14T06:25:37.490026Z","shell.execute_reply.started":"2024-05-14T06:25:27.515385Z","shell.execute_reply":"2024-05-14T06:25:37.488676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pip install --upgrade pydicom","metadata":{"execution":{"iopub.status.busy":"2024-05-14T06:25:37.493648Z","iopub.execute_input":"2024-05-14T06:25:37.494006Z","iopub.status.idle":"2024-05-14T06:25:47.501558Z","shell.execute_reply.started":"2024-05-14T06:25:37.493955Z","shell.execute_reply":"2024-05-14T06:25:47.500309Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pip install pylibjpeg pylibjpeg-libjpeg pydicom","metadata":{"execution":{"iopub.status.busy":"2024-05-14T06:25:47.503019Z","iopub.execute_input":"2024-05-14T06:25:47.503369Z","iopub.status.idle":"2024-05-14T06:25:57.619711Z","shell.execute_reply.started":"2024-05-14T06:25:47.50334Z","shell.execute_reply":"2024-05-14T06:25:57.618906Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport pandas as pdw\nimport pydicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nfrom PIL import Image\nimport torch\nimport numpy as np","metadata":{"execution":{"iopub.status.busy":"2024-05-14T06:25:57.620634Z","iopub.execute_input":"2024-05-14T06:25:57.620895Z","iopub.status.idle":"2024-05-14T06:25:57.628361Z","shell.execute_reply.started":"2024-05-14T06:25:57.620869Z","shell.execute_reply":"2024-05-14T06:25:57.626094Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IS_LOCAL = False\nimport numpy as np\nimport pandas as pd\nfrom skimage.io import imread\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom glob import glob\n\n# import pydicom as dicom\n\nimport os\n\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\nimport matplotlib.patches as patches","metadata":{"execution":{"iopub.status.busy":"2024-05-14T06:34:09.908652Z","iopub.execute_input":"2024-05-14T06:34:09.909008Z","iopub.status.idle":"2024-05-14T06:34:09.914519Z","shell.execute_reply.started":"2024-05-14T06:34:09.90898Z","shell.execute_reply":"2024-05-14T06:34:09.913332Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#########Code for Albert\n\n#bbox csv\ntrain_bbox = pd.read_csv(\"../input/rsna-2022-cervical-spine-fracture-detection/train_bounding_boxes.csv\")\n\n#List of patients with Bounding boxes:\nbbox_patient_list = train_bbox['StudyInstanceUID'].unique()\nprint(bbox_patient_list[0:10])\n\nprint(\"\\nNumber of BBOX patients:  \",len(bbox_patient_list)) #235 patients with bounding boxes\n\n#Input Patient here\npatient = '1.2.826.0.1.3680043.10051'  # '1.2.826.0.1.3680043.10051' for example\n\n#This line will contain what Slices of this patient have bounding boxes and therefore what slices have fractures on them\nslices_with_bboxes = train_bbox.loc[train_bbox['StudyInstanceUID'] == patient]['slice_number'].to_list()\n\nprint(slices_with_bboxes)\n\n# Create a Matplotlib figure and axis\nfig, ax = plt.subplots()\n\nbase_path = \"../input/rsna-2022-cervical-spine-fracture-detection\"\ndef plot_fracture(slice_num,bbox_id,ax_id1,ax_id2):\n    file = pydicom.dcmread(f\"{base_path}/train_images/{bbox_id}/{slice_num}.dcm\")\n    img = apply_voi_lut(file.pixel_array, file)\n    info = train_bbox[(train_bbox['StudyInstanceUID']==bbox_id)&(train_bbox['slice_number']==slice_num)]\n    rect = patches.Rectangle((float(info.x), float(info.y)), float(info.width), float(info.height), linewidth=3, edgecolor='r', facecolor='none')\n\n    axes[ax_id1,ax_id2].imshow(img, cmap=\"bone\")\n    axes[ax_id1,ax_id2].add_patch(rect)\n    axes[ax_id1,ax_id2].set_title(f\"Slice: {slice_num}\", fontsize=20, weight='bold',y=1.02)\n    axes[ax_id1,ax_id2].axis('off')\nfig, axes = plt.subplots(nrows=6, ncols=3, figsize=(24,48))\nfig.suptitle(f'ID: {patient}', weight=\"bold\", size=20)\n\nfor i in range (0,len(slices_with_bboxes)):\n    x = (i) // 3\n    y = (i) % 3\n    plot_fracture(train_bbox.loc[train_bbox['StudyInstanceUID'] == patient]['slice_number'].to_list()[i], patient,x,y)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-14T06:34:11.760548Z","iopub.execute_input":"2024-05-14T06:34:11.760888Z","iopub.status.idle":"2024-05-14T06:34:16.052252Z","shell.execute_reply.started":"2024-05-14T06:34:11.760864Z","shell.execute_reply":"2024-05-14T06:34:16.051093Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a Matplotlib figure and axis\nfig, ax = plt.subplots()\n\npatient = '1.2.826.0.1.3680043.10051'\n\n#This line will contain what Slices of this patient have bounding boxes and therefore what slices have fractures on them\nslices_with_bboxes = train_bbox.loc[train_bbox['StudyInstanceUID'] == patient]['slice_number'].to_list()\n\nprint(slices_with_bboxes)\n\nslice_num = 138   #The slice you want to look at\n\nbase_path = \"../input/rsna-2022-cervical-spine-fracture-detection\"\n\nfile = pydicom.dcmread(f\"{base_path}/train_images/{patient}/{slice_num}.dcm\")\nimg = apply_voi_lut(file.pixel_array, file)\ninfo = train_bbox[(train_bbox['StudyInstanceUID']==patient)&(train_bbox['slice_number']==slice_num)]\nrect = patches.Rectangle((float(info.x), float(info.y)), float(info.width), float(info.height), linewidth=3, edgecolor='r', facecolor='none')\n\nax.imshow(img, cmap=\"bone\")\nax.add_patch(rect)\nax.set_title(f\"Slice: {slice_num}\", fontsize=20, weight='bold',y=1.02)\nax.axis('off')\n","metadata":{"execution":{"iopub.status.busy":"2024-05-14T06:34:25.55877Z","iopub.execute_input":"2024-05-14T06:34:25.559135Z","iopub.status.idle":"2024-05-14T06:34:25.729373Z","shell.execute_reply.started":"2024-05-14T06:34:25.559107Z","shell.execute_reply":"2024-05-14T06:34:25.728213Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Animation for the CT Scan\n# import os\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport pydicom as dicom\nPATH = '../input/rsna-2022-cervical-spine-fracture-detection/train_images/'\ndirectory_path = os.path.join(PATH, patient)\nprint(directory_path)\n# Define the directory containing the DICOM images\n# List all DICOM files in the directory\nslices = [dicom.dcmread(os.path.join(PATH, patient) + '/' + s) for s in os.listdir(os.path.join(PATH, patient))]\nbbox_indices = train_bbox.loc[train_bbox['StudyInstanceUID'] == patient]['slice_number'].to_list()\n\n\nslices.sort(key = lambda x: float(x.ImagePositionPatient[2]), reverse=True) # Sort Slices by the z axis\n# Function to update the plot for each frame of the animation\n\n\n\ndef update(frame):\n    ax.clear()  # Clear previous frame\n    #ax.imshow(vol[frame], cmap='gray', vmin=0, vmax = 200 )  # Contrast to show only Spine\n    #ax.imshow(vol[frame], cmap='gray', vmin=-200, vmax = 200 )  # Contrast that amplifies spine\n    mask = slices[frame].pixel_array\n\n    ax.imshow(mask, cmap='gray')\n    for i in range (0, len(bbox_indices)):\n        if (frame == bbox_indices[i]):\n            print(frame)\n            info = train_bbox[(train_bbox['StudyInstanceUID']==patient)&(train_bbox['slice_number']==frame)]\n            rect = patches.Rectangle((float(info.x), float(info.y)), float(info.width), float(info.height), linewidth=3, edgecolor='r', facecolor='none')\n            ax.add_patch(rect)\n    try:\n        ax.set_title(f\"Slice: {frame}\", fontsize=14, weight='bold')\n        #ax.set_title(f\"Slice: {frame} Vertebrae: {np.unique(slices[frame])[1]}\", fontsize=14, weight='bold')\n    except:\n        ax.set_title(f\"Slice: {frame}\", fontsize=14, weight='bold')\n    #Get progress of video compilation\n    if (frame%50 == 0):\n        print(frame)\n    ax.axis('off')\n\n\n\n# Create a Matplotlib figure and axis\nfig, ax = plt.subplots()\n\n# Create animation\nani = animation.FuncAnimation(fig, update, frames=len(slices), interval=100)\n\n# Save the animation as a video\nani.save('myAnimation4.gif', writer='pillow', fps=20)\n\n# Show the animation (optional)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-05-14T06:38:37.349989Z","iopub.execute_input":"2024-05-14T06:38:37.350334Z","iopub.status.idle":"2024-05-14T06:38:59.603622Z","shell.execute_reply.started":"2024-05-14T06:38:37.350308Z","shell.execute_reply":"2024-05-14T06:38:59.602382Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Play the Video\n\n# HTML\nfrom IPython.display import HTML\nHTML('<img src=\"./myAnimation4.gif\" />')","metadata":{"execution":{"iopub.status.busy":"2024-05-14T06:39:28.703639Z","iopub.execute_input":"2024-05-14T06:39:28.703991Z","iopub.status.idle":"2024-05-14T06:39:28.71208Z","shell.execute_reply.started":"2024-05-14T06:39:28.703963Z","shell.execute_reply":"2024-05-14T06:39:28.710739Z"},"trusted":true},"execution_count":null,"outputs":[]}]}