{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":36363,"databundleVersionId":4050810,"sourceType":"competition"},{"sourceId":6304944,"sourceType":"datasetVersion","datasetId":3627104}],"dockerImageVersionId":30527,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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\nfor 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","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install gdcm pylibjpeg pylibjpeg-libjpeg pydicom pipdeptree\n","metadata":{"execution":{"iopub.status.busy":"2023-08-15T05:15:02.6317Z","iopub.execute_input":"2023-08-15T05:15:02.632151Z","iopub.status.idle":"2023-08-15T05:15:20.911017Z","shell.execute_reply.started":"2023-08-15T05:15:02.632114Z","shell.execute_reply":"2023-08-15T05:15:20.909462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pipdeptree\n","metadata":{"execution":{"iopub.status.busy":"2023-08-15T05:15:39.317316Z","iopub.execute_input":"2023-08-15T05:15:39.31774Z","iopub.status.idle":"2023-08-15T05:15:54.721007Z","shell.execute_reply.started":"2023-08-15T05:15:39.317704Z","shell.execute_reply":"2023-08-15T05:15:54.719362Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install --upgrade pydicom\n","metadata":{"execution":{"iopub.status.busy":"2023-08-15T05:16:38.085304Z","iopub.execute_input":"2023-08-15T05:16:38.086506Z","iopub.status.idle":"2023-08-15T05:16:52.187517Z","shell.execute_reply.started":"2023-08-15T05:16:38.086448Z","shell.execute_reply":"2023-08-15T05:16:52.186152Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport pydicom\nimport nibabel as nib\nimport numpy as np\n\ndef dicom_to_single_nii(input_folder, output_folder):\n    # Get a list of DICOM files in the input folder\n    dicom_files = [os.path.join(input_folder, file) for file in os.listdir(input_folder) if file.endswith('.dcm')]\n\n    if not dicom_files:\n        return  # No matching DICOM files found\n\n    # Sort the DICOM files based on image position\n    dicom_files.sort(key=lambda file: pydicom.dcmread(file).ImagePositionPatient[-1])\n\n    # Rest of your conversion code ...\n\n# Specify the root directory containing subfolders with DICOM files\nroot_folder = \"/kaggle/input/rsna-2022-cervical-spine-fracture-detection/train_images\"\n\n# Specify the output folder for the NIfTI images\noutput_folder = \"/kaggle/working/output_nii_images\"\n\n# Specify the path to the text file containing the list of subdirectory names\nsubdirectory_list_path = \"/kaggle/input/train-image-namess/train/subdirectory_list 1.txt\"\n\n# Read the list of subdirectory names from the text file\nwith open(subdirectory_list_path, \"r\") as file:\n    subdirectory_list = file.read().splitlines()\n\n# Iterate over subfolders and convert DICOM slices to NIfTI images for matching subdirectories\nfor subfolder in os.listdir(root_folder):\n    subfolder_path = os.path.join(root_folder, subfolder)\n    if os.path.isdir(subfolder_path) and subfolder in subdirectory_list:\n        dicom_to_single_nii(subfolder_path, output_folder)\n\nprint(\"Conversion completed.\")\n","metadata":{"execution":{"iopub.status.busy":"2023-08-15T05:30:20.288766Z","iopub.execute_input":"2023-08-15T05:30:20.2892Z","iopub.status.idle":"2023-08-15T05:30:20.731175Z","shell.execute_reply.started":"2023-08-15T05:30:20.289168Z","shell.execute_reply":"2023-08-15T05:30:20.72879Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport pydicom\nimport nibabel as nib\nimport numpy as np\nimport pandas as pd\n\ndef dicom_to_single_nii(input_folder, output_folder):\n    # Get a list of DICOM files in the input folder\n    dicom_files = [os.path.join(input_folder, file) for file in os.listdir(input_folder) if file.endswith('.dcm')]\n\n    if not dicom_files:\n        return  # No matching DICOM files found\n\n    # Sort the DICOM files based on image position\n    dicom_files.sort(key=lambda file: pydicom.dcmread(file).ImagePositionPatient[-1])\n\n    # Read the first DICOM file to get image properties\n    ds = pydicom.dcmread(dicom_files[0])\n    pixel_spacing = ds.PixelSpacing\n    slice_thickness = ds.SliceThickness\n\n    # Create the affine matrix\n    affine = np.eye(4)\n    affine[0, 0] = pixel_spacing[1]\n    affine[1, 1] = pixel_spacing[0]\n    affine[2, 2] = slice_thickness\n\n    # Create an empty 3D array to hold the volume\n    volume = np.zeros((ds.Rows, ds.Columns, len(dicom_files)), dtype=ds.pixel_array.dtype)\n\n    # Read and store each DICOM slice\n    for i, dicom_file in enumerate(dicom_files):\n        ds = pydicom.dcmread(dicom_file)\n        volume[:, :, i] = ds.pixel_array\n\n    # Create a NIfTI image from the 3D volume\n    nii_image = nib.Nifti1Image(volume, affine=affine)\n\n    # Save the 3D NIfTI image\n    if not os.path.exists(output_folder):\n        os.makedirs(output_folder)\n    output_nii_path = os.path.join(output_folder, f\"{os.path.basename(input_folder)}.nii.gz\")\n    nib.save(nii_image, output_nii_path)\n\n    print(f\"Converted {len(dicom_files)} DICOM slices to a single NIfTI image: {output_nii_path}\")\n\n# Specify the root directory containing subfolders with DICOM files\nroot_folder = \"/kaggle/input/rsna-2022-cervical-spine-fracture-detection/train_images\"\n\n# Specify the output folder for the NIfTI images\noutput_folder = \"/kaggle/working/output_nii_images\"\n\n# Specify the path to the text file containing the list of subdirectory namesnames\nsubdirectory_list_path = \"/kaggle/input/train-image-namess/train/subdirectory_list 1.txt\"\n\n# Read the list of subdirectory names from the text file\nwith open(subdirectory_list_path, \"r\") as file:\n    subdirectory_list = file.read().splitlines()\n\n# Iterate over subfolders and convert DICOM slices to NIfTI images for matching subdirectories\nfor subfolder in os.listdir(root_folder):\n    subfolder_path = os.path.join(root_folder, subfolder)\n    if os.path.isdir(subfolder_path) and subfolder in subdirectory_list:\n        dicom_to_single_nii(subfolder_path, output_folder)\n\n# Create a ZIP archive of the files\nzip_filename = \"/kaggle/working/output_nii_images.zip\"\nwith zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:\n    for root, _, files in os.walk(output_folder):\n        for file in files:\n            file_path = os.path.join(root, file)\n            zipf.write(file_path, os.path.relpath(file_path, output_folder))\n\nprint(\"Conversion and ZIP creation completed.\")","metadata":{"execution":{"iopub.status.busy":"2023-08-15T05:38:10.244284Z","iopub.execute_input":"2023-08-15T05:38:10.244679Z","iopub.status.idle":"2023-08-15T05:38:12.232692Z","shell.execute_reply.started":"2023-08-15T05:38:10.244646Z","shell.execute_reply":"2023-08-15T05:38:12.230517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install pydicom==2.2.0 nibabel==3.2.1 numpy==1.21.0 gdcm==3.0.10\n","metadata":{"execution":{"iopub.status.busy":"2023-08-15T05:35:16.750204Z","iopub.execute_input":"2023-08-15T05:35:16.75064Z","iopub.status.idle":"2023-08-15T05:35:39.034976Z","shell.execute_reply.started":"2023-08-15T05:35:16.750603Z","shell.execute_reply":"2023-08-15T05:35:39.033812Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install pydicom\n!pip install nibabel\n!pip install numpy\n!pip install gdcm\n","metadata":{"execution":{"iopub.status.busy":"2023-08-15T05:28:09.372627Z","iopub.execute_input":"2023-08-15T05:28:09.373041Z","iopub.status.idle":"2023-08-15T05:29:04.914627Z","shell.execute_reply.started":"2023-08-15T05:28:09.373009Z","shell.execute_reply":"2023-08-15T05:29:04.912911Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pip cache purge","metadata":{"execution":{"iopub.status.busy":"2023-08-15T05:26:58.415996Z","iopub.execute_input":"2023-08-15T05:26:58.416451Z","iopub.status.idle":"2023-08-15T05:27:00.091946Z","shell.execute_reply.started":"2023-08-15T05:26:58.416415Z","shell.execute_reply":"2023-08-15T05:27:00.090465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pip install --upgrade pydicom","metadata":{"execution":{"iopub.status.busy":"2023-08-15T05:24:34.173093Z","iopub.execute_input":"2023-08-15T05:24:34.173544Z","iopub.status.idle":"2023-08-15T05:24:48.172649Z","shell.execute_reply.started":"2023-08-15T05:24:34.173507Z","shell.execute_reply":"2023-08-15T05:24:48.171113Z"},"trusted":true},"execution_count":null,"outputs":[]}]}