{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":52254,"databundleVersionId":9674523,"sourceType":"competition"},{"sourceId":8336917,"sourceType":"datasetVersion","datasetId":4940845}],"dockerImageVersionId":31040,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import kagglehub\n\n# Download latest version\npath = kagglehub.dataset_download(\"ashery/rsna-2023-abdominal-trauma-processed-dataset\")\n\nprint(\"Path to dataset files:\", path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-18T05:13:42.275818Z","iopub.execute_input":"2025-05-18T05:13:42.276076Z","iopub.status.idle":"2025-05-18T05:13:42.787462Z","shell.execute_reply.started":"2025-05-18T05:13:42.276058Z","shell.execute_reply":"2025-05-18T05:13:42.786743Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Generating 3 views (windows) of images","metadata":{}},{"cell_type":"code","source":"import os\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# -----------------------------\n# Windowing Functions\n# -----------------------------\n\ndef window_image(img, WL, WW):\n    \"\"\"Apply window level (WL) and window width (WW) to image.\"\"\"\n    img = img.astype(np.float32)\n    min_val = WL - WW // 2\n    max_val = WL + WW // 2\n    windowed = np.clip(img, min_val, max_val)\n    windowed = ((windowed - min_val) / (max_val - min_val)) * 255.0\n    return windowed.astype(np.uint8)\n\ndef apply_brain_window(img):\n    return window_image(img, WL=40, WW=80)\n\ndef apply_lung_window(img):\n    return window_image(img, WL=-600, WW=1500)\n\ndef apply_soft_tissue_window(img):\n    return window_image(img, WL=50, WW=400)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-18T05:13:45.298558Z","iopub.execute_input":"2025-05-18T05:13:45.298815Z","iopub.status.idle":"2025-05-18T05:13:45.740257Z","shell.execute_reply.started":"2025-05-18T05:13:45.298797Z","shell.execute_reply":"2025-05-18T05:13:45.739713Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Brain Window; Lung Window; Soft Tissue Window","metadata":{}},{"cell_type":"code","source":"\n# -----------------------------\n# Image Loader\n# -----------------------------\n\ndef load_images_from_folder(folder, max_images):\n    image_paths = []\n    for root, _, files in os.walk(folder):\n        for file in files:\n            if file.lower().endswith('.png'):\n                image_paths.append(os.path.join(root, file))\n    image_paths.sort()  # Optional: consistent order\n    selected_paths = image_paths[:max_images]\n    \n    processed = []\n    for path in selected_paths:\n        img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n        if img is None:\n            continue\n        brain = apply_brain_window(img)\n        lung = apply_lung_window(img)\n        soft = apply_soft_tissue_window(img)\n        processed.append((img, brain, lung, soft))\n    \n    return processed\n\n# -----------------------------\n# Display Function\n# -----------------------------\n\ndef display_xth_image(processed_images, index=0):\n    if index < 0 or index >= len(processed_images):\n        print(f\"Invalid index {index}. Total images processed: {len(processed_images)}\")\n        return\n    original, brain, lung, soft = processed_images[index]\n\n    titles = ['Original', 'Brain Window', 'Lung Window', 'Soft Tissue Window']\n    images = [original, brain, lung, soft]\n\n    fig, axs = plt.subplots(2, 2, figsize=(10, 10))\n    for i, ax in enumerate(axs.flat):\n        ax.imshow(images[i], cmap='gray')\n        ax.set_title(titles[i])\n        ax.axis('off')\n    plt.tight_layout()\n    plt.show()\n\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-18T05:13:52.439465Z","iopub.execute_input":"2025-05-18T05:13:52.440158Z","iopub.status.idle":"2025-05-18T05:13:52.446803Z","shell.execute_reply.started":"2025-05-18T05:13:52.44013Z","shell.execute_reply":"2025-05-18T05:13:52.44619Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# -----------------------------\n# Main Execution\n# -----------------------------\n\nif __name__ == \"__main__\":\n    folder_path = \"/kaggle/input/rsna-2023-abdominal-trauma-processed-dataset/RSNA2023ProcessedImages/RSNA2023ProcessedImages/10004/21057\"\n    x = 5  # Number of images to process\n    display_index = 1  # Index of the image to display (0 to x-1)\n\n    processed_images = load_images_from_folder(folder_path, x)\n    display_xth_image(processed_images, display_index)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-18T05:14:00.395003Z","iopub.execute_input":"2025-05-18T05:14:00.395293Z","iopub.status.idle":"2025-05-18T05:14:01.476378Z","shell.execute_reply.started":"2025-05-18T05:14:00.395271Z","shell.execute_reply":"2025-05-18T05:14:01.475589Z"}},"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},{"cell_type":"markdown","source":"## TEST CODE -  ","metadata":{}},{"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\nimport cv2\nimport pydicom\nimport matplotlib.pyplot as plt\nfrom math import ceil\n\n%matplotlib inline\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\n\nimage_paths = []\nfor index,(dirname, _, filenames) in enumerate(os.walk('/kaggle/input')):\n    for filename in filenames:\n        if filename.endswith(\".dcm\"):\n            ## get dicom image paths\n            path = os.path.join(dirname, filename)\n            #print(path)\n            image_paths.append(path)\n    if index == 9:\n        break\n        \n    \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":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-18T03:50:26.597692Z","iopub.execute_input":"2025-05-18T03:50:26.59817Z","iopub.status.idle":"2025-05-18T03:50:27.231378Z","shell.execute_reply.started":"2025-05-18T03:50:26.598151Z","shell.execute_reply":"2025-05-18T03:50:27.23065Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(image_paths)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-18T03:50:31.996086Z","iopub.execute_input":"2025-05-18T03:50:31.996719Z","iopub.status.idle":"2025-05-18T03:50:32.001547Z","shell.execute_reply.started":"2025-05-18T03:50:31.996697Z","shell.execute_reply":"2025-05-18T03:50:32.000777Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Standardize the Image","metadata":{}},{"cell_type":"code","source":"def standardize_image(dicom_image):\n    pixel_array = dicom_image.pixel_array   \n    \n    if dicom_image.PixelRepresentation == 1:\n        bit_shift = dicom_image.BitsAllocated - dicom_image.BitsStored\n        dtype = pixel_array.dtype \n        pixel_array = (pixel_array << bit_shift).astype(dtype) >>  bit_shift\n    \n    if dicom_image.PhotometricInterpretation == \"MONOCHROME1\":\n        pixel_array = 1 - pixel_array\n    \n    # transform to hounsfield units\n    intercept = dicom_image.RescaleIntercept\n    slope = dicom_image.RescaleSlope\n    pixel_array = pixel_array * slope + intercept\n    return pixel_array","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-18T03:50:39.307586Z","iopub.execute_input":"2025-05-18T03:50:39.307854Z","iopub.status.idle":"2025-05-18T03:50:39.313683Z","shell.execute_reply.started":"2025-05-18T03:50:39.307832Z","shell.execute_reply":"2025-05-18T03:50:39.312328Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Applying Windowing Technique","metadata":{}},{"cell_type":"code","source":"def apply_window(image_stack, window, normalize = True):\n    \n    window_width = window[0]\n    window_center = window[1]\n    img_min = window_center - window_width//2 #minimum HU level\n    img_max = window_center + window_width//2 #maximum HU level\n    img = np.clip(image_stack, img_min, img_max)\n    \n    if normalize:\n        img = (img - img_min) / (img_max - img_min)\n    return img","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-18T03:50:41.642439Z","iopub.execute_input":"2025-05-18T03:50:41.642712Z","iopub.status.idle":"2025-05-18T03:50:41.646825Z","shell.execute_reply.started":"2025-05-18T03:50:41.642693Z","shell.execute_reply":"2025-05-18T03:50:41.646084Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Convert DICOM images to PNG format by applying windowing techniques to highlight specific anatomical features.","metadata":{}},{"cell_type":"code","source":"def dicom_to_png(dicom_image):\n    \"\"\"\n    Read the dicom file and preprocess appropriately.\n    \"\"\"\n    pixel_array = standardize_image(dicom_image)\n    \n    windows = [(2,1),(2048,1),(300,150)]\n    imgs = []\n    for window in windows:\n        windowed_array = apply_window(pixel_array,window, normalize = True)\n        img = (windowed_array * 255).astype(np.uint8)\n        img = cv2.resize(img, (256,256))\n        imgs.append(img)\n    \n    return np.stack(imgs,axis=-1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-18T03:50:44.005927Z","iopub.execute_input":"2025-05-18T03:50:44.006184Z","iopub.status.idle":"2025-05-18T03:50:44.011142Z","shell.execute_reply.started":"2025-05-18T03:50:44.006168Z","shell.execute_reply":"2025-05-18T03:50:44.010318Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Show images before preprocessing","metadata":{}},{"cell_type":"code","source":"num_images = len(image_paths[:9])\nnum_rows = ceil(num_images / 3)\nfig, axes = plt.subplots(num_rows, 3, figsize=(15, 5 * num_rows))\n\nfor i, path in enumerate(image_paths[:9]):\n    dicom_data = pydicom.dcmread(path)\n    img = dicom_data.pixel_array\n    row = i // 3\n    col = i % 3\n    axes[row, col].imshow(img, cmap='gray')\n    axes[row, col].axis('off')\n    axes[row, col].set_title(f\"Image {i+1}\")\n\n#Remove empty subplots\nfor i in range(num_images, num_rows*3):\n    row = i // 3\n    col = i % 3\n    fig.delaxes(axes[row, col])\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-18T03:50:46.329228Z","iopub.execute_input":"2025-05-18T03:50:46.329482Z","iopub.status.idle":"2025-05-18T03:50:47.971726Z","shell.execute_reply.started":"2025-05-18T03:50:46.329463Z","shell.execute_reply":"2025-05-18T03:50:47.970727Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Process 9 sample images and show them","metadata":{}},{"cell_type":"code","source":"num_images = min(len(image_paths), 9)\nnum_rows = (num_images + 2) // 3\nfig, axes = plt.subplots(num_rows, 3, figsize=(15, 5 * num_rows))\n\nfor i, path in enumerate(image_paths[:9]):\n    dicom_data = pydicom.dcmread(path)\n    img = dicom_to_png(dicom_data)\n    row = i // 3\n    col = i % 3\n    axes[row, col].imshow(img, cmap='gray')\n    axes[row, col].axis('off')\n    axes[row, col].set_title(f\"Image {i+1}\")\n\n# Remove empty subplots\nfor i in range(num_images, num_rows*3):\n    row = i // 3\n    col = i % 3\n    fig.delaxes(axes[row, col])\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-18T03:50:51.862323Z","iopub.execute_input":"2025-05-18T03:50:51.862986Z","iopub.status.idle":"2025-05-18T03:50:53.30333Z","shell.execute_reply.started":"2025-05-18T03:50:51.862963Z","shell.execute_reply":"2025-05-18T03:50:53.302378Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}