{"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":71447,"databundleVersionId":7847298,"sourceType":"competition"}],"dockerImageVersionId":30664,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"#Install necessary libraries\n!pip install pydicom numpy matplotlib Pillow","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-03-03T12:30:56.176103Z","iopub.execute_input":"2024-03-03T12:30:56.176556Z","iopub.status.idle":"2024-03-03T12:31:10.597269Z","shell.execute_reply.started":"2024-03-03T12:30:56.176522Z","shell.execute_reply":"2024-03-03T12:31:10.595802Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pydicom\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\n\ndef window_image(dcm, window_center,window_width, intercept, slope, rescale=True):\n    '''\n    This fucntion came from this notebook https://www.kaggle.com/code/redwankarimsony/ct-scans-dicom-files-windowing-explained\n    If you want to understand more about windowing the referenced notebook is a good read.\n    '''\n    img = dcm.pixel_array\n    img = (img*slope +intercept) #for translation adjustments given in the dicom file. \n    img_min = window_center - window_width//2 #minimum HU level\n    img_max = window_center + window_width//2 #maximum HU level\n    img[img<img_min] = img_min #set img_min for all HU levels less than minimum HU level\n    img[img>img_max] = img_max #set img_max for all HU levels higher than maximum HU level\n    if rescale: \n        img = (img - img_min) / (img_max - img_min)*255.0 \n    return img\n\ndef normalize_image(image):\n    \"\"\"\n    Normalize image to the range [0, 1].\n    \"\"\"\n    image = image - np.min(image)\n    return image / np.max(image)\n\ndef process_and_save_dicom(dcm_path, output_path, window_center=None, window_width=None):\n    \"\"\"\n    Process a DICOM file and save it as a PNG file.\n    \"\"\"\n    dcm = pydicom.dcmread(dcm_path, force= True) # There is a need to use force = True due to anonymization reasons.\n    \n    if window_center is not None and window_width is not None:\n        image = window_image(dcm, window_center, window_width, dcm.RescaleIntercept, dcm.RescaleSlope)\n    else:\n        image = dcm.pixel_array\n\n    # Correct for MONOCHROME1\n    if dcm.PhotometricInterpretation == \"MONOCHROME1\":\n        image = np.invert(image)\n    \n    normalized_image = normalize_image(image)\n    img = Image.fromarray((normalized_image * 255).astype(np.uint8))\n    img.save(output_path)\n    print(f'PNG file saved at {output_path}')\n\nbase_dir = \"/kaggle/input/spr-head-ct-age-prediction-challenge/dataset_jpr_train/dataset_jpr_train\"\noutput_base_dir = \"/kaggle/working//png_files/\"  # Update this path as necessary\n\nfor root_dir in [\"1\", \"2\", \"3\"]:\n    root_path = os.path.join(base_dir, root_dir)\n    print(root_path)\n    for accession_number in os.listdir(root_path):\n        accession_path = os.path.join(root_path, accession_number)\n        for dcm_file in os.listdir(accession_path):\n            dcm_path = os.path.join(accession_path, dcm_file)\n            output_path = os.path.join(output_base_dir, accession_number, os.path.splitext(dcm_file)[0] + '.png')\n            os.makedirs(os.path.dirname(output_path), exist_ok=True)\n            # Example windowing values, adjust as necessary\n            process_and_save_dicom(dcm_path, output_path, window_center=40, window_width=80)\n\n","metadata":{"execution":{"iopub.status.busy":"2024-03-03T12:31:10.600092Z","iopub.execute_input":"2024-03-03T12:31:10.600437Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}