{"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":"code","source":"! pip install pylibjpeg -q\n! pip install python-gdcm -q\n! pip install pylibjpeg-libjpeg -q","metadata":{"execution":{"iopub.status.busy":"2022-10-31T07:10:35.447801Z","iopub.execute_input":"2022-10-31T07:10:35.448483Z","iopub.status.idle":"2022-10-31T07:11:14.387678Z","shell.execute_reply.started":"2022-10-31T07:10:35.44834Z","shell.execute_reply":"2022-10-31T07:11:14.385981Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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 pandas as pd\nimport numpy as np \nimport scipy as sc \nimport pydicom as dicom\nimport matplotlib.patches as patches\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\nimport torch\nimport torchvision as tv\nfrom tqdm.notebook import tqdm\nimport wandb\nimport tensorflow as tf\n\nfrom pydicom import dcmread\nimport pylibjpeg\nimport cv2\nimport matplotlib.pyplot as plt \nimport random\nfrom random import randint\n\n# Packages\nimport nibabel as nb\nimport os\nimport sys\nimport math\nfrom pathlib import Path\nimport warnings\nwarnings.simplefilter(\"ignore\")\n\n# for 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","execution":{"iopub.status.busy":"2022-10-31T07:19:53.466044Z","iopub.execute_input":"2022-10-31T07:19:53.466454Z","iopub.status.idle":"2022-10-31T07:19:53.475791Z","shell.execute_reply.started":"2022-10-31T07:19:53.466421Z","shell.execute_reply":"2022-10-31T07:19:53.474517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"root = Path('../input/rsna-2022-cervical-spine-fracture-detection')\ntrain_folder = root/'train_images'\ntest_folder = root/'test_images'\n\nseg_folder = root/'segmentations'\nsegmentations = list(seg_folder.iterdir())\nseg_ids = [o.stem for o in segmentations]\n\ntrain_df = pd.read_csv(\"../input/rsna-2022-cervical-spine-fracture-detection/train.csv\")\ntrain_bbox = pd.read_csv(\"../input/rsna-2022-cervical-spine-fracture-detection/train_bounding_boxes.csv\")\ntest_df = pd.read_csv(\"../input/rsna-2022-cervical-spine-fracture-detection/test.csv\")\nbbdf = pd.read_csv('../input/rsna-2022-cervical-spine-fracture-detection/train_bounding_boxes.csv')\n\ntrain_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-10-31T07:18:48.139249Z","iopub.execute_input":"2022-10-31T07:18:48.139686Z","iopub.status.idle":"2022-10-31T07:18:48.188052Z","shell.execute_reply.started":"2022-10-31T07:18:48.139652Z","shell.execute_reply":"2022-10-31T07:18:48.186658Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-10-31T07:11:25.383155Z","iopub.execute_input":"2022-10-31T07:11:25.38358Z","iopub.status.idle":"2022-10-31T07:11:25.398398Z","shell.execute_reply.started":"2022-10-31T07:11:25.383542Z","shell.execute_reply":"2022-10-31T07:11:25.397131Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_dicom(path):\n    img=dicom.dcmread(path)\n    img.PhotometricInterpretation = 'YBR_FULL'\n    data = img.pixel_array    \n    data = data - np.min(data)\n    if np.max(data) != 0:\n        data = data / np.max(data)\n    data=(data * 255).astype(np.uint8)\n    return cv2.cvtColor(data, cv2.COLOR_GRAY2RGB), img\n\nrand= randint(0, 10)\nprint(f'1.2.826.0.1.3680043.10001/{rand}.dcm')\nim, meta = load_dicom(f'../input/rsna-2022-cervical-spine-fracture-detection/train_images/1.2.826.0.1.3680043.11170/{rand}.dcm')\n\nplt.figure(figsize = (10,10))\nplt.imshow(im)\nplt.title('Train regular image')","metadata":{"execution":{"iopub.status.busy":"2022-10-31T07:11:25.400047Z","iopub.execute_input":"2022-10-31T07:11:25.401366Z","iopub.status.idle":"2022-10-31T07:11:25.926246Z","shell.execute_reply.started":"2022-10-31T07:11:25.401324Z","shell.execute_reply":"2022-10-31T07:11:25.925202Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"randomlist = random.sample(range(1, 125), 25)\ncount = 0\n\nplt.figure(figsize=(15,15))\n\nfor sel in randomlist:\n    print(f'1.2.826.0.1.3680043.10001/{sel}.dcm')\n    im, meta = load_dicom(f'../input/rsna-2022-cervical-spine-fracture-detection/train_images/1.2.826.0.1.3680043.11170/{sel}.dcm')\n    plt.subplot(5, 5, count+1)\n    plt.xticks([])\n    plt.imshow(im, cmap='gray')\n    plt.xlabel(f'{sel}.dcm')\n    count+=1","metadata":{"execution":{"iopub.status.busy":"2022-10-31T07:13:34.99664Z","iopub.execute_input":"2022-10-31T07:13:34.997078Z","iopub.status.idle":"2022-10-31T07:13:39.032165Z","shell.execute_reply.started":"2022-10-31T07:13:34.997044Z","shell.execute_reply":"2022-10-31T07:13:39.030843Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path = '../input/rsna-2022-cervical-spine-fracture-detection/segmentations/1.2.826.0.1.3680043.12833.nii'\nimg = nb.load(path)\nprint(img)\n\n# Convert to numpy array\nseg = img.get_fdata()[:, ::-1, ::-1].transpose(2, 1, 0)\nseg.shape\n\n# Plot images\ntest = seg[:,:,200]\nplt.imshow(test)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-10-31T07:11:54.470108Z","iopub.execute_input":"2022-10-31T07:11:54.470493Z","iopub.status.idle":"2022-10-31T07:11:55.791562Z","shell.execute_reply.started":"2022-10-31T07:11:54.470457Z","shell.execute_reply":"2022-10-31T07:11:55.790001Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_fracture(slice_num,bbox_id,ax_id1,ax_id2):\n    file = dicom.dcmread(f\"{root}/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\"ID:{bbox_id}, Slice: {slice_num}\", fontsize=15, weight='bold',y=1.02)\n    axes[ax_id1,ax_id2].axis('off')\n\nfig, axes = plt.subplots(nrows=2, ncols=2, figsize=(15,15))\nplot_fracture(119,'1.2.826.0.1.3680043.25651',0,0)\nplot_fracture(156,'1.2.826.0.1.3680043.23817',0,1)\nplot_fracture(325,'1.2.826.0.1.3680043.12031',1,0)\nplot_fracture(151,'1.2.826.0.1.3680043.11899',1,1)","metadata":{"execution":{"iopub.status.busy":"2022-10-31T07:20:37.969962Z","iopub.execute_input":"2022-10-31T07:20:37.971093Z","iopub.status.idle":"2022-10-31T07:20:38.879681Z","shell.execute_reply.started":"2022-10-31T07:20:37.971019Z","shell.execute_reply":"2022-10-31T07:20:38.878413Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-10-31T07:11:55.793012Z","iopub.execute_input":"2022-10-31T07:11:55.79383Z","iopub.status.idle":"2022-10-31T07:11:55.80797Z","shell.execute_reply.started":"2022-10-31T07:11:55.793792Z","shell.execute_reply":"2022-10-31T07:11:55.806542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df[train_df.columns[2:]].sum().plot.bar(rot=0, color='DarkTurquoise')\nplt.title(\"Fracturas por sección C\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-10-31T07:11:55.809595Z","iopub.execute_input":"2022-10-31T07:11:55.810927Z","iopub.status.idle":"2022-10-31T07:11:56.063932Z","shell.execute_reply.started":"2022-10-31T07:11:55.810882Z","shell.execute_reply":"2022-10-31T07:11:56.062707Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.patient_overall.value_counts().sort_values().plot(kind = 'barh', color='brown')\nplt.title(\"Patient overall fractures\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-10-31T07:11:56.067675Z","iopub.execute_input":"2022-10-31T07:11:56.068927Z","iopub.status.idle":"2022-10-31T07:11:56.251227Z","shell.execute_reply.started":"2022-10-31T07:11:56.068874Z","shell.execute_reply":"2022-10-31T07:11:56.250101Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}