{"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":"# 0. Imports and paths","metadata":{}},{"cell_type":"code","source":"import os\nfrom fastai.vision.all import *\nimport SimpleITK as sitk\nimport shutil","metadata":{"execution":{"iopub.status.busy":"2022-11-14T11:02:19.466038Z","iopub.execute_input":"2022-11-14T11:02:19.466364Z","iopub.status.idle":"2022-11-14T11:02:19.473328Z","shell.execute_reply.started":"2022-11-14T11:02:19.466333Z","shell.execute_reply":"2022-11-14T11:02:19.472511Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path = Path('../input/../input/rsna-2022-cervical-spine-fracture-detection/train_images')","metadata":{"execution":{"iopub.status.busy":"2022-11-14T11:06:18.227675Z","iopub.execute_input":"2022-11-14T11:06:18.228006Z","iopub.status.idle":"2022-11-14T11:06:18.232773Z","shell.execute_reply.started":"2022-11-14T11:06:18.227976Z","shell.execute_reply":"2022-11-14T11:06:18.231834Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!mkdir t1w_nifti\n!mkdir t1wce_nifti\n!mkdir t2w_nifti\n!mkdir flair_nifti","metadata":{"execution":{"iopub.status.busy":"2022-11-14T11:02:24.814173Z","iopub.execute_input":"2022-11-14T11:02:24.814522Z","iopub.status.idle":"2022-11-14T11:02:28.65079Z","shell.execute_reply.started":"2022-11-14T11:02:24.814488Z","shell.execute_reply":"2022-11-14T11:02:28.649613Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 1. Select 5 random patients ","metadata":{}},{"cell_type":"code","source":"samples = [Path('../input/rsna-2022-cervical-spine-fracture-detection/train_images/1.2.826.0.1.3680043.10001'),\n           Path('../input/rsna-2022-cervical-spine-fracture-detection/train_images/1.2.826.0.1.3680043.10230'),\n           Path('../input/rsna-2022-cervical-spine-fracture-detection/train_images/1.2.826.0.1.3680043.10400'),\n           Path('../input/rsna-2022-cervical-spine-fracture-detection/train_images/1.2.826.0.1.3680043.10449'),\n           Path('../input/rsna-2022-cervical-spine-fracture-detection/train_images/1.2.826.0.1.3680043.10614')]","metadata":{"execution":{"iopub.status.busy":"2022-11-14T12:07:42.298901Z","iopub.execute_input":"2022-11-14T12:07:42.299221Z","iopub.status.idle":"2022-11-14T12:07:42.303981Z","shell.execute_reply.started":"2022-11-14T12:07:42.299191Z","shell.execute_reply":"2022-11-14T12:07:42.302753Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path_train_t2w, path_train_t1wce,path_train_t1w,path_train_flair = [],[],[],[]\nfor each in samples:\n    path_train_t2w.append(each.ls()[0])\n    path_train_t1wce.append(each.ls()[1])\n    path_train_t1w.append(each.ls()[2])\n    path_train_flair.append(each.ls()[3])","metadata":{"execution":{"iopub.status.busy":"2022-11-14T12:07:43.710222Z","iopub.execute_input":"2022-11-14T12:07:43.710644Z","iopub.status.idle":"2022-11-14T12:07:43.973554Z","shell.execute_reply.started":"2022-11-14T12:07:43.710602Z","shell.execute_reply":"2022-11-14T12:07:43.972717Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def dicom2nifti(image_dir, out_dir, save=True):\n    \"given a dicom directory, loads them into single file and can save it as .nii file\"\n    reader = sitk.ImageSeriesReader()\n    reader.LoadPrivateTagsOn()\n    filenamesDICOM = reader.GetGDCMSeriesFileNames(str(image_dir))\n    reader.SetFileNames(filenamesDICOM)\n    img = reader.Execute()\n    img = sitk.Cast(img, sitk.sitkFloat32)\n    \n    if save:\n        sitk.WriteImage(img, f'{out_dir}/{image_dir.parent.name}.nii')\n    else:\n        return img","metadata":{"execution":{"iopub.status.busy":"2022-11-14T12:07:47.569523Z","iopub.execute_input":"2022-11-14T12:07:47.569839Z","iopub.status.idle":"2022-11-14T12:07:47.577383Z","shell.execute_reply.started":"2022-11-14T12:07:47.569811Z","shell.execute_reply":"2022-11-14T12:07:47.57481Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 이미지 nifti파일로 변환","metadata":{}},{"cell_type":"code","source":"for fn in path_train_t1w: dicom2nifti(fn, \"/kaggle/working/t1w_nifti/\")\nfor fn in path_train_t1wce: dicom2nifti(fn, \"/kaggle/working/t1wce_nifti/\")\nfor fn in path_train_t2w: dicom2nifti(fn, \"/kaggle/working/t2w_nifti/\")\nfor fn in path_train_flair: dicom2nifti(fn, \"/kaggle/working/flair_nifti/\")","metadata":{"execution":{"iopub.status.busy":"2022-11-14T12:07:51.17571Z","iopub.execute_input":"2022-11-14T12:07:51.176036Z","iopub.status.idle":"2022-11-14T12:07:51.241054Z","shell.execute_reply.started":"2022-11-14T12:07:51.176006Z","shell.execute_reply":"2022-11-14T12:07:51.239405Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 이미지 확인","metadata":{}},{"cell_type":"code","source":"def get_array(fn):\n    \"opens .nii file and return the array\"\n    img = sitk.ReadImage(str(fn))\n    imgd = sitk.GetArrayFromImage(img)\n    return imgd\n\ndef plot_slice(imgd, sli):\n    \"given an image of shape slices x height x width, plots a slice\"\n    plt.imshow(imgd[sli], cmap='gray')\n    plt.axis('off')\n    \ndef get_array_plot(fn, sli):\n    imgd = get_array(fn)\n    plot_slice(imgd, sli)","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:22:10.479263Z","iopub.execute_input":"2021-09-03T12:22:10.479693Z","iopub.status.idle":"2021-09-03T12:22:10.488392Z","shell.execute_reply.started":"2021-09-03T12:22:10.479656Z","shell.execute_reply":"2021-09-03T12:22:10.487111Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"samp_pat = '00094'","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:22:10.491739Z","iopub.execute_input":"2021-09-03T12:22:10.492281Z","iopub.status.idle":"2021-09-03T12:22:10.504329Z","shell.execute_reply.started":"2021-09-03T12:22:10.492231Z","shell.execute_reply":"2021-09-03T12:22:10.503082Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"get_array_plot(Path(f'./t1w_nifti/{samp_pat}.nii'), 20)","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:22:10.506284Z","iopub.execute_input":"2021-09-03T12:22:10.506754Z","iopub.status.idle":"2021-09-03T12:22:10.745257Z","shell.execute_reply.started":"2021-09-03T12:22:10.506707Z","shell.execute_reply":"2021-09-03T12:22:10.744096Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"get_array_plot(Path(f'./t1wce_nifti/{samp_pat}.nii'), 45)","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:22:10.746944Z","iopub.execute_input":"2021-09-03T12:22:10.74739Z","iopub.status.idle":"2021-09-03T12:22:11.214352Z","shell.execute_reply.started":"2021-09-03T12:22:10.747343Z","shell.execute_reply":"2021-09-03T12:22:11.212965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"get_array_plot(Path(f'./t2w_nifti/{samp_pat}'), 120)","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:22:11.216337Z","iopub.execute_input":"2021-09-03T12:22:11.216811Z","iopub.status.idle":"2021-09-03T12:22:12.412961Z","shell.execute_reply.started":"2021-09-03T12:22:11.216764Z","shell.execute_reply":"2021-09-03T12:22:12.411889Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"get_array_plot(Path(f'./flair_nifti/{samp_pat}'), 80)","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:22:12.414659Z","iopub.execute_input":"2021-09-03T12:22:12.415125Z","iopub.status.idle":"2021-09-03T12:22:12.903613Z","shell.execute_reply.started":"2021-09-03T12:22:12.415076Z","shell.execute_reply":"2021-09-03T12:22:12.902545Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 2. Resample the images using SimpleITK and SIR24 dataset","metadata":{}},{"cell_type":"markdown","source":"### As we can see, for orientations are different across the different modalities. Let's resample using SRI24 as the template. \n### 방향이 다르기 때문에 템플릿으로 다른 데이터셋을 이용해서 resample하는 과정 필요","metadata":{}},{"cell_type":"code","source":"def resample_nifti(image_dir, ref_image, fn, save=True):\n    \"resample using a reference image\"\n\n    image = sitk.ReadImage(str(image_dir), sitk.sitkFloat32)\n    \n    initial_transform = sitk.CenteredTransformInitializer(ref_image, \n                                                          image, \n                                                          sitk.Euler3DTransform(), \n                                                          sitk.CenteredTransformInitializerFilter.GEOMETRY)\n\n    resampler = sitk.ResampleImageFilter()\n    resampler.SetReferenceImage(ref_image)\n    resampler.SetInterpolator(sitk.sitkLinear)\n    resampler.SetTransform(initial_transform)\n    resampler.SetOutputSpacing(ref_image.GetSpacing())\n    resampler.SetSize((ref_image.GetSize()))\n    resampler.SetOutputDirection(ref_image.GetDirection())\n    resampler.SetOutputOrigin(ref_image.GetOrigin())\n    resampler.SetDefaultPixelValue(image.GetPixelIDValue())\n    resamped_image = resampler.Execute(image)\n    \n    if save:\n        sitk.WriteImage(resamped_image, fn)\n\n    return resamped_image","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:22:12.905145Z","iopub.execute_input":"2021-09-03T12:22:12.905518Z","iopub.status.idle":"2021-09-03T12:22:12.915354Z","shell.execute_reply.started":"2021-09-03T12:22:12.905486Z","shell.execute_reply":"2021-09-03T12:22:12.91324Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ref_image = sitk.ReadImage('../input/sri24-dataset/sri24/spgr.nii', sitk.sitkFloat32)","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:22:12.917408Z","iopub.execute_input":"2021-09-03T12:22:12.917859Z","iopub.status.idle":"2021-09-03T12:22:13.1907Z","shell.execute_reply.started":"2021-09-03T12:22:12.917813Z","shell.execute_reply":"2021-09-03T12:22:13.189556Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!mkdir t1w_resample\n!mkdir t1wce_resample\n!mkdir t2w_resample\n!mkdir flair_resample","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:22:13.194397Z","iopub.execute_input":"2021-09-03T12:22:13.19474Z","iopub.status.idle":"2021-09-03T12:22:16.492515Z","shell.execute_reply.started":"2021-09-03T12:22:13.194707Z","shell.execute_reply":"2021-09-03T12:22:16.491106Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for fn in Path(\"./t1w_nifti\").ls():\n    pat_id = str(fn).split('/')[-1].split('.')[0]\n    final_fn = f\"/kaggle/working/t1w_resample/{pat_id}_0001.nii.gz\"\n    resample_nifti(fn, ref_image, final_fn, True)\n    os.remove(str(fn))","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:22:16.49666Z","iopub.execute_input":"2021-09-03T12:22:16.497022Z","iopub.status.idle":"2021-09-03T12:22:21.418302Z","shell.execute_reply.started":"2021-09-03T12:22:16.496984Z","shell.execute_reply":"2021-09-03T12:22:21.417154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for fn in Path(\"./t1wce_nifti\").ls():\n    pat_id = str(fn).split('/')[-1].split('.')[0]\n    final_fn = f\"/kaggle/working/t1wce_resample/{pat_id}_0002.nii.gz\"\n    resample_nifti(fn, ref_image, final_fn, True)\n    os.remove(str(fn))","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:22:21.41986Z","iopub.execute_input":"2021-09-03T12:22:21.420301Z","iopub.status.idle":"2021-09-03T12:22:26.936432Z","shell.execute_reply.started":"2021-09-03T12:22:21.420255Z","shell.execute_reply":"2021-09-03T12:22:26.935299Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for fn in Path(\"./t2w_nifti\").ls():\n    pat_id = str(fn).split('/')[-1].split('.')[0]\n    final_fn = f\"/kaggle/working/t2w_resample/{pat_id}_0003.nii.gz\"\n    resample_nifti(fn, ref_image, final_fn, True)\n    os.remove(str(fn))","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:22:26.937996Z","iopub.execute_input":"2021-09-03T12:22:26.93847Z","iopub.status.idle":"2021-09-03T12:22:34.992728Z","shell.execute_reply.started":"2021-09-03T12:22:26.938421Z","shell.execute_reply":"2021-09-03T12:22:34.991557Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for fn in Path(\"./flair_nifti\").ls():\n    pat_id = str(fn).split('/')[-1].split('.')[0]\n    final_fn = f\"/kaggle/working/flair_resample/{pat_id}_0000.nii.gz\"\n    resample_nifti(fn, ref_image, final_fn, True)\n    os.remove(str(fn))","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:22:34.994484Z","iopub.execute_input":"2021-09-03T12:22:34.994947Z","iopub.status.idle":"2021-09-03T12:22:40.551619Z","shell.execute_reply.started":"2021-09-03T12:22:34.994898Z","shell.execute_reply":"2021-09-03T12:22:40.550469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"get_array_plot(Path(f'/kaggle/working/t1w_resample/{samp_pat}_0001.nii.gz'), 85)","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:22:40.5532Z","iopub.execute_input":"2021-09-03T12:22:40.553621Z","iopub.status.idle":"2021-09-03T12:22:40.829684Z","shell.execute_reply.started":"2021-09-03T12:22:40.553576Z","shell.execute_reply":"2021-09-03T12:22:40.828294Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"get_array_plot(Path(f'/kaggle/working/t1wce_resample/{samp_pat}_0002.nii.gz'), 85)","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:22:40.831503Z","iopub.execute_input":"2021-09-03T12:22:40.831974Z","iopub.status.idle":"2021-09-03T12:22:41.114678Z","shell.execute_reply.started":"2021-09-03T12:22:40.831926Z","shell.execute_reply":"2021-09-03T12:22:41.113335Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"get_array_plot(Path(f'/kaggle/working/t2w_resample/{samp_pat}_0003.nii.gz'), 85)","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:22:41.12046Z","iopub.execute_input":"2021-09-03T12:22:41.120788Z","iopub.status.idle":"2021-09-03T12:22:41.390885Z","shell.execute_reply.started":"2021-09-03T12:22:41.120756Z","shell.execute_reply":"2021-09-03T12:22:41.389349Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"get_array_plot(Path(f'/kaggle/working/flair_resample/{samp_pat}_0000.nii.gz'), 85)","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:22:41.393187Z","iopub.execute_input":"2021-09-03T12:22:41.393653Z","iopub.status.idle":"2021-09-03T12:22:41.677984Z","shell.execute_reply.started":"2021-09-03T12:22:41.393598Z","shell.execute_reply":"2021-09-03T12:22:41.676594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!rm -rf t1w_nifti\n!rm -rf t1wce_nifti\n!rm -rf t2w_nifti\n!rm -rf flair_nifti","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:22:41.679942Z","iopub.execute_input":"2021-09-03T12:22:41.680437Z","iopub.status.idle":"2021-09-03T12:22:45.251039Z","shell.execute_reply.started":"2021-09-03T12:22:41.680389Z","shell.execute_reply":"2021-09-03T12:22:45.249569Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Looks like we have resampled them. If you noticed, we added four digits to the file names. This is because nnUnet (Task01 - Brain Tumour) requires all four modalities \n### nnUnet에 digits 추가 해주는 과정 필요, 우리는 c1-c7까지 있으니까 add 7 digits..?\n\n`0000 - flair, 0001 - T1w, 0002 - T1wce, 0003 - T2w`\n=> \n`0001 - C1, 0002 - C2, 0003 - C3 ...`","metadata":{}},{"cell_type":"markdown","source":"# 3. Git clone and set up nnUnet","metadata":{}},{"cell_type":"markdown","source":"`labels: {'0': 'background',  '1': 'edema', '2': 'non-enhancing tumor', '3': 'enhancing tumour'}` - following is the labels ","metadata":{}},{"cell_type":"code","source":"import os\nbase_dir = '/kaggle/working/'\nos.chdir(base_dir)","metadata":{"execution":{"iopub.status.busy":"2022-11-14T12:20:20.299681Z","iopub.execute_input":"2022-11-14T12:20:20.300009Z","iopub.status.idle":"2022-11-14T12:20:20.304242Z","shell.execute_reply.started":"2022-11-14T12:20:20.29998Z","shell.execute_reply":"2022-11-14T12:20:20.303248Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!git clone https://github.com/MIC-DKFZ/nnUNet.git \n!git clone https://github.com/NVIDIA/apex","metadata":{"execution":{"iopub.status.busy":"2022-11-14T12:20:24.339587Z","iopub.execute_input":"2022-11-14T12:20:24.339912Z","iopub.status.idle":"2022-11-14T12:20:28.595314Z","shell.execute_reply.started":"2022-11-14T12:20:24.339883Z","shell.execute_reply":"2022-11-14T12:20:28.594343Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"respository_dir = os.path.join(base_dir,'nnUNet')\nos.chdir(respository_dir)\n\n!pip install -e .\n#(optional installation)\n!pip install --upgrade git+https://github.com/nanohanno/hiddenlayer.git@bugfix/get_trace_graph#egg=hiddenlayer\n\nos.chdir(base_dir)","metadata":{"execution":{"iopub.status.busy":"2022-11-14T12:20:30.454901Z","iopub.execute_input":"2022-11-14T12:20:30.455244Z","iopub.status.idle":"2022-11-14T12:23:06.176222Z","shell.execute_reply.started":"2022-11-14T12:20:30.455209Z","shell.execute_reply":"2022-11-14T12:23:06.175205Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Note** Restart the notebook","metadata":{}},{"cell_type":"code","source":"#import IPython\n#IPython.Application.instance().kernel.do_shutdown(True)","metadata":{"execution":{"iopub.status.busy":"2022-11-14T12:23:53.840531Z","iopub.execute_input":"2022-11-14T12:23:53.840986Z","iopub.status.idle":"2022-11-14T12:23:53.845519Z","shell.execute_reply.started":"2022-11-14T12:23:53.84094Z","shell.execute_reply":"2022-11-14T12:23:53.844658Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nfrom fastai.vision.all import *\nimport SimpleITK as sitk\nimport shutil\n\nbase_dir = '/kaggle/working/'\nos.chdir(base_dir)","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:23:34.845276Z","iopub.execute_input":"2021-09-03T12:23:34.845722Z","iopub.status.idle":"2021-09-03T12:23:34.856781Z","shell.execute_reply.started":"2021-09-03T12:23:34.845675Z","shell.execute_reply":"2021-09-03T12:23:34.855495Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Dataset Folder Structure","metadata":{}},{"cell_type":"code","source":"def make_if_dont_exist(folder_path,overwrite=False):\n    \"\"\"\n    creates a folder if it does not exists\n    input: \n    folder_path : relative path of the folder which needs to be created\n    over_write :(default: False) if True overwrite the existing folder \n    \"\"\"\n    if os.path.exists(folder_path):\n        \n        if not overwrite:\n            print(f'{folder_path} exists.')\n        else:\n            print(f\"{folder_path} overwritten\")\n            shutil.rmtree(folder_path)\n            os.makedirs(folder_path)\n\n    else:\n        os.makedirs(folder_path)\n        print(f\"{folder_path} created!\")","metadata":{"execution":{"iopub.status.busy":"2022-11-14T12:23:59.597642Z","iopub.execute_input":"2022-11-14T12:23:59.597974Z","iopub.status.idle":"2022-11-14T12:23:59.603516Z","shell.execute_reply.started":"2022-11-14T12:23:59.597945Z","shell.execute_reply":"2022-11-14T12:23:59.602653Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"task_name = 'Task001_Cervical_Spine' #change here for different task name\nnnunet_dir = \"nnUNet/nnunet/nnUNet_raw_data_base/nnUNet_raw_data\"\ntask_folder_name = os.path.join(nnunet_dir,task_name)\ntrain_image_dir = os.path.join(task_folder_name,'imagesTr')\ntrain_label_dir = os.path.join(task_folder_name,'labelsTr')\ntest_dir = os.path.join(task_folder_name,'imagesTs')\nmain_dir = os.path.join(base_dir,'nnUNet/nnunet')","metadata":{"execution":{"iopub.status.busy":"2022-11-14T12:24:01.620396Z","iopub.execute_input":"2022-11-14T12:24:01.620799Z","iopub.status.idle":"2022-11-14T12:24:01.626542Z","shell.execute_reply.started":"2022-11-14T12:24:01.620767Z","shell.execute_reply":"2022-11-14T12:24:01.625308Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"make_if_dont_exist(task_folder_name,overwrite = False)\nmake_if_dont_exist(train_image_dir)\nmake_if_dont_exist(train_label_dir)\nmake_if_dont_exist(test_dir,overwrite= False)\nmake_if_dont_exist(os.path.join(main_dir,'nnunet_trained_models'))","metadata":{"execution":{"iopub.status.busy":"2022-11-14T12:24:05.031405Z","iopub.execute_input":"2022-11-14T12:24:05.03181Z","iopub.status.idle":"2022-11-14T12:24:05.045214Z","shell.execute_reply.started":"2022-11-14T12:24:05.031776Z","shell.execute_reply":"2022-11-14T12:24:05.044257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Environment Veriables","metadata":{}},{"cell_type":"code","source":"os.environ['nnUNet_raw_data_base'] = os.path.join(main_dir,'nnUNet_raw_data_base')\nos.environ['nnUNet_preprocessed'] = os.path.join(main_dir,'preprocessed')\nos.environ['RESULTS_FOLDER'] = os.path.join(main_dir,'nnUNet_trained_models')","metadata":{"execution":{"iopub.status.busy":"2022-11-14T12:24:12.42535Z","iopub.execute_input":"2022-11-14T12:24:12.426061Z","iopub.status.idle":"2022-11-14T12:24:12.43359Z","shell.execute_reply.started":"2022-11-14T12:24:12.426018Z","shell.execute_reply":"2022-11-14T12:24:12.432585Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Download the pretrained model","metadata":{}},{"cell_type":"code","source":"#!nnUNet_print_available_pretrained_models\n!nnUNet_download_pretrained_model Task001_Cervical_Spine","metadata":{"execution":{"iopub.status.busy":"2022-11-14T12:24:25.39904Z","iopub.execute_input":"2022-11-14T12:24:25.399519Z","iopub.status.idle":"2022-11-14T12:24:26.674183Z","shell.execute_reply.started":"2022-11-14T12:24:25.399454Z","shell.execute_reply":"2022-11-14T12:24:26.673202Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 4. Prepare the data as per nnUnet's requirement","metadata":{}},{"cell_type":"markdown","source":"* nnUNet을 사용하기 위해서는 nii.gz파일만 가능","metadata":{}},{"cell_type":"code","source":"path_ts = '/kaggle/working/nnUNet/nnunet/nnUNet_raw_data_base/nnUNet_raw_data/Task001_Cervical_Spine/imagesTs'","metadata":{"execution":{"iopub.status.busy":"2022-11-14T12:24:29.986396Z","iopub.execute_input":"2022-11-14T12:24:29.986956Z","iopub.status.idle":"2022-11-14T12:24:29.993478Z","shell.execute_reply.started":"2022-11-14T12:24:29.986848Z","shell.execute_reply":"2022-11-14T12:24:29.992408Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for fn in Path(\"./t1w_resample\").ls(): \n    pat_id = fn.name.split('.')[0].split('_')[0]\n    shutil.copy(f'/kaggle/working/t1w_resample/{pat_id}_0001.nii.gz', f'{path_ts}')\n    shutil.copy(f'/kaggle/working/t1wce_resample/{pat_id}_0002.nii.gz', f'{path_ts}/{pat_id}_0002.nii.gz')\n    shutil.copy(f'/kaggle/working/t2w_resample/{pat_id}_0003.nii.gz', f'{path_ts}/{pat_id}_0003.nii.gz')\n    shutil.copy(f'/kaggle/working/flair_resample/{pat_id}_0000.nii.gz', f'{path_ts}/{pat_id}_0000.nii.gz')\n    \n    os.remove(f'/kaggle/working/t1w_resample/{pat_id}_0001.nii.gz')\n    os.remove(f'/kaggle/working/t1wce_resample/{pat_id}_0002.nii.gz')\n    os.remove(f'/kaggle/working/t2w_resample/{pat_id}_0003.nii.gz')\n    os.remove(f'/kaggle/working/flair_resample/{pat_id}_0000.nii.gz')","metadata":{"execution":{"iopub.status.busy":"2022-11-14T12:24:31.660047Z","iopub.execute_input":"2022-11-14T12:24:31.660405Z","iopub.status.idle":"2022-11-14T12:24:31.702777Z","shell.execute_reply.started":"2022-11-14T12:24:31.660374Z","shell.execute_reply":"2022-11-14T12:24:31.700524Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 5. Inference - Make Masks","metadata":{}},{"cell_type":"code","source":"result_dir = os.path.join(main_dir,'nnUNet_Prediction_Results',task_name)\nmake_if_dont_exist(result_dir)\n\nteam_name = 'arshath'\n\n#location where you want save your results, will be created if dont exist\nos.chdir(main_dir)\n!nnUNet_predict -i nnUNet_raw_data_base/nnUNet_raw_data/Task001_BrainTumour/imagesTs -o nnUNet_Prediction_Results/Task001_BrainTumour -t 001 -tr nnUNetTrainerV2 -m 3d_fullres --disable_tta \nos.chdir(base_dir)","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:25:07.767955Z","iopub.execute_input":"2021-09-03T12:25:07.768498Z","iopub.status.idle":"2021-09-03T12:29:00.969592Z","shell.execute_reply.started":"2021-09-03T12:25:07.768449Z","shell.execute_reply":"2021-09-03T12:29:00.968291Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Finally let's check the masks","metadata":{}},{"cell_type":"code","source":"import os\nfrom fastai.vision.all import *\nimport SimpleITK as sitk\nimport shutil","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:32:17.772551Z","iopub.execute_input":"2021-09-03T12:32:17.77294Z","iopub.status.idle":"2021-09-03T12:32:19.428623Z","shell.execute_reply.started":"2021-09-03T12:32:17.772906Z","shell.execute_reply":"2021-09-03T12:32:19.427438Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path_ts = '/kaggle/working/nnUNet/nnunet/nnUNet_raw_data_base/nnUNet_raw_data/Task001_BrainTumour/imagesTs'\npath_lbl = '/kaggle/working/nnUNet/nnunet/nnUNet_Prediction_Results/Task001_BrainTumour'\nsamp_pat = '00094'","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:35:17.203472Z","iopub.execute_input":"2021-09-03T12:35:17.203871Z","iopub.status.idle":"2021-09-03T12:35:17.210152Z","shell.execute_reply.started":"2021-09-03T12:35:17.203823Z","shell.execute_reply":"2021-09-03T12:35:17.208917Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_array(fn):\n    \"opens .nii file and return the array\"\n    img = sitk.ReadImage(str(fn))\n    imgd = sitk.GetArrayFromImage(img)\n    return imgd\n\ndef plot_slice(imgd, sli):\n    \"given an image of shape slices x height x width, plots a slice\"\n    plt.imshow(imgd[sli], cmap='gray')\n    plt.axis('off')\n    \ndef get_array_plot(fn, sli):\n    imgd = get_array(fn)\n    plot_slice(imgd, sli)","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:33:46.2891Z","iopub.execute_input":"2021-09-03T12:33:46.28949Z","iopub.status.idle":"2021-09-03T12:33:46.298395Z","shell.execute_reply.started":"2021-09-03T12:33:46.289456Z","shell.execute_reply":"2021-09-03T12:33:46.297259Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"get_array_plot(f'{path_ts}/{samp_pat}_0003.nii.gz', 85)","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:35:42.017339Z","iopub.execute_input":"2021-09-03T12:35:42.017758Z","iopub.status.idle":"2021-09-03T12:35:42.374077Z","shell.execute_reply.started":"2021-09-03T12:35:42.017725Z","shell.execute_reply":"2021-09-03T12:35:42.372563Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"get_array_plot(f'{path_lbl}/{samp_pat}.nii.gz', 85)","metadata":{"execution":{"iopub.status.busy":"2021-09-03T12:35:46.391946Z","iopub.execute_input":"2021-09-03T12:35:46.392382Z","iopub.status.idle":"2021-09-03T12:35:46.517425Z","shell.execute_reply.started":"2021-09-03T12:35:46.392339Z","shell.execute_reply":"2021-09-03T12:35:46.515907Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}