{"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":"# 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\n#for dirname, _, filenames in os.walk('/kaggle/input'):\n#    for filename in filenames:\n#        print(os.path.join(dirname, filename))\n        \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-12T17:41:44.048354Z","iopub.execute_input":"2022-10-12T17:41:44.048811Z","iopub.status.idle":"2022-10-12T17:41:44.05562Z","shell.execute_reply.started":"2022-10-12T17:41:44.048774Z","shell.execute_reply":"2022-10-12T17:41:44.054147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Trying to replicate Sagittal View conversion code for our data\n\n#Library to convert dicom files (raw data) to nifti files\n!pip install dicom2nifti\n\n\nimport pydicom\nimport dicom2nifti\nimport pandas as pd\nimport nibabel as nib\nimport SimpleITK as sitk\nimport matplotlib.pyplot as plt\n\nfrom pydicom.datadict import dictionary_VR","metadata":{"execution":{"iopub.status.busy":"2022-10-12T17:43:12.840323Z","iopub.execute_input":"2022-10-12T17:43:12.840813Z","iopub.status.idle":"2022-10-12T17:43:28.487517Z","shell.execute_reply.started":"2022-10-12T17:43:12.840777Z","shell.execute_reply":"2022-10-12T17:43:28.486252Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Test image is given with patient id, along with all the images that are associated with this patiet\npatient_id = \"1.2.826.0.1.3680043.10449\"\nbase_path = \"../input/rsna-2022-cervical-spine-fracture-detection/train_images/\"\n\nexample_path = f\"{base_path}{patient_id}/1.dcm\"\n\ndcm_example = pydicom.dcmread(example_path)\ndcm_example","metadata":{"execution":{"iopub.status.busy":"2022-10-12T17:45:16.879792Z","iopub.execute_input":"2022-10-12T17:45:16.881007Z","iopub.status.idle":"2022-10-12T17:45:16.913069Z","shell.execute_reply.started":"2022-10-12T17:45:16.880952Z","shell.execute_reply":"2022-10-12T17:45:16.911883Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#The modality entry is (0008, 0060) (DICOM Modalities) and the dictionary entry is \"CS\".\n\n#Looking at the dictionary, unsure how they got this modality entry to dictionary entry conversion???\ndictionary_VR([0x0008, 0x0060])\n\n# But with this info we can add 'CT' scan to the metadata.\n#I understand this as taking \"CS\" as the dictionary entry and changing it to \"CT\" or adding \"CT\" as another option for the modality entry\ndcm_example.add_new([0x0008, 0x0060], \"CS\", \"CT\")\ndcm_example","metadata":{"execution":{"iopub.status.busy":"2022-10-12T17:49:38.976475Z","iopub.execute_input":"2022-10-12T17:49:38.976971Z","iopub.status.idle":"2022-10-12T17:49:38.987064Z","shell.execute_reply.started":"2022-10-12T17:49:38.976933Z","shell.execute_reply":"2022-10-12T17:49:38.985901Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Need somewhere to move the images with new modality information (all from one pation) to a new folder\nexport_dir = \"/kaggle/working/dcm_export\"\n\n# Create export folder for one patient\nos.mkdir(export_dir)","metadata":{"execution":{"iopub.status.busy":"2022-10-12T17:58:59.978908Z","iopub.execute_input":"2022-10-12T17:58:59.97937Z","iopub.status.idle":"2022-10-12T17:59:00.021015Z","shell.execute_reply.started":"2022-10-12T17:58:59.979329Z","shell.execute_reply":"2022-10-12T17:59:00.019827Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#for every image for our test patient we will add a new modality of CT to CS dictionary entry\nimage_number = 1\n\npatient_path = f\"{base_path}{patient_id}/\"\n\nfor filename in os.listdir(patient_path):\n    path = patient_path + str(image_number) + \".dcm\"\n    dcm_example = pydicom.dcmread(path)\n    dcm_example.add_new([0x0008, 0x0060], \"CS\", \"CT\")\n    pydicom.filewriter.write_file(f\"{export_dir}/{image_number}.dcm\", dcm_example, write_like_original=True)\n    image_number += 1\n\nprint(f\"Saved {image_number-1} images\")","metadata":{"execution":{"iopub.status.busy":"2022-10-12T17:59:57.656724Z","iopub.execute_input":"2022-10-12T17:59:57.657156Z","iopub.status.idle":"2022-10-12T17:59:59.932617Z","shell.execute_reply.started":"2022-10-12T17:59:57.657121Z","shell.execute_reply":"2022-10-12T17:59:59.931307Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# With all these images now having a new modality, we must convert them to nifti files for easy display through python\n# Using the SImpleNTK library exported above\nreader = sitk.ImageSeriesReader()\ndicom_names = reader.GetGDCMSeriesFileNames(export_dir)\nreader.SetFileNames(dicom_names)\nimage = reader.Execute()\nimage = sitk.PermuteAxes(image, [2, 1, 0])\n\nsitk.WriteImage(image, f\"{patient_id}.nii.gz\")\n# From https://www.kaggle.com/competitions/rsna-2022-cervical-spine-fracture-detection/discussion/340612\nexample_path_nii = f\"{patient_id}.nii.gz\"\nnii_example = nib.load(example_path_nii)\ndata = nii_example.get_fdata()\n\ndata_transposed = data[:, ::-1, ::-1].transpose(2, 1, 0)\ndata_transposed.shape\n","metadata":{"execution":{"iopub.status.busy":"2022-10-12T18:08:32.542284Z","iopub.execute_input":"2022-10-12T18:08:32.542745Z","iopub.status.idle":"2022-10-12T18:08:47.392978Z","shell.execute_reply.started":"2022-10-12T18:08:32.542709Z","shell.execute_reply":"2022-10-12T18:08:47.391848Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#We have to get the middle slice of all the images, which we can do simply by dividing the # of images by 2\nmiddle_point = int(data_transposed.shape[2] / 2)\nprint(middle_point)\n\nplt.figure(figsize=(10,15))\n\nplt.imshow(data_transposed[middle_point], cmap='binary')\nplt.imshow(data_transposed[middle_point], cmap='bone')","metadata":{"execution":{"iopub.status.busy":"2022-10-12T18:12:30.578564Z","iopub.execute_input":"2022-10-12T18:12:30.579334Z","iopub.status.idle":"2022-10-12T18:12:31.029776Z","shell.execute_reply.started":"2022-10-12T18:12:30.579284Z","shell.execute_reply":"2022-10-12T18:12:31.028699Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import shutil\n\n\n#Lets make this into a function with the inputs being Patient_ID as string\ndef convert_to_sagittaral(patient_id):\n    \n    #Step 1: Get the filepath of the patient\n    base_path = \"../input/rsna-2022-cervical-spine-fracture-detection/train_images/\"\n    patient_path = f\"{base_path}{patient_id}/\"\n    \n    #clear all the files in the dcm_export for now, and add the new dcm files with new modality into it\n    #at some point we will need to store all of them so that we have\n    shutil.rmtree(export_dir)\n    os.mkdir(export_dir)\n    #for f in export_dir:\n    #    os.remove(f)\n        \n    #Step 2: Add CT modality for all the images of our patient's cervical spine\n    image_number = 1\n\n    for filename in os.listdir(patient_path):\n        path = patient_path + str(image_number) + \".dcm\"\n        dcm_example = pydicom.dcmread(path)\n        dcm_example.add_new([0x0008, 0x0060], \"CS\", \"CT\")\n        pydicom.filewriter.write_file(f\"{export_dir}/{image_number}.dcm\", dcm_example, write_like_original=True)\n        image_number += 1\n\n    print(f\"Saved {image_number-1} images\")\n    \n    #Step 3: Convert all DCM files into NFTI files\n    reader = sitk.ImageSeriesReader()\n    dicom_names = reader.GetGDCMSeriesFileNames(export_dir)\n    reader.SetFileNames(dicom_names)\n    image = reader.Execute()\n    image = sitk.PermuteAxes(image, [2, 1, 0])\n    sitk.WriteImage(image, f\"{patient_id}.nii.gz\")\n    example_path_nii = f\"{patient_id}.nii.gz\"\n    nii_example = nib.load(example_path_nii)\n    data = nii_example.get_fdata()\n    data_transposed = data[:, ::-1, ::-1].transpose(2, 1, 0)\n    data_transposed.shape\n    \n    #We have to get the middle slice of all the images, which we can do simply by dividing the # of images by 2\n    middle_point = int(data_transposed.shape[2] / 2)\n    print(middle_point)\n\n    plt.figure(figsize=(10,15))\n    plt.imshow(data_transposed[middle_point], cmap='bone')","metadata":{"execution":{"iopub.status.busy":"2022-10-12T19:21:30.977998Z","iopub.execute_input":"2022-10-12T19:21:30.97845Z","iopub.status.idle":"2022-10-12T19:21:30.990717Z","shell.execute_reply.started":"2022-10-12T19:21:30.9784Z","shell.execute_reply":"2022-10-12T19:21:30.989241Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#testing function\n\nconvert_to_sagittaral('1.2.826.0.1.3680043.10412')","metadata":{"execution":{"iopub.status.busy":"2022-10-12T19:24:29.453784Z","iopub.execute_input":"2022-10-12T19:24:29.45421Z","iopub.status.idle":"2022-10-12T19:25:17.79429Z","shell.execute_reply.started":"2022-10-12T19:24:29.454176Z","shell.execute_reply":"2022-10-12T19:25:17.793147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}}]}