{"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":"!pip install gdcm\n!pip install pylibjpeg\n!pip install pylibjpeg-libjpeg\n!pip install --upgrade pydicom\n!pip install --upgrade pylibjpeg pylibjpeg-libjpeg pylibjpeg-openjpeg\n!pip install pipdeptree\n!pip install pydicom==2.4.2\n!pip install --upgrade nibabel\n!pip install nibabel==3.2.1\n!pip install nibabel numpy scipy\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-09-06T03:33:35.462436Z","iopub.execute_input":"2023-09-06T03:33:35.462839Z","iopub.status.idle":"2023-09-06T03:35:45.036158Z","shell.execute_reply.started":"2023-09-06T03:33:35.462811Z","shell.execute_reply":"2023-09-06T03:35:45.035009Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport shutil\nimport pydicom\nimport nibabel as nib\nimport numpy as np\nimport zipfile\nimport pandas as pd\nfrom scipy.ndimage import zoom\nfrom sklearn.model_selection import train_test_split\n\n\n# Function to resize NIfTI data\ndef resize_nifti(nifti_data, target_shape):\n    factors = (target_shape[0] / nifti_data.shape[0],\n               target_shape[1] / nifti_data.shape[1],\n               target_shape[2] / nifti_data.shape[2])\n    resized_data = zoom(nifti_data, factors, order=3)  # Cubic interpolation (higher quality)\n    return resized_data\n\n# Function to convert DICOM to resized NIfTI\ndef dicom_to_resized_nii(input_folder, output_folder, desired_shape,patientname):\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\n\n    dicom_files.sort(key=lambda file: pydicom.dcmread(file).ImagePositionPatient[-1])\n\n    ds = pydicom.dcmread(dicom_files[0])\n    pixel_spacing = ds.PixelSpacing\n    slice_thickness = ds.SliceThickness\n\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    volume = np.zeros((ds.Rows, ds.Columns, len(dicom_files)), dtype=ds.pixel_array.dtype)\n\n    for i, dicom_file in enumerate(dicom_files):\n        ds = pydicom.dcmread(dicom_file)\n        volume[:, :, i] = ds.pixel_array\n\n    nii_image = nib.Nifti1Image(volume, affine=affine)\n\n    resized_data = resize_nifti(nii_image.get_fdata(), desired_shape)\n    resized_affine = nii_image.affine\n\n    resized_nii_image = nib.Nifti1Image(resized_data, affine=resized_affine)\n\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(patientname)}.nii.gz\")\n    nib.save(resized_nii_image, output_nii_path)\n\n    print(f\"Converted, resized, and saved {len(dicom_files)} DICOM slices to a resized NIfTI image: {output_nii_path}\")\n    return os.path.basename(patientname)\n\nroot_folder = \"/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images\"\noutput_folder = \"/kaggle/working/output_nii_images\"\ndesired_shape = (128,128,128)\n\n# Load or create the CSV file\ncsv_file_path = \"/kaggle/input/abdominal-trauma-records-2/conversion_records.csv\"\nif os.path.exists(csv_file_path):\n    conversion_records = pd.read_csv(csv_file_path)\n    # Save the updated CSV file to kaggle/working directory\n    csv_file_path_new = \"/kaggle/working/conversion_records.csv\"\n    conversion_records.to_csv(csv_file_path_new, index=False)\nelse:\n    conversion_records = pd.DataFrame(columns=[\"patient_id\"])\n\n# Loop through subfolders and convert DICOM to NIfTI\ncount = 0\nfor subfolder in os.listdir(root_folder):\n    subfolder_path = os.path.join(root_folder, subfolder)\n    \n    if os.path.isdir(subfolder_path):\n        for onemore_subfolder in os.listdir(subfolder_path):\n            onemore_subfolder_path = os.path.join(subfolder_path, onemore_subfolder)\n            patient_id = subfolder+\"_\"+onemore_subfolder\n            if subfolder.startswith('1'):\n\n                if os.path.isdir(onemore_subfolder_path) and patient_id not in conversion_records[\"patient_id\"].values:\n                    converted_patient_id = dicom_to_resized_nii(onemore_subfolder_path, output_folder, desired_shape,patient_id)\n                    if converted_patient_id:\n                        conversion_records.loc[len(conversion_records)] = [converted_patient_id]\n                        \n\n# Save the updated CSV file\nconversion_records.to_csv(csv_file_path_new, index=False)\n\n# Create a ZIP file containing the converted NIfTI images\n# zip_filename = \"/kaggle/working/output_nii_images.zip\"\n# with 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#             os.remove(file_path)  # Delete the file after adding to the ZIP folder\n\n# # Close the ZIP file\n# zipf.close()\n\nprint(\"ZIP file closed.\")\n\nprint(\"Conversion, resizing, CSV update, and ZIP creation completed.\")\n","metadata":{},"execution_count":null,"outputs":[]}]}