{"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":71549,"databundleVersionId":8561470,"sourceType":"competition"}],"dockerImageVersionId":30746,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Convert DICOM series into a NIfTI file (= pack 2D image series into one 3D data)","metadata":{}},{"cell_type":"markdown","source":"For 3d approaches, dicom 2d image series are a little bit hard to work with. So this notebook tries to convert them into 3D NIfTI files. \nAfter this conversion, 6295 nii.gz files will be generated. \nFirstly I've tried to utilize a python library called dicom2nifti, but it didn't work well. So I tried to just stack pixel arrays from DICOM series. ","metadata":{}},{"cell_type":"markdown","source":"## What is NIfTI files?\n> The Neuroimaging Informatics Technology Initiative (NIfTI) is an open file format commonly used to store brain imaging data obtained using Magnetic Resonance Imaging methods. \n\nhttps://en.wikipedia.org/wiki/Neuroimaging_Informatics_Technology_Initiative#:~:text=The%20Neuroimaging%20Informatics%20Technology%20Initiative,gz%20%2C%20.hdr%20%2F%20.img","metadata":{}},{"cell_type":"markdown","source":"## Import libs","metadata":{}},{"cell_type":"code","source":"!pip install natsort\n\nimport pydicom\nimport numpy as np\nfrom glob import glob\nimport os\nfrom natsort import natsorted\nimport SimpleITK as sitk\nimport pandas as pd\nimport sys","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-08-18T07:33:00.525830Z","iopub.execute_input":"2024-08-18T07:33:00.526294Z","iopub.status.idle":"2024-08-18T07:33:17.776896Z","shell.execute_reply.started":"2024-08-18T07:33:00.526261Z","shell.execute_reply":"2024-08-18T07:33:17.775776Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Config","metadata":{}},{"cell_type":"code","source":"rd = \"/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification\"\noutput_dir = \"/kaggle/working/niigz\"\nos.makedirs(output_dir, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2024-08-18T07:33:17.779140Z","iopub.execute_input":"2024-08-18T07:33:17.779619Z","iopub.status.idle":"2024-08-18T07:33:17.786959Z","shell.execute_reply.started":"2024-08-18T07:33:17.779587Z","shell.execute_reply":"2024-08-18T07:33:17.785513Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## All conversion","metadata":{}},{"cell_type":"code","source":"df = pd.read_csv(rd+\"/train_series_descriptions.csv\")\n\ncount = 0\ntmp_ipp_z = -sys.float_info.max\nfor row in df.itertuples():\n    dcm_pths = natsorted(glob(rd+f\"/train_images/{row.study_id}/{row.series_id}/*\"))\n    sdesc = row.series_description.replace(' ', '').replace('/', '')\n    if sdesc == 'AxialT2': continue #cannot axial series correctly due to image orientation patient. see https://blog.redbrickai.com/blog-posts/introduction-to-dicom-coordinate\n\n    img_list = []\n    dcm_data = []\n    for pth in dcm_pths:\n        ds = pydicom.dcmread(pth)\n        img = ds.pixel_array\n        spacing = ds['0028', '0030'].value\n        slice_thickness = ds['0018', '0050'].value\n\n        assert tmp_ipp_z < ds['0020', '0032'].value[2], \"slice inconsistent increment\"\n        img_list.append(img)\n\n    print(count, row.study_id, row.series_id)\n\n    vol = np.stack(img_list)[:, ::-1, :].transpose(1, 2, 0)\n    spacing_xyz = [slice_thickness, spacing[0], spacing[1]]\n\n    sitk_img = sitk.GetImageFromArray(vol)\n    sitk_img.SetSpacing(spacing_xyz)\n    sitk.WriteImage(sitk_img, output_dir+f\"/{row.study_id}_{row.series_id}_{sdesc}.nii.gz\")\n\n    count+=1","metadata":{"execution":{"iopub.status.busy":"2024-08-18T07:34:57.603321Z","iopub.execute_input":"2024-08-18T07:34:57.603718Z","iopub.status.idle":"2024-08-18T07:35:12.412876Z","shell.execute_reply.started":"2024-08-18T07:34:57.603686Z","shell.execute_reply":"2024-08-18T07:35:12.411107Z"},"trusted":true},"execution_count":null,"outputs":[]}]}