{"cells":[{"metadata":{},"cell_type":"markdown","source":"<div><div class=\"markdown-converter__text--rendered\"><h1><strong>Hemorrhage Types</strong></h1>\n<p>Hemorrhage in the head (intracranial hemorrhage) is a relatively common condition that has many causes ranging from trauma, stroke, aneurysm, vascular malformations, high blood pressure, illicit drugs and blood clotting disorders.  The neurologic consequences also vary extensively depending upon the size, type of hemorrhage and location ranging from headache to death.  The role of the Radiologist is to detect the hemorrhage, characterize the hemorrhage subtype, its size and to determine if the hemorrhage might be jeopardizing critical areas of the brain that might require immediate surgery. </p>\n<p>While all acute (i.e. new) hemorrhages appear dense (i.e. white) on computed tomography (CT), the primary imaging features that help Radiologists determine the subtype of hemorrhage are the location, shape and proximity to other structures (see table).  </p>\n<p>Intraparenchymal hemorrhage is blood that is located completely within the brain itself; intraventricular or subarachnoid hemorrhage is blood that has leaked into the spaces of the brain that normally contain cerebrospinal fluid (the ventricles or subarachnoid cisterns).  Extra-axial hemorrhages are blood that collects in the tissue coverings that surround the brain (e.g. subdural or epidural subtypes). ee figure.) Patients may exhibit more than one type of cerebral hemorrhage, which c may appear on the same image.  While small hemorrhages are less morbid than large hemorrhages typically, even a small hemorrhage can lead to death because it is an indicator of another type of serious abnormality (e.g. cerebral aneurysm). </p>\n<p><img src=\"https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F603584%2F56162e47358efd77010336a373beb0d2%2Fsubtypes-of-hemorrhage.png?generation=1568657910458946&amp;alt=media\" alt=\"subtypes of hemorrhage\"></p>\n<p><img src=\"https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F603584%2Fda30220341a8c77a9925868023698b8f%2FMeninges-en.png?generation=1566848157664036&amp;alt=media\" alt=\"intracranial diagram\"></p>\n<p>Image credit: By SVG by Mysid, original by SEER Development Team [1], Jmarchn - Vectorized in Inkscape by Mysid, based on work by SEER Development Team, CC BY-SA 3.0, <a href=\"https://commons.wikimedia.org/w/index.php?curid=10485059\" target=\"_blank\">https://commons.wikimedia.org/w/index.php?curid=10485059</a></p></div></div>\n<br/>\n<br/>\n<div>\n    <h3>References : </h3>\n    <ul>\n        <li>https://www.radiologymasterclass.co.uk/tutorials/ct/ct_acute_brain/ct_brain_details</li>\n        <li>https://radiopaedia.org/articles/windowing-ct</li>\n        <li>https://www.slideshare.net/ganesahyogananthem/ct-numbers-window-width-and-window-level</li>\n    </ul>\n</div>"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport cv2\nimport pydicom\nimport os, glob\nimport warnings\nfrom sklearn.preprocessing import MinMaxScaler\nimport seaborn as sns\nwarnings.filterwarnings(\"ignore\")","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"colorcodes = [\"#00876c\"\n,\"#4c9c85\"\n,\"#78b19f\"\n,\"#a0c6b9\"\n,\"#c8dbd5\"\n,\"#f1f1f1\"\n,\"#f1cfce\"\n,\"#eeadad\"\n,\"#e88b8d\"\n,\"#df676e\"\n,\"#d43d51\"]\n\n\ncolorcodes = [\"#003f5c\"\n,\"#2f4b7c\"\n,\"#665191\"\n,\"#a05195\"\n,\"#d45087\"\n,\"#f95d6a\"\n,\"#ff7c43\"\n,\"#ffa600\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(os.listdir(\"/kaggle/input/rsna-intracranial-hemorrhage-detection/\"))\nprint(os.listdir(\"/kaggle/input/rsna-intracranial-hemorrhage-detection/stage_1_test_images\")[0])\ninit_dir_path = \"/kaggle/input/rsna-intracranial-hemorrhage-detection/\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def window_image(img, window_center,window_width, intercept, slope):\n    '''\n        img : dicom.pixel array\n        window center : Window Center/Level center of the CT numbers\n        window width : It is the range of the CT numbers that image contains\n        intercept : It helps to specify the linear transformation of CT images\n        slope : rescale scope is also used to specify the linear transformation of images\n    '''\n    img = (img*slope +intercept) #linear transformation\n    img_min = window_center - window_width//2 #lower grey level\n    img_max = window_center + window_width//2 #upper grey level\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]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data = pd.read_csv(init_dir_path+\"stage_1_train.csv\")\nsmpl = pd.read_csv(init_dir_path+\"stage_1_sample_submission.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_filter = pd.DataFrame(data.ID.str.split(\"_\").tolist(), columns=[\"ID\",\"Number\",\"Class\"])\ndata_filter.ID = data_filter.ID +\"_\"+data_filter.Number\ndata_filter[\"Label\"] = data.Label\n\ndata_filter = data_filter.drop('Number', 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_filter.sample(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_dict_true = {}\ndata_dict_false = {}\nclasses = list(set(data_filter.Class))\nfor name in classes:\n    data_dict_true[name] = np.array((data_filter.Class == name)&(data_filter.Label==1)).astype(int).sum()\n    data_dict_false[name] = np.array((data_filter.Class == name)&(data_filter.Label==0)).astype(int).sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Total Images : \",len(list(set(data_filter.ID))))\nprint(\"Total Classes : \",len(classes))\nprint(\"Total Labels : \",2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(data_dict_true)\nplt.figure(figsize=(10,7))\nplt.bar(list(data_dict_true.keys()),list(data_dict_true.values()), label=\"Label | 1\", color=colorcodes[0])\nplt.grid()\nplt.title(\"True Class Dstribution\")\nplt.ylabel(\"Count\")\nplt.xlabel(\"class\")\nplt.legend()\n_=plt.xticks(rotation=75)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(data_dict_true)\nprint(data_dict_false)\nplt.figure(figsize=(10,7))\nplt.bar(list(data_dict_false.keys()),list(data_dict_false.values()),color=colorcodes[6], label=\"Label | 0\")\nplt.bar(list(data_dict_true.keys()),list(data_dict_true.values()),color=colorcodes[0],bottom=list(data_dict_false.values()), label=\"Label | 1\")\nplt.grid()\nplt.title(\"Class Dstribution\")\nplt.ylabel(\"Count\")\nplt.xlabel(\"class\")\nplt.legend()\n_=plt.xticks(rotation=75)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ds = pydicom.dcmread(\"/kaggle/input/rsna-intracranial-hemorrhage-detection/stage_1_test_images/\"+\"ID_0000ca2f6.dcm\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<div>\n    <h3>Linear Transformation of CT windows (Conversion of <i>Bone to Brain</i> window)</h3>\n    <ul>\n        <li>Window Width(WW) is used to see wide range of CT numbers (or simply window width controls contrast) </li>\n        <li>Window level/center(WL) is center of CT numbers (or simply window level/center controls brightness)  </li>\n        <li>Rescale Intercept and Rescale Slope is used for linear transformation <b>(image*slope + intercept)</b></li>\n        <li>Lower grey level = WL - (WW / 2) </li>\n        <li>Upper grey level = WL + (WW / 2) </li>\n    </ul>\n</div>"},{"metadata":{"trusted":true},"cell_type":"code","source":"image = ds.pixel_array\nwindow_center , window_width, intercept, slope = get_windowing(ds)\nimage_windowed = window_image(image, window_center, window_width, intercept, slope)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<div>\n    <h3>Brain VS Bone CT Windows</h3>\n    <ul>\n        <li>The roll over images show the 'bone window' images at the same level as the 'brain windows'</li>\n        <li>The brain window images provide limited detail of bone structures</li>\n        <li>The bone window images provide no useful detail of brain structure</li>\n        <li>For understanding <i>Hemorrhage Types</i> we need <b>brain windowing</b> images </li>\n        <li>For understanding of <i>fracture or suture</i> <b>bone windowing</b> can be used</li>\n    </ul>\n</div>"},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(25,15))\nplt.subplot(1,2,1)\nplt.title(\"Bone Windowing\")\nplt.axis(\"off\")\nplt.imshow(ds.pixel_array, cmap=plt.cm.bone)\nplt.subplot(1,2,2)\nplt.title(\"Brain Windowing\")\nplt.axis(\"off\")\n_=plt.imshow(image_windowed, cmap=plt.cm.bone)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<div>\n    <h3>Understanding DICOM metadata</h3>\n    <img class=\"cp-img panning\" src=\"https://api.media.atlassian.com/file/3ee878d2-cf3c-47a4-b2bc-f285ed41f1e6/image?mode=full-fit&amp;client=4489e027-dff6-46fe-8dbe-66960db0d2a0&amp;token=eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiI0NDg5ZTAyNy1kZmY2LTQ2ZmUtOGRiZS02Njk2MGRiMGQyYTAiLCJhY2Nlc3MiOnsidXJuOmZpbGVzdG9yZTpmaWxlOjNlZTg3OGQyLWNmM2MtNDdhNC1iMmJjLWYyODVlZDQxZjFlNiI6WyJyZWFkIl19LCJleHAiOjE1NjkxNTEyMDYsIm5iZiI6MTU2OTE0Nzg0Nn0.9sa5c3tVwXldcQE6HYedS1Zc1VMvj1GIHo5UYG3JHzk\" alt=\"iod.jpg\" style=\"width: 604.041px; height: 599px;\">\n    <p>Reference : https://dcm4che.atlassian.net/wiki/spaces/d2/pages/1835038/A+Very+Basic+DICOM+Introduction</p>\n</div>"},{"metadata":{"trusted":true},"cell_type":"code","source":"ds","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<h3>Sample Classes</h3>"},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(25,10))\niterIdx=1\nfor cls in classes:\n    idx = data_filter.Class[(data_filter.Class == cls)&(data_filter.Label==1)].index[260]\n#     print(\"Class : \", cls, \"  ,Index : \",idx,\"  ,ID : \", data_filter.ID[idx])\n    \n    ds_class_wise = pydicom.dcmread(init_dir_path+\"stage_1_train_images/\"+data_filter.ID[idx]+\".dcm\")\n    image = ds_class_wise.pixel_array\n    window_center , window_width, intercept, slope = get_windowing(ds_class_wise)\n    image_windowed = window_image(image, window_center, window_width, intercept, slope)    \n    plt.subplot(1,6,iterIdx)\n    plt.title(cls)\n    plt.axis(\"off\")\n    plt.imshow(image_windowed, cmap=plt.cm.bone)\n#     plt.show()\n    iterIdx+=1","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<H3>Difficult to figure out the images with same distribution</H3>"},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(25,10))\nsubdural_img_ids = data_filter[(data_filter.Class==\"subdural\") & (data_filter.Label==1)]['ID'].iloc[0:5]\nimgs_list = {}\nplt_idx_d=1\nfor name in subdural_img_ids:\n    ds_class_wise = pydicom.dcmread(init_dir_path+\"stage_1_train_images/\"+name+\".dcm\")\n    image = ds_class_wise.pixel_array\n    window_center , window_width, intercept, slope = get_windowing(ds_class_wise)\n    image_windowed = window_image(image, window_center, window_width, intercept, slope)\n    plt.title(\"Subdural Image distributions\")\n    sns.distplot(image_windowed.flatten(), hist=False, label=name)\n    imgs_list[name]=image_windowed\n\nplt.figure(figsize=(25,10))\nfor name in imgs_list:\n    plt.subplot(1,5,plt_idx_d)\n    plt.title(name)\n    plt.imshow(imgs_list[name], cmap=plt.cm.bone)\n    plt.axis('off')\n    \n    plt_idx_d+=1","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<h3>Some images are going out of the box which having high peek at the end needs to figure out how many of them are following this dribution</h3>"},{"metadata":{"trusted":true},"cell_type":"code","source":"plt_idx = 1\nplt.figure(figsize=(25,15))\n\n        \nfor cls in classes:\n    img_name = data_filter[(data_filter.Class == cls)&(data_filter.Label==1)]['ID'][100:106]\n    plt.subplot(3,2,plt_idx)\n    plt.title(cls)\n    for name in img_name:\n        ds_class_wise = pydicom.dcmread(init_dir_path+\"stage_1_train_images/\"+name+\".dcm\")\n        image = ds_class_wise.pixel_array\n        window_center , window_width, intercept, slope = get_windowing(ds_class_wise)\n        image_windowed = window_image(image, window_center, window_width, intercept, slope) \n        minmax = MinMaxScaler(feature_range=(0,1))\n        out = minmax.fit_transform(image_windowed)\n        sns.distplot(out.flatten(), hist=False, label=name)\n    plt_idx+=1","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<H3>Conclusion :</H3>\n<ul>\n    <li>Bone windowing cannot be used in model</li>\n    <li>Brain windowing also maintain some of the feature which Bone is having</li>\n    <li>Some images are not having the expected distribution needs to figure out</li>\n    <li>Deep features have to maintain while making model</li>\n</ul>"},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":1}