{"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":[{"sourceType":"competition","sourceId":13451,"datasetId":654585,"databundleVersionId":1188070},{"sourceType":"datasetVersion","sourceId":10556648,"datasetId":6531339,"databundleVersionId":10889676}],"dockerImageVersionId":30822,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\n\nimport numpy as np \nimport pandas as pd\n\nimport pydicom\nimport matplotlib.pyplot as plt\nimport nibabel as nib\n\nfrom tqdm import tqdm\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nrd = \"../input/rsna-intracranial-hemorrhage-detection/rsna-intracranial-hemorrhage-detection/\"\n\ntrain_df = pd.read_csv(rd + \"stage_2_train.csv\")\nprint(train_df.head())\n\nprint('-'*120)\ntrain_df['subtype'] = train_df.ID.apply(lambda x: x.split('_')[2])\ntrain_df['ID'] = train_df.ID.apply(lambda x: '_'.join(x.split('_')[:2]))\nprint(train_df.shape)\nprint(train_df['Label'].value_counts())\ntrain_df.head()","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-01-23T09:59:08.091724Z","iopub.execute_input":"2025-01-23T09:59:08.092043Z","iopub.status.idle":"2025-01-23T09:59:19.084157Z","shell.execute_reply.started":"2025-01-23T09:59:08.092018Z","shell.execute_reply":"2025-01-23T09:59:19.083129Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_files = rd + \"stage_2_train/\"\nprint(\"Len of dicom files: \", len(os.listdir(train_files)))\nprint(\"Uniq IDs: \", len(train_df.ID.unique()))\nprint(\"Ratio: \", train_df.shape[0] / len(train_df.ID.unique()))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T09:59:19.085364Z","iopub.execute_input":"2025-01-23T09:59:19.085656Z","iopub.status.idle":"2025-01-23T09:59:47.127137Z","shell.execute_reply.started":"2025-01-23T09:59:19.085632Z","shell.execute_reply":"2025-01-23T09:59:47.126213Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Read One Example","metadata":{}},{"cell_type":"code","source":"img = pydicom.dcmread(train_files + 'ID_5c8b5d701.dcm')\nimg","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:00:00.416247Z","iopub.execute_input":"2025-01-23T10:00:00.416628Z","iopub.status.idle":"2025-01-23T10:00:00.446224Z","shell.execute_reply.started":"2025-01-23T10:00:00.416595Z","shell.execute_reply":"2025-01-23T10:00:00.445194Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# https://www.kaggle.com/code/samanesharifi/eda-view-dicom-images-with-correct-windowing","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:00:01.197998Z","iopub.execute_input":"2025-01-23T10:00:01.198401Z","iopub.status.idle":"2025-01-23T10:00:01.202811Z","shell.execute_reply.started":"2025-01-23T10:00:01.198366Z","shell.execute_reply":"2025-01-23T10:00:01.201367Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def window_image(img, window_center,window_width, intercept, slope):\n\n    img = (img*slope +intercept)\n    img_min = window_center - window_width//2\n    img_max = window_center + window_width//2\n    img[img<img_min] = img_min\n    img[img>img_max] = img_max\n    return img \n\ndef get_first_of_dicom_field_as_int(x):\n    #get x[0] as in int is x is a 'pydicom.multival.MultiValue', otherwise get int(x)\n    if type(x) == pydicom.multival.MultiValue:\n        return int(x[0])\n    else:\n        return int(x)\n\ndef get_windowing(data):\n    dicom_fields = [data[('0028','1050')].value, #window center\n                    data[('0028','1051')].value, #window width\n                    data[('0028','1052')].value, #intercept\n                    data[('0028','1053')].value] #slope\n    return [get_first_of_dicom_field_as_int(x) for x in dicom_fields]\n\nwindow_center, window_width, intercept, slope = get_windowing(img)\nprint(window_center , window_width, intercept, slope)\nimg_arr = window_image(img.pixel_array, window_center, window_width, intercept, slope)\nplt.imshow(img_arr, cmap='gray')\nplt.grid(False)\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:00:04.209575Z","iopub.execute_input":"2025-01-23T10:00:04.209903Z","iopub.status.idle":"2025-01-23T10:00:04.528672Z","shell.execute_reply.started":"2025-01-23T10:00:04.209876Z","shell.execute_reply":"2025-01-23T10:00:04.527675Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Slice counts","metadata":{}},{"cell_type":"code","source":"# hs, ws, cs = set(), set(), set()\n# for idx, filename in tqdm(enumerate(os.listdir(train_files)), total=10**3):\n#     img_path = os.path.join(train_files, filename)\n#     img = pydicom.dcmread(img_path).pixel_array\n#     hs.add(img.shape[0])\n#     ws.add(img.shape[1])\n#     if len(img.shape)>2:\n#         cs.add(img.shape[2])\n\n#     if idx==10**3:\n#         break\n\n# print('uniq heights: ', hs)\n# print('uniq widths: ', ws)\n# print('uniq channels: ', cs)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:00:07.960069Z","iopub.execute_input":"2025-01-23T10:00:07.96043Z","iopub.status.idle":"2025-01-23T10:00:07.964829Z","shell.execute_reply.started":"2025-01-23T10:00:07.960403Z","shell.execute_reply":"2025-01-23T10:00:07.963611Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def get_metadata(image_dir):\n\n    labels = [\n        'BitsAllocated', 'BitsStored', 'Columns', 'HighBit', \n        'ImageOrientationPatient_0', 'ImageOrientationPatient_1', 'ImageOrientationPatient_2',\n        'ImageOrientationPatient_3', 'ImageOrientationPatient_4', 'ImageOrientationPatient_5',\n        'ImagePositionPatient_0', 'ImagePositionPatient_1', 'ImagePositionPatient_2',\n        'Modality', 'PatientID', 'PhotometricInterpretation', 'PixelRepresentation',\n        'PixelSpacing_0', 'PixelSpacing_1', 'RescaleIntercept', 'RescaleSlope', 'Rows', 'SOPInstanceUID',\n        'SamplesPerPixel', 'SeriesInstanceUID', 'StudyID', 'StudyInstanceUID', \n        'WindowCenter', 'WindowWidth', 'Image',\n    ]\n\n    data = {l: [] for l in labels}\n    i = 0\n    for image in tqdm(os.listdir(image_dir)):\n        data[\"Image\"].append(image[:-4])\n\n        ds = pydicom.dcmread(os.path.join(image_dir, image))\n\n        for metadata in ds.dir():\n            if metadata != \"PixelData\":\n                metadata_values = getattr(ds, metadata)\n                if type(metadata_values) == pydicom.multival.MultiValue and metadata not in [\"WindowCenter\", \"WindowWidth\"]:\n                    for i, v in enumerate(metadata_values):\n                        data[f\"{metadata}_{i}\"].append(v)\n                else:\n                    if type(metadata_values) == pydicom.multival.MultiValue and metadata in [\"WindowCenter\", \"WindowWidth\"]:\n                        data[metadata].append(metadata_values[0])\n                    else:\n                        data[metadata].append(metadata_values)\n                        \n        i+=1\n\n    # print(data)\n    return pd.DataFrame(data).set_index(\"Image\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:00:08.28245Z","iopub.execute_input":"2025-01-23T10:00:08.282852Z","iopub.status.idle":"2025-01-23T10:00:08.290975Z","shell.execute_reply.started":"2025-01-23T10:00:08.282823Z","shell.execute_reply":"2025-01-23T10:00:08.28996Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df = pd.read_csv(f'{rd}/stage_2_train.csv').drop_duplicates()\ntrain_df['ImageID'] = train_df['ID'].str.slice(stop=12)\ntrain_df['Diagnosis'] = train_df['ID'].str.slice(start=13)\ntrain_labels = train_df.pivot(index=\"ImageID\", columns=\"Diagnosis\", values=\"Label\")\ntrain_labels.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:00:09.686697Z","iopub.execute_input":"2025-01-23T10:00:09.687019Z","iopub.status.idle":"2025-01-23T10:00:25.25677Z","shell.execute_reply.started":"2025-01-23T10:00:09.686994Z","shell.execute_reply":"2025-01-23T10:00:25.255805Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# train_metadata = get_metadata(os.path.join(rd, \"stage_2_train\"))\n# test_metadata = get_metadata(os.path.join(rd, \"stage_2_test\"))\n\n# train_metadata.to_parquet(f'./train_metadata.parquet.gzip', compression='gzip')\n# test_metadata.to_parquet(f'./test_metadata.parquet.gzip', compression='gzip')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:00:25.258021Z","iopub.execute_input":"2025-01-23T10:00:25.258298Z","iopub.status.idle":"2025-01-23T10:00:25.262207Z","shell.execute_reply.started":"2025-01-23T10:00:25.258274Z","shell.execute_reply":"2025-01-23T10:00:25.261094Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"! ls /kaggle/input/rsna19-metadata-zip/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:00:25.264184Z","iopub.execute_input":"2025-01-23T10:00:25.264433Z","iopub.status.idle":"2025-01-23T10:00:25.475018Z","shell.execute_reply.started":"2025-01-23T10:00:25.264411Z","shell.execute_reply":"2025-01-23T10:00:25.473694Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_metadata = pd.read_parquet(f'/kaggle/input/rsna19-metadata-zip/train_metadata.parquet.gzip')\ntest_metadata = pd.read_parquet(f'/kaggle/input/rsna19-metadata-zip/test_metadata.parquet.gzip')\n\ntrain_metadata[\"Dataset\"] = \"train\"\ntest_metadata[\"Dataset\"] = \"test\"\n\ntrain_metadata = train_metadata.join(train_labels)\n\nmetadata = pd.concat([train_metadata, test_metadata], sort=True)\n# metadata = test_metadata #pd.concat([train_metadata, test_metadata], sort=True)\n\nmetadata.sort_values(by=\"ImagePositionPatient_2\", inplace=True, ascending=False)\nmetadata.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:00:25.476661Z","iopub.execute_input":"2025-01-23T10:00:25.477071Z","iopub.status.idle":"2025-01-23T10:00:29.955752Z","shell.execute_reply.started":"2025-01-23T10:00:25.477036Z","shell.execute_reply":"2025-01-23T10:00:29.954792Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"metadata[\"StudyInstanceUID\"].nunique()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:00:29.956673Z","iopub.execute_input":"2025-01-23T10:00:29.957014Z","iopub.status.idle":"2025-01-23T10:00:30.038724Z","shell.execute_reply.started":"2025-01-23T10:00:29.95698Z","shell.execute_reply":"2025-01-23T10:00:30.037672Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def window_img(dcm, width=None, center=None, norm=True):\n    pixels = dcm.pixel_array * dcm.RescaleSlope + dcm.RescaleIntercept\n    \n    # Pad non-square images\n    if pixels.shape[0] != pixels.shape[1]:\n        (a,b) = pixels.shape\n        if a > b:\n            padding = ((0, 0), ((a-b) // 2, (a-b) // 2))\n        else:\n            padding = (((b-a) // 2, (b-a) // 2), (0, 0))\n        pixels = np.pad(pixels, padding, mode='constant', constant_values=0)\n            \n    if not width:\n        width = dcm.WindowWidth\n        if type(width) != pydicom.valuerep.DSfloat:\n            width = width[0]\n    if not center:\n        center = dcm.WindowCenter\n        if type(center) != pydicom.valuerep.DSfloat:\n            center = center[0]\n    lower = center - (width / 2)\n    upper = center + (width / 2)\n    img = np.clip(pixels, lower, upper)\n    \n    if norm:\n        return (img - lower) / (upper - lower)\n    else:\n        return img","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:00:30.039831Z","iopub.execute_input":"2025-01-23T10:00:30.040092Z","iopub.status.idle":"2025-01-23T10:00:30.047322Z","shell.execute_reply.started":"2025-01-23T10:00:30.040069Z","shell.execute_reply":"2025-01-23T10:00:30.046511Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"studies = metadata.groupby(\"StudyInstanceUID\")\nstudies_list = list(studies)\n\nos.makedirs('npy_files', exist_ok=True)\n\nfor i in range(len(studies_list)): #range(1000):\n    \n    study_name, study_df = studies_list[i]\n\n    volume, labels = [], []\n    for index, row in study_df.iterrows():\n        if row[\"Dataset\"] == \"train\":\n            dcm = pydicom.dcmread(os.path.join(rd, \"stage_2_train\", index+\".dcm\"))\n        else:\n            dcm = pydicom.dcmread(os.path.join(rd, \"stage_2_test\", index+\".dcm\"))\n            \n        img = dcm.pixel_array #window_img(dcm, width=80, center=40, norm=False)\n        label = row[[\"any\", \"epidural\", \"intraparenchymal\", \"intraventricular\", \"subarachnoid\", \"subdural\"]]\n        volume.append(img)\n        labels.append(label)\n        \n    volume = np.array(volume)\n    labels = np.array(labels)\n\n    np.save(f'npy_files/{study_name}.npy', volume)\n    np.save(f'npy_files/{study_name}_labels.npy', labels)\n\n    affine = np.eye(4)\n    nifti_img = nib.Nifti1Image(volume, affine)\n    output_file = f\"{study_name}_nifti_file_from_numpy.nii.gz\"  # Replace with desired output file name\n    nib.save(nifti_img, output_file)\n\n    \n    break\n    \n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:00:30.895071Z","iopub.execute_input":"2025-01-23T10:00:30.895426Z","iopub.status.idle":"2025-01-23T10:00:35.119422Z","shell.execute_reply.started":"2025-01-23T10:00:30.895394Z","shell.execute_reply":"2025-01-23T10:00:35.118421Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"i = 100\nstudies = metadata[metadata['Dataset']=='train'].groupby(\"StudyInstanceUID\")\nstudies_list = list(studies)\n\nstudy_name, study_df = studies_list[i]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:00:36.806462Z","iopub.execute_input":"2025-01-23T10:00:36.806853Z","iopub.status.idle":"2025-01-23T10:00:40.48282Z","shell.execute_reply.started":"2025-01-23T10:00:36.806824Z","shell.execute_reply":"2025-01-23T10:00:40.481834Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import shutil\nos.makedirs(study_name, exist_ok=True)\n\nfor index, row in study_df.iterrows():\n    dicom_path = os.path.join(rd, \"stage_2_train\", index+\".dcm\")\n    assert os.path.exists(dicom_path)\n\n    shutil.copy(dicom_path, os.path.join(study_name, index+\".dcm\"))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:00:40.484039Z","iopub.execute_input":"2025-01-23T10:00:40.484405Z","iopub.status.idle":"2025-01-23T10:00:41.361892Z","shell.execute_reply.started":"2025-01-23T10:00:40.484376Z","shell.execute_reply":"2025-01-23T10:00:41.360902Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"! pip install dicom2nifti\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:00:46.017436Z","iopub.execute_input":"2025-01-23T10:00:46.017835Z","iopub.status.idle":"2025-01-23T10:00:53.907199Z","shell.execute_reply.started":"2025-01-23T10:00:46.017805Z","shell.execute_reply":"2025-01-23T10:00:53.906063Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"! dicom2nifti ./ID_010b7f38e0/ ./ -M","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:02:17.208248Z","iopub.execute_input":"2025-01-23T10:02:17.208653Z","iopub.status.idle":"2025-01-23T10:02:18.273838Z","shell.execute_reply.started":"2025-01-23T10:02:17.208618Z","shell.execute_reply":"2025-01-23T10:02:18.27212Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"! ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:02:27.020361Z","iopub.execute_input":"2025-01-23T10:02:27.020862Z","iopub.status.idle":"2025-01-23T10:02:27.226034Z","shell.execute_reply.started":"2025-01-23T10:02:27.020819Z","shell.execute_reply":"2025-01-23T10:02:27.224618Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import dicom2nifti\nimport nibabel as nib\n\ndicom2nifti.convert_directory('./ID_010b7f38e0', \".\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:02:29.541825Z","iopub.execute_input":"2025-01-23T10:02:29.542167Z","iopub.status.idle":"2025-01-23T10:02:29.690622Z","shell.execute_reply.started":"2025-01-23T10:02:29.542142Z","shell.execute_reply":"2025-01-23T10:02:29.689698Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"dicom_directory = study_name\noutput_file = f'{study_name}_nifti/nifti_file.nii.gz'\nos.makedirs(os.path.dirname(output_file), exist_ok=True)\nprint(os.path.dirname(output_file))\n# dicom2nifti.convert_directory(dicom_directory, os.path.dirname(output_file), compression=True, reorient=True)\n\ndicom2nifti.dicom_series_to_nifti([dicom_directory], output_file, reorient_nifti=True)\n\nprint(os.listdir(os.path.dirname(output_file)))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:02:55.222255Z","iopub.execute_input":"2025-01-23T10:02:55.222662Z","iopub.status.idle":"2025-01-23T10:02:55.239631Z","shell.execute_reply.started":"2025-01-23T10:02:55.222626Z","shell.execute_reply":"2025-01-23T10:02:55.238145Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# nifti_image = nib.load(output_file)\n# print(nifti_image.shape)\n# print(nifti_image.header)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T09:02:40.995714Z","iopub.execute_input":"2025-01-23T09:02:40.996189Z","iopub.status.idle":"2025-01-23T09:02:41.001476Z","shell.execute_reply.started":"2025-01-23T09:02:40.996154Z","shell.execute_reply":"2025-01-23T09:02:40.999578Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport numpy as np\nimport nibabel as nib\nimport pydicom\n\n# Define the DICOM folder path\ndicom_folder = \"ID_010b7f38e0\"  # Replace with your DICOM folder\n\n# Load all DICOM files\ndicom_files = [os.path.join(dicom_folder, f) for f in os.listdir(dicom_folder) if f.endswith(\".dcm\")]\ndicom_files.sort()  # Ensure slices are in order\n\n# Read the first DICOM file to get metadata\nfirst_dicom = pydicom.dcmread(dicom_files[0])\npixel_spacing = first_dicom.PixelSpacing  # e.g., [row_spacing, col_spacing]\nslice_thickness = 1.0 #float(first_dicom.SliceThickness)\naffine = np.array([\n    [pixel_spacing[0], 0, 0, 0],\n    [0, pixel_spacing[1], 0, 0],\n    [0, 0, slice_thickness, 0],\n    [0, 0, 0, 1]\n])\n\n# Stack all slices into a 3D NumPy array\nimages = [pydicom.dcmread(f).pixel_array for f in dicom_files]\nvolume = np.stack(images, axis=-1)\n\n# Convert to NIfTI and save\nnifti_img = nib.Nifti1Image(volume, affine)\noutput_file = \"output_file_gpt.nii.gz\"\nnib.save(nifti_img, output_file)\n\nprint(f\"NIfTI file saved as {output_file}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:11:42.761323Z","iopub.execute_input":"2025-01-23T10:11:42.761734Z","iopub.status.idle":"2025-01-23T10:11:43.528654Z","shell.execute_reply.started":"2025-01-23T10:11:42.7617Z","shell.execute_reply":"2025-01-23T10:11:43.527701Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"first_dicom","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-23T10:06:44.199408Z","iopub.execute_input":"2025-01-23T10:06:44.199854Z","iopub.status.idle":"2025-01-23T10:06:44.208416Z","shell.execute_reply.started":"2025-01-23T10:06:44.199821Z","shell.execute_reply":"2025-01-23T10:06:44.207319Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# https://www.kaggle.com/code/amirmohammadparvizi/identify-acute-intracranial-hemorrhage","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-06T12:44:52.562106Z","iopub.execute_input":"2025-01-06T12:44:52.562481Z","iopub.status.idle":"2025-01-06T12:44:52.566432Z","shell.execute_reply.started":"2025-01-06T12:44:52.562455Z","shell.execute_reply":"2025-01-06T12:44:52.565416Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# def correct_dcm(dcm):\n#     \"\"\"\n#     Correct DICOM pixel values.\n#     \"\"\"\n#     x = dcm.pixel_array + 1000\n#     px_mode = 4096\n#     x[x >= px_mode] -= px_mode\n#     dcm.PixelData = x.tobytes()\n#     dcm.RescaleIntercept = -1000\n\n# def window_image(dcm, window_center, window_width):\n#     \"\"\"\n#     Apply specified window level and width to the DICOM image.\n#     \"\"\"\n#     if (dcm.BitsStored == 12) and (dcm.PixelRepresentation == 0) and (int(dcm.RescaleIntercept) > -100):\n#         correct_dcm(dcm)\n    \n#     img = dcm.pixel_array * dcm.RescaleSlope + dcm.RescaleIntercept\n#     img_min = window_center - window_width // 2\n#     img_max = window_center + window_width // 2\n#     img = np.clip(img, img_min, img_max)\n\n#     return img\n\n# def bsb_window(dcm):\n#     \"\"\"\n#     Apply Brain, Subdural, and Soft tissue windowing to the DICOM image.\n#     \"\"\"\n#     brain_img = window_image(dcm, 40, 80)\n#     subdural_img = window_image(dcm, 80, 200)\n#     soft_img = window_image(dcm, 40, 380)\n    \n#     brain_img = (brain_img - 0) / 80\n#     subdural_img = (subdural_img - (-20)) / 200\n#     soft_img = (soft_img - (-150)) / 380\n#     bsb_img = np.array([brain_img, subdural_img, soft_img]).transpose(1, 2, 0)\n\n#     return bsb_img\n\n# plt.subplot(1, 3, 1)\n# plt.imshow(window_image(img, 40, 80), cmap='gray')\n# plt.title('Brain img')\n\n# plt.subplot(1, 3, 2)\n# plt.imshow(window_image(img, 80, 200), cmap='gray')\n# plt.title('Subdural img')\n\n# plt.subplot(1, 3, 3)\n# plt.imshow(window_image(img, 40, 380), cmap='gray')\n# plt.title('Soft img')\n# plt.show()\n\n# plt.figure()\n# plt.imshow(bsb_window(img))\n# plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-06T12:44:52.567474Z","iopub.execute_input":"2025-01-06T12:44:52.567858Z","iopub.status.idle":"2025-01-06T12:44:53.273124Z","shell.execute_reply.started":"2025-01-06T12:44:52.567833Z","shell.execute_reply":"2025-01-06T12:44:53.27184Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# def window_with_correction(dcm, window_center, window_width):\n#     \"\"\"\n#     Apply windowing to DICOM image with correction for specific conditions.\n#     \"\"\"\n#     if (dcm.BitsStored == 12) and (dcm.PixelRepresentation == 0) and (int(dcm.RescaleIntercept) > -100):\n#         correct_dcm(dcm)\n#     img = dcm.pixel_array * dcm.RescaleSlope + dcm.RescaleIntercept\n#     img_min = window_center - window_width // 2\n#     img_max = window_center + window_width // 2\n#     img = np.clip(img, img_min, img_max)\n#     return img\n\n# def window_without_correction(dcm, window_center, window_width):\n#     \"\"\"\n#     Apply windowing to DICOM image without correction.\n#     \"\"\"\n#     img = dcm.pixel_array * dcm.RescaleSlope + dcm.RescaleIntercept\n#     img_min = window_center - window_width // 2\n#     img_max = window_center + window_width // 2\n#     img = np.clip(img, img_min, img_max)\n#     return img\n\n# def window_testing(img, window):\n#     \"\"\"\n#     Apply Brain, Subdural, and Soft tissue windowing to the DICOM image.\n#     \"\"\"\n#     brain_img = window(img, 40, 80)\n#     subdural_img = window(img, 80, 200)\n#     soft_img = window(img, 40, 380)\n    \n#     brain_img = (brain_img - 0) / 80\n#     subdural_img = (subdural_img - (-20)) / 200\n#     soft_img = (soft_img - (-150)) / 380\n#     bsb_img = np.array([brain_img, subdural_img, soft_img]).transpose(1, 2, 0)\n\n#     return bsb_img\n\n\n# # Plot original and corrected images side by side\n# fig, ax = plt.subplots(1, 2)\n# ax[0].imshow(window_testing(img, window_without_correction), cmap='gray')\n# ax[0].set_title(\"Original\")\n# ax[1].imshow(window_testing(img, window_with_correction), cmap='gray')\n# ax[1].set_title(\"Corrected\")\n# plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-06T12:44:53.274597Z","iopub.execute_input":"2025-01-06T12:44:53.274974Z","iopub.status.idle":"2025-01-06T12:44:53.711971Z","shell.execute_reply.started":"2025-01-06T12:44:53.274923Z","shell.execute_reply":"2025-01-06T12:44:53.710745Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}