{"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":"markdown","source":"## Exploration of data for abdominal trauma detection","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19"}},{"cell_type":"markdown","source":"<div align=\"center\">\n  <h3>Things to do in this EDA</h3>\n</div>","metadata":{"execution":{"iopub.status.busy":"2023-08-10T22:49:32.194916Z","iopub.execute_input":"2023-08-10T22:49:32.195753Z","iopub.status.idle":"2023-08-10T22:49:32.236631Z","shell.execute_reply.started":"2023-08-10T22:49:32.19571Z","shell.execute_reply":"2023-08-10T22:49:32.235093Z"}}},{"cell_type":"markdown","source":"<div align=\"center\">\n    <img src=\"https://media.giphy.com/media/aSZSj0mT8f6tW/giphy.gif\" alt=\"SegmentLocal\" title=\"segment\">\n</div>\n","metadata":{}},{"cell_type":"markdown","source":"1. Load packages\n2. Load data relevant for the tast\n3. Understand the ditribution of the injuries across different organs.\n4. Analyse the information of the pydicom data\n5. Visualise a few CT scan samples.\n6. Check for any patternsin the scans corresponding to specific injuries.","metadata":{}},{"cell_type":"code","source":"from datetime import datetime\ndt_string = datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\") \nprint(f\"Updated {dt_string} GMT\")","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:15.076412Z","iopub.execute_input":"2023-08-13T07:03:15.076855Z","iopub.status.idle":"2023-08-13T07:03:15.090268Z","shell.execute_reply.started":"2023-08-13T07:03:15.076792Z","shell.execute_reply":"2023-08-13T07:03:15.08919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 1. Load packages","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm_notebook\nfrom matplotlib.patches import Rectangle\nimport nibabel as nib\nimport seaborn as sns\nimport pydicom as dcm\n%matplotlib inline\nIS_LOCAL = False\nimport os\n\nPATH = '/kaggle/input/rsna-2023-abdominal-trauma-detection'\nprint(os.listdir(PATH))","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:15.091515Z","iopub.execute_input":"2023-08-13T07:03:15.092441Z","iopub.status.idle":"2023-08-13T07:03:15.853119Z","shell.execute_reply.started":"2023-08-13T07:03:15.09241Z","shell.execute_reply":"2023-08-13T07:03:15.852054Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 2. Load data","metadata":{"execution":{"iopub.status.busy":"2023-08-11T00:03:50.816685Z","iopub.execute_input":"2023-08-11T00:03:50.817599Z","iopub.status.idle":"2023-08-11T00:03:50.825871Z","shell.execute_reply.started":"2023-08-11T00:03:50.817566Z","shell.execute_reply":"2023-08-11T00:03:50.824579Z"}}},{"cell_type":"code","source":"# Loading csv data using pandas\nimage_level_labels = pd.read_csv(PATH+'/image_level_labels.csv')\ntest_series_meta = pd.read_csv(PATH+'/test_series_meta.csv')\ntrain = pd.read_csv(PATH+'/train.csv')\ntrain_series_meta = pd.read_csv(PATH+'/train_series_meta.csv')","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:15.854399Z","iopub.execute_input":"2023-08-13T07:03:15.855344Z","iopub.status.idle":"2023-08-13T07:03:15.892856Z","shell.execute_reply.started":"2023-08-13T07:03:15.855307Z","shell.execute_reply":"2023-08-13T07:03:15.892Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 3. Understand the distribution of the injuries across different organs.","metadata":{"execution":{"iopub.status.busy":"2023-08-10T22:50:10.318161Z","iopub.execute_input":"2023-08-10T22:50:10.318616Z","iopub.status.idle":"2023-08-10T22:50:10.32411Z","shell.execute_reply.started":"2023-08-10T22:50:10.31858Z","shell.execute_reply":"2023-08-10T22:50:10.322726Z"}}},{"cell_type":"code","source":"# Checking the first five values of variable in train data\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:15.895588Z","iopub.execute_input":"2023-08-13T07:03:15.896144Z","iopub.status.idle":"2023-08-13T07:03:15.913478Z","shell.execute_reply.started":"2023-08-13T07:03:15.896095Z","shell.execute_reply":"2023-08-13T07:03:15.91231Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Check the size of the train data\nprint(\"Shape of train dataset\", train.shape)","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:15.914692Z","iopub.execute_input":"2023-08-13T07:03:15.915213Z","iopub.status.idle":"2023-08-13T07:03:15.921126Z","shell.execute_reply.started":"2023-08-13T07:03:15.915181Z","shell.execute_reply":"2023-08-13T07:03:15.919892Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Chekc for missing values in train data \ntrain.isnull().sum().sum()","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:15.922684Z","iopub.execute_input":"2023-08-13T07:03:15.923052Z","iopub.status.idle":"2023-08-13T07:03:15.937064Z","shell.execute_reply.started":"2023-08-13T07:03:15.923023Z","shell.execute_reply":"2023-08-13T07:03:15.935904Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Distribution of binary injuries\ncolumns = [\"bowel_healthy\", \"bowel_injury\", \"extravasation_healthy\", \"extravasation_injury\"]\nfig, axs = plt.subplots(2, 2, figsize = (12, 10))\n\nfor idx, column in enumerate(columns):\n    row = idx // 2\n    col = idx % 2\n    sns.countplot(data = train, x = column, ax = axs[row, col])\n    axs[row, col].set_title(column)\n    \nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:15.939065Z","iopub.execute_input":"2023-08-13T07:03:15.939385Z","iopub.status.idle":"2023-08-13T07:03:16.859097Z","shell.execute_reply.started":"2023-08-13T07:03:15.939357Z","shell.execute_reply":"2023-08-13T07:03:16.858148Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Distribution of multi-level injuries\nfig, axs = plt.subplots(len(['kidney', 'liver', 'spleen']), 3, figsize=(15, 10))\n\nfor idx, organ in enumerate(['kidney', 'liver', 'spleen']):\n    sns.countplot(data=train, x=f\"{organ}_healthy\", ax=axs[idx, 0])\n    axs[idx, 0].set_title(f\"{organ.capitalize()} Healthy\")\n    \n    sns.countplot(data=train, x=f\"{organ}_low\", ax=axs[idx, 1])\n    axs[idx, 1].set_title(f\"{organ.capitalize()} Low Injury\")\n    \n    sns.countplot(data=train, x=f\"{organ}_high\", ax=axs[idx, 2])\n    axs[idx, 2].set_title(f\"{organ.capitalize()} High Injury\")\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:16.860796Z","iopub.execute_input":"2023-08-13T07:03:16.861167Z","iopub.status.idle":"2023-08-13T07:03:18.64664Z","shell.execute_reply.started":"2023-08-13T07:03:16.861136Z","shell.execute_reply":"2023-08-13T07:03:18.645719Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"From the graphs above, target 0 represent unhealthy organs while 1 shows health lungs. The graphs also show that the unhealthy lungs \"0\" showed a high proportion of injuries as compared to the health ones.","metadata":{}},{"cell_type":"code","source":"# Showing the relationship between binary variables and the target \"any_injuries\"\norgans = ['bowel', 'extravasation']\nstatuses = ['healthy', 'injury']\n\nfig, axs = plt.subplots(len(organs), len(statuses), figsize=(15, 10))\n\nfor i, organ in enumerate(organs):\n    for j, status in enumerate(statuses):\n        sns.scatterplot(data=train, x='patient_id', y=f\"{organ}_{status}\", hue='any_injury', ax=axs[i, j], alpha=0.5, s=20)\n        axs[i, j].set_title(f\"{organ.capitalize()} {status.capitalize()}\")\n        axs[i, j].set_ylabel(f\"{organ}_{status}\")\n        axs[i, j].set_xticks([])  # To avoid clutter on the x-axis\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:18.648172Z","iopub.execute_input":"2023-08-13T07:03:18.648778Z","iopub.status.idle":"2023-08-13T07:03:20.56881Z","shell.execute_reply.started":"2023-08-13T07:03:18.648745Z","shell.execute_reply":"2023-08-13T07:03:20.567679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"It's interesting to see that the health organs have unrelated injuries \"0\" while the unhealthy lungs do not show any other injuries \"0\". But when we isolate the data to check the injusries, we see for the figure in the second subplot that the healthy lungs \"1\" do not have any injuries \"1\" while the unhealthy lungs have a mixuture of any injuries \"0\" and the common injuries that probably made them unhealthy. This is also true if you at the multiclass variables below.","metadata":{}},{"cell_type":"code","source":"# Showing the relationship between multi-class variables and the target \"any_injuries\"\norgans = ['kidney', 'liver', 'spleen']\nlevels = ['healthy', 'low', 'high']\n\nfig, axs = plt.subplots(len(organs), len(levels), figsize=(15, 10))\n\nfor i, organ in enumerate(organs):\n    for j, level in enumerate(levels):\n        sns.scatterplot(data=train, x='patient_id', y=f\"{organ}_{level}\", hue='any_injury', ax=axs[i, j], alpha=0.5, s=20)\n        axs[i, j].set_title(f\"{organ.capitalize()} {level.capitalize()}\")\n        axs[i, j].set_ylabel(f\"{organ}_{level}\")\n        axs[i, j].set_xticks([])  # To avoid clutter on the x-axis\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:20.570432Z","iopub.execute_input":"2023-08-13T07:03:20.570768Z","iopub.status.idle":"2023-08-13T07:03:24.726984Z","shell.execute_reply.started":"2023-08-13T07:03:20.570739Z","shell.execute_reply":"2023-08-13T07:03:24.726086Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We can see the presence of some other injuries even in healthy lungs","metadata":{}},{"cell_type":"markdown","source":"### 4. Analyse the information of the pydicom data","metadata":{}},{"cell_type":"code","source":"# Checking the information of a sample in the dicom data file\n\nimage_file = \"/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10169/18334/144.dcm\"\ndicom = dcm.read_file(image_file)\ndicom","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:24.728739Z","iopub.execute_input":"2023-08-13T07:03:24.729109Z","iopub.status.idle":"2023-08-13T07:03:24.748698Z","shell.execute_reply.started":"2023-08-13T07:03:24.729077Z","shell.execute_reply":"2023-08-13T07:03:24.747525Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the .parquet file into a pandas DataFrame\ndicom_tags_df = pd.read_parquet(\"/kaggle/input/rsna-2023-abdominal-trauma-detection/train_dicom_tags.parquet\")\n\n# Display the first few rows\nprint(dicom_tags_df.head())","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:24.750286Z","iopub.execute_input":"2023-08-13T07:03:24.751628Z","iopub.status.idle":"2023-08-13T07:03:29.941775Z","shell.execute_reply.started":"2023-08-13T07:03:24.751581Z","shell.execute_reply":"2023-08-13T07:03:29.940569Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Distribution for BitsAllocated\nbits_allocated_counts = dicom_tags_df['BitsAllocated'].value_counts().sort_index()\n\n# Plotting\nplt.figure(figsize=(10, 6))\nbits_allocated_counts.plot(kind='bar')\nplt.title('Distribution of BitsAllocated')\nplt.xlabel('Bits Allocated')\nplt.ylabel('Number of Images')\nplt.grid(axis='y')\nplt.xticks(rotation = 0)\nplt.show()\n\n# Analyze BitsStored in the same way as above\nbits_stored_counts = dicom_tags_df['BitsStored'].value_counts().sort_index()\n\nplt.figure(figsize=(10, 6))\nbits_stored_counts.plot(kind='bar')\nplt.title('Distribution of BitsStored')\nplt.xlabel('Bits Stored')\nplt.ylabel('Number of Images')\nplt.grid(axis='y')\nplt.xticks(rotation = 0)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:29.947668Z","iopub.execute_input":"2023-08-13T07:03:29.948489Z","iopub.status.idle":"2023-08-13T07:03:30.524793Z","shell.execute_reply.started":"2023-08-13T07:03:29.948427Z","shell.execute_reply":"2023-08-13T07:03:30.523559Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"It seems all images were allocated 16 bits and the bits stored were 12, 13 and 16.","metadata":{}},{"cell_type":"code","source":"# Distribution for ContentDate\n\ncontent_date_counts = dicom_tags_df['ContentDate'].value_counts().sort_index()\n\n# Plotting\nplt.figure(figsize=(15, 6))\ncontent_date_counts.plot(kind='line', marker='o')\nplt.title('Distribution by ContentDate')\nplt.xlabel('Date')\nplt.ylabel('Number of Images')\nplt.xticks(rotation=45)\nplt.grid(axis='y')\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:30.526501Z","iopub.execute_input":"2023-08-13T07:03:30.527238Z","iopub.status.idle":"2023-08-13T07:03:31.153388Z","shell.execute_reply.started":"2023-08-13T07:03:30.527196Z","shell.execute_reply":"2023-08-13T07:03:31.152198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"It seems image collection increased linearly after 21/07/2023.","metadata":{}},{"cell_type":"code","source":"# Check for unique values in specific columns\n\nivn_counts = dicom_tags_df['ImplementationVersionName'].value_counts()\n\nplt.figure(figsize=(12, 6))\nivn_counts.plot(kind='bar')\nplt.xlabel('Implementation Version Name')\nplt.ylabel('Number of Images')\nplt.title('Distribution for ImplementationVersionName')\nplt.xticks(rotation=90)\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:31.15519Z","iopub.execute_input":"2023-08-13T07:03:31.156076Z","iopub.status.idle":"2023-08-13T07:03:31.751867Z","shell.execute_reply.started":"2023-08-13T07:03:31.156033Z","shell.execute_reply":"2023-08-13T07:03:31.750644Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"It seems there is only one unique value in this column but to double check, will check for unique values for this case below.","metadata":{}},{"cell_type":"code","source":"print(dicom_tags_df['ImplementationVersionName'].value_counts())","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:31.753326Z","iopub.execute_input":"2023-08-13T07:03:31.753914Z","iopub.status.idle":"2023-08-13T07:03:31.948478Z","shell.execute_reply.started":"2023-08-13T07:03:31.75388Z","shell.execute_reply":"2023-08-13T07:03:31.947709Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"It is clear that there is only one unique ImplementationVersionName in the dataset, which is \"PYDICOM 2.4.0\", and it appears 1,510,373 times. This patter will be seen even in the other specific columns through the plots below.","metadata":{}},{"cell_type":"code","source":"# Check for unique values in specific columns\n\nivn_counts = dicom_tags_df['TransferSyntaxUID'].value_counts()\n\nplt.figure(figsize=(12, 6))\nivn_counts.plot(kind='bar')\nplt.xlabel('TransferSyntaxUID')\nplt.ylabel('Number of Images')\nplt.title('Distribution for TransferSyntaxUID')\nplt.xticks(rotation=90)\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:31.950439Z","iopub.execute_input":"2023-08-13T07:03:31.951034Z","iopub.status.idle":"2023-08-13T07:03:32.452751Z","shell.execute_reply.started":"2023-08-13T07:03:31.950991Z","shell.execute_reply":"2023-08-13T07:03:32.451734Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Check for unique values in specific columns\n\nivn_counts = dicom_tags_df['MediaStorageSOPClassUID'].value_counts()\n\nplt.figure(figsize=(12, 6))\nivn_counts.plot(kind='bar')\nplt.xlabel('MediaStorageSOPClassUID')\nplt.ylabel('Number of Images')\nplt.title('Distribution for MediaStorageSOPClassUID')\nplt.xticks(rotation=90)\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:32.454199Z","iopub.execute_input":"2023-08-13T07:03:32.454643Z","iopub.status.idle":"2023-08-13T07:03:33.064086Z","shell.execute_reply.started":"2023-08-13T07:03:32.454603Z","shell.execute_reply":"2023-08-13T07:03:33.062819Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 5. Visualize a Few CT Scans","metadata":{}},{"cell_type":"code","source":"# Making a plot of an image showing an organ\n\nimport matplotlib.pyplot as plt\n\n# Extracting the pixel array from the DICOM dataset\nimage_data = dicom.pixel_array\n\n# Display the image data using matplotlib\nplt.figure(figsize=(8, 8))\nplt.imshow(image_data, cmap='gray')\nplt.axis('off')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:33.065689Z","iopub.execute_input":"2023-08-13T07:03:33.066893Z","iopub.status.idle":"2023-08-13T07:03:33.365938Z","shell.execute_reply.started":"2023-08-13T07:03:33.066848Z","shell.execute_reply":"2023-08-13T07:03:33.365116Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"From the meta information given in dicom file, we can see window center and windor width. These two can be used to adjust the brightness and constrast of the images. This can be done using the formula below:\n\n\n$$ Rescaled Pixel Value = \\frac{Original Pixel Value-(Window Center−0.5)}{Window Width} $$\n\nUing this can enable us to see different tissues using windowing.\n\nFor the spleen, window center (WC) can be ranged from 40 - 60 while window width can be ranged from 350 to 400. This information can make sense if you check these values for this organ in the pydicom data. \n\nhttps://kevalnagda.github.io/ct-windowing#:~:text=Window%20settings%3A%20%28W%3A70%2C%20L%3A30%29%20or%20%28W%3A70%2C%20L%3A35%29%20Soft,to%20give%20a%20balance%20between%20contrast%20and%20resolution.","metadata":{}},{"cell_type":"code","source":"# Setting up the windowing funtion to see clearly the tissues of an organ\n\ndef apply_windowing(image, center, width):\n    min_window = center - (width / 2)\n    max_window = center + (width / 2)\n    windowed_image = image.copy()\n    windowed_image[windowed_image < min_window] = min_window\n    windowed_image[windowed_image > max_window] = max_window\n    \n    # Normalize the windowed image to [0, 255] scale for display\n    return ((windowed_image - min_window) / width * 255).astype('uint8')","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:33.367178Z","iopub.execute_input":"2023-08-13T07:03:33.368095Z","iopub.status.idle":"2023-08-13T07:03:33.374632Z","shell.execute_reply.started":"2023-08-13T07:03:33.368063Z","shell.execute_reply":"2023-08-13T07:03:33.373472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Setting up parameters for windowing for checking 5 images\n\nimport os\nimport random\nimport matplotlib.pyplot as plt\nimport pydicom\n\ndef show_dicom_images(directory, n=5):\n    file_paths = [os.path.join(directory, file) for file in os.listdir(directory) if file.endswith('.dcm')]\n    random_paths = random.sample(file_paths, n)\n    \n    fig, axs = plt.subplots(1, n, figsize=(20, 20))\n    \n    for ax, path in zip(axs, random_paths):\n        dicom_data = pydicom.read_file(path)\n        \n        if hasattr(dicom_data, 'WindowCenter'):\n            window_center = dicom_data.WindowCenter\n            if isinstance(window_center, pydicom.multival.MultiValue):\n                window_center = float(window_center[0])\n            else:\n                window_center = float(window_center)\n        else:\n            window_center = 40.0\n        \n        if hasattr(dicom_data, 'WindowWidth'):\n            window_width = dicom_data.WindowWidth\n            if isinstance(window_width, pydicom.multival.MultiValue):\n                window_width = float(window_width[0])\n            else:\n                window_width = float(window_width)\n        else:\n            window_width = 400.0\n        \n        windowed_image = apply_windowing(dicom_data.pixel_array, window_center, window_width)\n        \n        ax.imshow(windowed_image, cmap='gray')\n        ax.axis('off')\n    \n    plt.show()\n\ndirectory = \"/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/10169/18334/\"\nshow_dicom_images(directory)","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:33.376037Z","iopub.execute_input":"2023-08-13T07:03:33.37638Z","iopub.status.idle":"2023-08-13T07:03:34.037516Z","shell.execute_reply.started":"2023-08-13T07:03:33.376352Z","shell.execute_reply":"2023-08-13T07:03:34.036363Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We seen interesting features in the images but, let's also try using the interactive windowing, maybe using that method will enable us to see something even more interesting in the images.","metadata":{}},{"cell_type":"code","source":"# Trying to use a slider inoder to adjust it nicely and see interesting components of an image\n\nimport ipywidgets as widgets\nfrom IPython.display import display\n\n# The function to update and show the image\ndef interactive_windowing(center, width):\n    image_data = dicom.pixel_array\n    \n    # A subplot layout for the 2 images\n    fig, axes = plt.subplots(nrows = 1, ncols = 2, figsize = (10, 5))\n       \n    # You can use the apply_windowing function and imshow as before\n    windowed_image = apply_windowing(dicom.pixel_array, center, width)\n    axes[0].imshow(windowed_image, cmap='gray')\n    axes[0].axis('off')\n    axes[0].set_title('Windowed Image')\n    \n    # Displaying the original image on the first sublot\n    axes[1].imshow(image_data, cmap='gray')\n    axes[1].axis('off')\n    axes[1].set_title('Original Image')\n    \n# Create Interactive sliders\ncenter_slider = widgets.FloatSlider(value=40, min=-100, max=500, step=1, description='Center:')\nwidth_slider = widgets.FloatSlider(value=400, min=0, max=1000, step=1, description='Width:')\nui = widgets.VBox([center_slider, width_slider])\n\n# Show the interactive sliders on top\ndisplay(ui)\nwidgets.interactive_output(interactive_windowing, {'center': center_slider, 'width': width_slider})","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:34.038976Z","iopub.execute_input":"2023-08-13T07:03:34.039394Z","iopub.status.idle":"2023-08-13T07:03:34.397785Z","shell.execute_reply.started":"2023-08-13T07:03:34.039356Z","shell.execute_reply":"2023-08-13T07:03:34.396986Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"With the slider, we can be able to adjust the settings and check for any interesting tissues in the organ. We have also obsevered that the original windowed images shows more clear features than the original one.","metadata":{}},{"cell_type":"markdown","source":"### 6. Check for any patterns in the scans corresponding to specific injuries.","metadata":{}},{"cell_type":"code","source":"# Showing a plot for unhealthy organs\ndef show_dicom_images(data):\n    img_data = list(data.T.to_dict().values())\n    f, ax = plt.subplots(3,3, figsize=(16,18))\n    \n    for i, data_row in enumerate(img_data):\n        patient_dir = os.path.join(\"/kaggle/input/rsna-2023-abdominal-trauma-detection/train_images/\", str(data_row['patient_id']))\n        \n        # For simplicity, just getting the first study directory for each patient.\n        study_dir = os.listdir(patient_dir)[0]  \n        \n        # Getting the first DICOM file in that study directory.\n        dicom_file = os.listdir(os.path.join(patient_dir, study_dir))[0]\n        imagePath = os.path.join(patient_dir, study_dir, dicom_file)\n        \n        data_row_img_data = dcm.read_file(imagePath)\n        Bits_Allocated = data_row_img_data.BitsAllocated\n        Window_Center = data_row_img_data.WindowCenter\n        Window_Width = data_row_img_data.WindowWidth\n        ax[i//3, i%3].imshow(data_row_img_data.pixel_array, cmap=plt.cm.bone)\n        ax[i//3, i%3].axis('off')\n        ax[i//3, i%3].set_title('ID: {}\\nBA: {} WC: {} WW: {}'.format(\n                data_row['patient_id'], Bits_Allocated, Window_Center, Window_Width))\n        plt.subplots_adjust(hspace=0.5, wspace=0.5)\n\n    plt.show()\n\n# Sample usage for injured spleen organs:\nshow_dicom_images(train[train['spleen_low']==0].sample(9))","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:34.399058Z","iopub.execute_input":"2023-08-13T07:03:34.39956Z","iopub.status.idle":"2023-08-13T07:03:37.005498Z","shell.execute_reply.started":"2023-08-13T07:03:34.39953Z","shell.execute_reply":"2023-08-13T07:03:37.004186Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Showing a plot for uninjured spleen organs\n\nshow_dicom_images(train[train['spleen_low']==1].sample(9))","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:37.007038Z","iopub.execute_input":"2023-08-13T07:03:37.007395Z","iopub.status.idle":"2023-08-13T07:03:38.828232Z","shell.execute_reply.started":"2023-08-13T07:03:37.007363Z","shell.execute_reply":"2023-08-13T07:03:38.826989Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Checking the CT scans for other organs","metadata":{}},{"cell_type":"markdown","source":"***Below are images showing healthy and unhealthy organs of kidneys, liver, bowel and extravasation***","metadata":{}},{"cell_type":"code","source":"# showing injured kidney organs\n\nshow_dicom_images(train[train['kidney_low']==0].sample(9))","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:38.829998Z","iopub.execute_input":"2023-08-13T07:03:38.830426Z","iopub.status.idle":"2023-08-13T07:03:40.790665Z","shell.execute_reply.started":"2023-08-13T07:03:38.83039Z","shell.execute_reply":"2023-08-13T07:03:40.789549Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# showing uninjured kidney organs\n\nshow_dicom_images(train[train['kidney_low']==1].sample(9))","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:40.791994Z","iopub.execute_input":"2023-08-13T07:03:40.792319Z","iopub.status.idle":"2023-08-13T07:03:42.746675Z","shell.execute_reply.started":"2023-08-13T07:03:40.79229Z","shell.execute_reply":"2023-08-13T07:03:42.745852Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# showing injured liver organs\n\nshow_dicom_images(train[train['liver_low']==0].sample(9))","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:42.748006Z","iopub.execute_input":"2023-08-13T07:03:42.748519Z","iopub.status.idle":"2023-08-13T07:03:44.841809Z","shell.execute_reply.started":"2023-08-13T07:03:42.748486Z","shell.execute_reply":"2023-08-13T07:03:44.840582Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# showing uninjured liver organs\n\nshow_dicom_images(train[train['liver_low']==1].sample(9))","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:44.843303Z","iopub.execute_input":"2023-08-13T07:03:44.843697Z","iopub.status.idle":"2023-08-13T07:03:47.235464Z","shell.execute_reply.started":"2023-08-13T07:03:44.84366Z","shell.execute_reply":"2023-08-13T07:03:47.23436Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# showing injured bowel organs\n\nshow_dicom_images(train[train['bowel_injury']==0].sample(9))","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:47.237065Z","iopub.execute_input":"2023-08-13T07:03:47.237876Z","iopub.status.idle":"2023-08-13T07:03:49.347473Z","shell.execute_reply.started":"2023-08-13T07:03:47.237824Z","shell.execute_reply":"2023-08-13T07:03:49.346195Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# showing uninjured bowel organs\n\nshow_dicom_images(train[train['bowel_injury']==1].sample(9))","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:49.34904Z","iopub.execute_input":"2023-08-13T07:03:49.349441Z","iopub.status.idle":"2023-08-13T07:03:50.900891Z","shell.execute_reply.started":"2023-08-13T07:03:49.349394Z","shell.execute_reply":"2023-08-13T07:03:50.899837Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# showing injured extravasation organs\n\nshow_dicom_images(train[train['extravasation_injury']==0].sample(9))","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:50.902247Z","iopub.execute_input":"2023-08-13T07:03:50.90259Z","iopub.status.idle":"2023-08-13T07:03:53.132182Z","shell.execute_reply.started":"2023-08-13T07:03:50.902559Z","shell.execute_reply":"2023-08-13T07:03:53.131092Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# showing uninjured extravasation organs\n\nshow_dicom_images(train[train['extravasation_injury']==1].sample(9))","metadata":{"execution":{"iopub.status.busy":"2023-08-13T07:03:53.133565Z","iopub.execute_input":"2023-08-13T07:03:53.133946Z","iopub.status.idle":"2023-08-13T07:03:55.187111Z","shell.execute_reply.started":"2023-08-13T07:03:53.133913Z","shell.execute_reply":"2023-08-13T07:03:55.185892Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"From a laymans perspective, I have observed that most images showing injured organs have a lot of whitish parches than those of uninjured images. Different tissues have different radiodensities free air from a perforated organ may appear as dark or black while blood from internal bleeding may appear as whitish or graish mass.\n\nInjured tissues might appear swollen compared to their usual size and shape. The borders of the organ might appear indistinct, and the tissue might be more \"whitish\" due to fluid accumulation.\n\nHemorrhages or internal bleeding could show up as hyperdense (whitish) areas within an organ or in spaces where there shouldn't be any such appearance.\n\nThis explanation could be the reason why most images showing injured organs have lighter or whitish appearances more that the ininjured ones.","metadata":{}},{"cell_type":"markdown","source":"***Thank you for go going through my notebook, kindly share your suggestions to this work***","metadata":{}}]}