{"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":"Published on August 01, 2023. By Marília Prata, mpwolke.","metadata":{}},{"cell_type":"code","source":"#By Innat https://www.kaggle.com/code/ipythonx/cervical-spine-fracture-detection-quick-eda\n\nimport os\nimport cv2\nimport itertools\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom random import sample\nfrom matplotlib import pyplot as plt\n\nimport pydicom\nimport nibabel as nib\nfrom glob import glob\nfrom tqdm import tqdm\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\n\n#Ignore warnings\nimport warnings\nwarnings.filterwarnings('ignore')\n\npydicom.__version__, nib.__version__","metadata":{"execution":{"iopub.status.busy":"2023-08-01T21:16:39.245621Z","iopub.execute_input":"2023-08-01T21:16:39.246116Z","iopub.status.idle":"2023-08-01T21:16:39.257217Z","shell.execute_reply.started":"2023-08-01T21:16:39.246073Z","shell.execute_reply":"2023-08-01T21:16:39.255932Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#By Raddar\n\ndef read_dicom(path, voi_lut = True, fix_monochrome = True):\n    '''ref: https://www.kaggle.com/code/raddar/convert-dicom-to-np-array-the-correct-way\n    '''\n    dicom = pydicom.read_file(path)\n    \n    # VOI LUT (if available by DICOM device) is used to transform raw DICOM data to \"human-friendly\" view\n    if voi_lut:\n        data = apply_voi_lut(dicom.pixel_array, dicom)\n    else:\n        data = dicom.pixel_array\n               \n    # depending on this value, X-ray may look inverted - fix that:\n    if fix_monochrome and dicom.PhotometricInterpretation == \"MONOCHROME1\":\n        data = np.amax(data) - data\n        \n    data = data - np.min(data)\n    data = data / np.max(data)\n    data = (data * 255).astype(np.uint8)\n    return data, dicom","metadata":{"execution":{"iopub.status.busy":"2023-08-01T21:16:44.153538Z","iopub.execute_input":"2023-08-01T21:16:44.154049Z","iopub.status.idle":"2023-08-01T21:16:44.164992Z","shell.execute_reply.started":"2023-08-01T21:16:44.153979Z","shell.execute_reply":"2023-08-01T21:16:44.163334Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#By Innat https://www.kaggle.com/code/ipythonx/cervical-spine-fracture-detection-quick-eda\n\ndef read_nibabel(path):\n    return nib.load(path).get_fdata()","metadata":{"execution":{"iopub.status.busy":"2023-08-01T21:16:48.517393Z","iopub.execute_input":"2023-08-01T21:16:48.517861Z","iopub.status.idle":"2023-08-01T21:16:48.524012Z","shell.execute_reply.started":"2023-08-01T21:16:48.51782Z","shell.execute_reply":"2023-08-01T21:16:48.522647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#By Innat https://www.kaggle.com/code/ipythonx/cervical-spine-fracture-detection-quick-eda\n\ndef multi_dim_plot(multi_dim_array, id, num_slices=64):\n    fig = plt.figure(figsize=(30, 30))\n    plt.title(\n        f'Plotting first {num_slices} slices of {id}', \n        fontdict = {'fontsize' : 20}\n    )\n    plt.yticks([])\n    plt.xticks([])\n    \n    xy = int(np.sqrt(num_slices))\n    for i in range(num_slices):\n        ax = fig.add_subplot(xy, xy, i + 1)\n        plt.imshow(multi_dim_array[..., :num_slices][..., i])\n        plt.axis(\"off\")\n    plt.show()\n    \n    \ndef batch_plot(samples, cmap=None):\n    plt.figure(figsize=(30, 30))\n    \n    xy = int(np.sqrt(samples.shape[0]))\n    for i, sample in enumerate(samples):\n        try:\n            ax = plt.subplot(xy, xy, i + 1)\n        except:\n            ax = plt.subplot(8, 8, i + 1)\n        plt.axis('off')\n        plt.imshow(sample, cmap=cmap)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2023-08-01T21:16:53.024553Z","iopub.execute_input":"2023-08-01T21:16:53.025523Z","iopub.status.idle":"2023-08-01T21:16:53.037581Z","shell.execute_reply.started":"2023-08-01T21:16:53.025477Z","shell.execute_reply":"2023-08-01T21:16:53.036565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#Segmentation Data\n\n\"Pixel level annotations for a subset of the training set. This data is provided in the nifti file format. A portion of the imaging datasets have been segmented automatically using a 3D UNET model, and radiologists modified and approved the segmentations.\"\n\n\"Please be aware that the NIFTI files consist of segmentation in the sagittal plane, while the DICOM files are in the axial plane. Please use the NIFTI header information to determine the appropriate orientation such that the DICOM images and segmentation match. Otherwise, you run the risk of having the segmentations flipped in the Z axis and mirrored in the X axis.\"\n\nBy Innat https://www.kaggle.com/code/ipythonx/cervical-spine-fracture-detection-quick-eda","metadata":{}},{"cell_type":"code","source":"#By Innat https://www.kaggle.com/code/ipythonx/cervical-spine-fracture-detection-quick-eda\n\nsegmentation_masks = sorted(\n    glob(\n        '../input/rsna-2023-abdominal-trauma-detection/segmentations/*.nii'\n    )\n)\n\n# num of segmentation mask\nlen(segmentation_masks)","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2023-08-01T21:16:58.053633Z","iopub.execute_input":"2023-08-01T21:16:58.05412Z","iopub.status.idle":"2023-08-01T21:16:58.065518Z","shell.execute_reply.started":"2023-08-01T21:16:58.054071Z","shell.execute_reply":"2023-08-01T21:16:58.064093Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#By Innat https://www.kaggle.com/code/ipythonx/cervical-spine-fracture-detection-quick-eda\n\nfor msk in sample(segmentation_masks, 2):\n    m = read_nibabel(msk)\n    multi_dim_plot(m, id=msk.split('/')[4])#Original was [-1]","metadata":{"execution":{"iopub.status.busy":"2023-08-01T21:19:39.553358Z","iopub.execute_input":"2023-08-01T21:19:39.553774Z","iopub.status.idle":"2023-08-01T21:19:52.687704Z","shell.execute_reply.started":"2023-08-01T21:19:39.553743Z","shell.execute_reply":"2023-08-01T21:19:52.686445Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#DICOM\n\n\"The image data, organized with one folder per scan. Expect to see roughly 1,500 scans in the hidden test set. Each image is in the dicom file format.\"\n\n\"Please be aware that the NIFTI files consist of segmentation in the sagittal plane, while the DICOM files are in the axial plane. Please use the NIFTI header information to determine the appropriate orientation such that the DICOM images and segmentation match. Otherwise, you run the risk of having the segmentations flipped in the Z axis and mirrored in the X axis.\"\n\nBy Innat https://www.kaggle.com/code/ipythonx/cervical-spine-fracture-detection-quick-eda","metadata":{}},{"cell_type":"code","source":"dicom_files = glob(\n    \"../input/rsna-2023-abdominal-trauma-detection/train_images/10004/**/*.dcm\"\n)\n\nlen(dicom_files)","metadata":{"execution":{"iopub.status.busy":"2023-08-01T21:25:44.208556Z","iopub.execute_input":"2023-08-01T21:25:44.209153Z","iopub.status.idle":"2023-08-01T21:25:44.667661Z","shell.execute_reply.started":"2023-08-01T21:25:44.209104Z","shell.execute_reply":"2023-08-01T21:25:44.666337Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#Dicom Sample","metadata":{}},{"cell_type":"code","source":"# read_dicom funciton would retrun 2 things.\n# In index 0: dicom.pixel data, index 1: raw read with meta info\nsample_dicom = dicom_files[0]\ntemp_read = read_dicom(sample_dicom)[1]\ntemp_read","metadata":{"execution":{"iopub.status.busy":"2023-08-01T21:27:02.969712Z","iopub.execute_input":"2023-08-01T21:27:02.970214Z","iopub.status.idle":"2023-08-01T21:27:03.015419Z","shell.execute_reply.started":"2023-08-01T21:27:02.97017Z","shell.execute_reply":"2023-08-01T21:27:03.014171Z"},"_kg_hide-output":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#By Innat https://www.kaggle.com/code/ipythonx/cervical-spine-fracture-detection-quick-eda\n\n# read and plot first 64 dicom files\ntemp = [read_dicom(i)[0][None, ...] for i in dicom_files[:64]]\ntemp = np.concatenate(temp, axis=0)\ntemp.shape","metadata":{"execution":{"iopub.status.busy":"2023-08-01T21:27:35.630393Z","iopub.execute_input":"2023-08-01T21:27:35.630865Z","iopub.status.idle":"2023-08-01T21:27:37.353716Z","shell.execute_reply.started":"2023-08-01T21:27:35.630829Z","shell.execute_reply":"2023-08-01T21:27:37.352282Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#By Innat https://www.kaggle.com/code/ipythonx/cervical-spine-fracture-detection-quick-eda\n\nbatch_plot(temp, cmap='jet')","metadata":{"execution":{"iopub.status.busy":"2023-08-01T21:29:40.928777Z","iopub.execute_input":"2023-08-01T21:29:40.929484Z","iopub.status.idle":"2023-08-01T21:29:46.965103Z","shell.execute_reply.started":"2023-08-01T21:29:40.929436Z","shell.execute_reply":"2023-08-01T21:29:46.963916Z"},"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#By Innat https://www.kaggle.com/code/ipythonx/cervical-spine-fracture-detection-quick-eda\n\n# read and plot first 64 dicom files\ntemp = [read_dicom(i)[0][None, ...] for i in dicom_files[-64:]]\ntemp = np.concatenate(temp, axis=0)\ntemp.shape","metadata":{"execution":{"iopub.status.busy":"2023-08-01T21:28:21.253607Z","iopub.execute_input":"2023-08-01T21:28:21.254062Z","iopub.status.idle":"2023-08-01T21:28:23.086741Z","shell.execute_reply.started":"2023-08-01T21:28:21.254025Z","shell.execute_reply":"2023-08-01T21:28:23.085316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#By Innat https://www.kaggle.com/code/ipythonx/cervical-spine-fracture-detection-quick-eda\n\nbatch_plot(temp, cmap='RdPu')","metadata":{"execution":{"iopub.status.busy":"2023-08-01T21:41:00.163399Z","iopub.execute_input":"2023-08-01T21:41:00.164349Z","iopub.status.idle":"2023-08-01T21:41:05.485587Z","shell.execute_reply.started":"2023-08-01T21:41:00.164304Z","shell.execute_reply":"2023-08-01T21:41:05.482675Z"},"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#Finally, We have Nii!!!!","metadata":{}},{"cell_type":"code","source":"# nibabel docs: https://nipy.org/nibabel/nifti_images.html?highlight=nifti\nexample_path = \"../input/rsna-2023-abdominal-trauma-detection/segmentations/10109.nii\"\nexample_segm_mask = nib.load(example_path)\nprint(example_segm_mask.header)","metadata":{"execution":{"iopub.status.busy":"2023-08-01T21:52:27.813579Z","iopub.execute_input":"2023-08-01T21:52:27.814102Z","iopub.status.idle":"2023-08-01T21:52:27.836847Z","shell.execute_reply.started":"2023-08-01T21:52:27.814064Z","shell.execute_reply":"2023-08-01T21:52:27.835617Z"},"_kg_hide-output":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#I have No clue about what's that mask below. Maybe a Kidney?\n\nI still don't know which image correspond to each mask.","metadata":{}},{"cell_type":"code","source":"#Code Breaker https://www.kaggle.com/code/muki2003/display-dicom-and-nifti-format-s\n\nimport nibabel as nib\nimport glob\n\nimage_file = glob.glob(\"../input/rsna-2023-abdominal-trauma-detection/segmentations/*.nii\")\nplt.figure(figsize=(20, 20))\n\nfor i in range(28):\n    ax = plt.subplot(7, 7, i + 1)\n    # specify your nii image path\n    image_path = image_file[i]\n    nii_img = nib.load(image_path).get_fdata()\n    nib_image = nii_img[:,:,10] #Original was 59\n    plt.axis('off')\n    plt.imshow(nib_image)","metadata":{"execution":{"iopub.status.busy":"2023-08-01T22:34:08.406378Z","iopub.execute_input":"2023-08-01T22:34:08.406819Z","iopub.status.idle":"2023-08-01T22:34:50.730337Z","shell.execute_reply.started":"2023-08-01T22:34:08.406784Z","shell.execute_reply":"2023-08-01T22:34:50.729074Z"},"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#Acknowledgements:\n\nRaddar https://www.kaggle.com/code/raddar/convert-dicom-to-np-array-the-correct-way\n\nInnat https://www.kaggle.com/code/ipythonx/cervical-spine-fracture-detection-quick-eda\n\nCode Breaker https://www.kaggle.com/code/muki2003/display-dicom-and-nifti-format-s","metadata":{"execution":{"iopub.status.busy":"2023-08-01T21:31:31.665662Z","iopub.execute_input":"2023-08-01T21:31:31.666197Z","iopub.status.idle":"2023-08-01T21:31:32.508131Z","shell.execute_reply.started":"2023-08-01T21:31:31.666126Z","shell.execute_reply":"2023-08-01T21:31:32.505917Z"}}}]}