{"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":"## <div style=\"text-align: center\"> First Impression about this RSNA Intracranial Hemorrhage\n</div>\n<img src=\"https://images.idgesg.net/images/article/2017/09/data-science-certification10-100734865-large.jpg\">\n\n   Bleeding, also called hemorrhage, is the name used to describe blood loss. It can refer to blood loss inside the body, called internal bleeding, or to blood loss outside of the body, called external bleeding.\n\nIn this we are working with 4 types and another any\n\n- 1_epidural\n- intraparenchymal\n- intraventricular\n- subarachnoid\n- subdural\n- any\n\n **I hope this kernel helpful and some <font color=\"red\"><b>UPVOTES</b></font> would be very much appreciated**","metadata":{}},{"cell_type":"markdown","source":"<a id=\"top\"></a> <br>\n## Notebook  Content\n\n1. [What is an intracranial hemorrhage](#1)\n1. [Import](#2)\n1. [Load Data](#3)\n1. [Check images](#4)\n1. [Visualization](#5)\n1. [Working newTable ](#6)\n1. [Visualization of hemorrhage epidural](#7)\n1. [Visualization of hemorrhage Intraparenchymal](#8)\n1. [Visualization of hemorrhage Intraparenchymal](#9)\n1. [Visualization of hemorrhage Subarachnoid](#10)\n1. [Visualization of hemorrhage subdural](#11)\n\n","metadata":{}},{"cell_type":"markdown","source":"**<a id=\"1\"></a> <br>**\n## 1- What is an intracranial hemorrhage","metadata":{}},{"cell_type":"markdown","source":"<img src=\"https://www.googleapis.com/download/storage/v1/b/kaggle-user-content/o/inbox%2F603584%2F56162e47358efd77010336a373beb0d2%2Fsubtypes-of-hemorrhage.png?generation=1568657910458946&alt=media\">","metadata":{}},{"cell_type":"markdown","source":"Intracranial hemorrhage (ICH) refers to acute bleeding inside your skull or brain. It’s a life-threatening emergency. You should go to the emergency room right away or call 911 if you think you or someone you know is experiencing ICH.","metadata":{}},{"cell_type":"markdown","source":"### What are the types of ICH?\n\nThere are four types of ICH:\n\n- epidural hematoma\n- subdural hematoma\n- subarachnoid hemorrhage\n- intracerebral hemorrhage","metadata":{}},{"cell_type":"markdown","source":"### Epidural hematoma\n\n<img src=\" \">\n\nA hematoma is a collection of blood, in a clot or ball, outside of a blood vessel. An epidural hematoma occurs when blood accumulates between your skull and the outermost covering of your brain.\n\nIt typically follows a head injury, and usually with a skull fracture. High-pressure bleeding is a prominent feature. If you have an epidural hematoma, you may briefly lose consciousness and then regain consciousness.","metadata":{}},{"cell_type":"markdown","source":"### Subdural hematoma\n\nA subdural hematoma is a collection of blood on the surface of your brain.\n\nIt’s typically the result of your head moving rapidly forward and stopping, such as in a car accident. However, it could also suggest abuse in children. This is the same type of movement a child experiences when being shaken.\n\nA subdural hematoma is more common than other ICHs in older people and people with history of heavy alcohol use.","metadata":{}},{"cell_type":"markdown","source":"### Intracerebral hemorrhage\nIntracerebral hemorrhage is when there’s bleeding inside of your brain. This is the most common type of ICH that occurs with a stroke. It’s not usually the result of injury.\n\nA prominent warning sign is the sudden onset of neurological deficit. This is a problem with your brain’s functioning. The symptoms progress over minutes to hours. They include:\n\n- headache\n- difficulty speaking\n- nausea\n- vomiting\n- decreased consciousness\n- weakness in one part of the body\n- elevated blood pressure","metadata":{}},{"cell_type":"markdown","source":"**<a id=\"2\"></a> <br>**\n## 2- Import","metadata":{}},{"cell_type":"code","source":"import glob, pylab, pandas as pd\nimport pydicom, numpy as np\nfrom os import listdir\nfrom os.path import isfile, join\nimport matplotlib.pylab as plt\nimport os\nimport seaborn as sns\n\n","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","execution":{"iopub.status.busy":"2022-12-05T15:33:39.00849Z","iopub.execute_input":"2022-12-05T15:33:39.008892Z","iopub.status.idle":"2022-12-05T15:33:39.014123Z","shell.execute_reply.started":"2022-12-05T15:33:39.008819Z","shell.execute_reply":"2022-12-05T15:33:39.013189Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras import layers\nfrom keras.applications import DenseNet121\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import Callback, ModelCheckpoint\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.optimizers import Adam\nfrom tqdm import tqdm","metadata":{"execution":{"iopub.status.busy":"2022-12-05T15:33:39.018834Z","iopub.execute_input":"2022-12-05T15:33:39.019097Z","iopub.status.idle":"2022-12-05T15:33:39.025534Z","shell.execute_reply.started":"2022-12-05T15:33:39.019049Z","shell.execute_reply":"2022-12-05T15:33:39.024717Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls ../input","metadata":{"execution":{"iopub.status.busy":"2022-12-05T15:33:39.027173Z","iopub.execute_input":"2022-12-05T15:33:39.027615Z","iopub.status.idle":"2022-12-05T15:33:39.984827Z","shell.execute_reply.started":"2022-12-05T15:33:39.027566Z","shell.execute_reply":"2022-12-05T15:33:39.98394Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"3\"></a> <br>\n## 3- Load Data\n\n**stage_1_train.csv** - the training set. Contains Ids and target information.\n**stage_1_sample_submission.csv** - a sample submission file in the correct format. Contains Ids for the test set.\n\n\nStage 1 Images - **stage_1_train_images.zip** and **stage_1_test_images.zip**\n\n- images for the current stage. Filenames are also patient names.\n\n","metadata":{}},{"cell_type":"code","source":"train = pd.read_csv('../input/rsna-intracranial-hemorrhage-detection/rsna-intracranial-hemorrhage-detection/stage_2_train.csv')\n","metadata":{"execution":{"iopub.status.busy":"2022-12-05T15:33:39.988095Z","iopub.execute_input":"2022-12-05T15:33:39.988631Z","iopub.status.idle":"2022-12-05T15:33:43.060238Z","shell.execute_reply.started":"2022-12-05T15:33:39.988575Z","shell.execute_reply":"2022-12-05T15:33:43.059381Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head(10)","metadata":{"execution":{"iopub.status.busy":"2022-12-05T15:33:43.062304Z","iopub.execute_input":"2022-12-05T15:33:43.062624Z","iopub.status.idle":"2022-12-05T15:33:43.084675Z","shell.execute_reply.started":"2022-12-05T15:33:43.062576Z","shell.execute_reply":"2022-12-05T15:33:43.083932Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.shape\n","metadata":{"execution":{"iopub.status.busy":"2022-12-05T15:33:43.086417Z","iopub.execute_input":"2022-12-05T15:33:43.086846Z","iopub.status.idle":"2022-12-05T15:33:43.092301Z","shell.execute_reply.started":"2022-12-05T15:33:43.086661Z","shell.execute_reply":"2022-12-05T15:33:43.091394Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"newtable = train.copy()","metadata":{"execution":{"iopub.status.busy":"2022-12-05T15:33:43.093939Z","iopub.execute_input":"2022-12-05T15:33:43.094479Z","iopub.status.idle":"2022-12-05T15:33:43.243941Z","shell.execute_reply.started":"2022-12-05T15:33:43.094193Z","shell.execute_reply":"2022-12-05T15:33:43.243043Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.Label.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2022-12-05T15:33:43.245428Z","iopub.execute_input":"2022-12-05T15:33:43.245907Z","iopub.status.idle":"2022-12-05T15:33:43.263256Z","shell.execute_reply.started":"2022-12-05T15:33:43.245704Z","shell.execute_reply":"2022-12-05T15:33:43.262496Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Images Example\ntrain_images_dir = '../input/rsna-intracranial-hemorrhage-detection/rsna-intracranial-hemorrhage-detection/stage_2_train/'\ntrain_images = [f for f in listdir(train_images_dir) if isfile(join(train_images_dir, f))]\ntest_images_dir = '../input/rsna-intracranial-hemorrhage-detection/rsna-intracranial-hemorrhage-detection/stage_2_test/'\ntest_images = [f for f in listdir(test_images_dir) if isfile(join(test_images_dir, f))]\nprint('5 Training images', train_images[:5]) # Print the first 5","metadata":{"execution":{"iopub.status.busy":"2022-12-05T15:33:43.264494Z","iopub.execute_input":"2022-12-05T15:33:43.264955Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Total File sizes')\nfor f in os.listdir('../input/rsna-intracranial-hemorrhage-detection/rsna-intracranial-hemorrhage-detection'):\n    if 'zip' not in f:\n        print(f.ljust(30) + str(round(os.path.getsize('../input/rsna-intracranial-hemorrhage-detection/rsna-intracranial-hemorrhage-detection/' + f) / 1000000, 2)) + 'MB')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Number of train images:', len(train_images))\nprint('Number of test images:', len(test_images))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"4\"></a> <br>\n## 4- Check images","metadata":{}},{"cell_type":"markdown","source":"## Overview of DICOM files and medical images\nMedical images are stored in a special format known as DICOM files (*.dcm). They contain a combination of header metadata as well as underlying raw image arrays for pixel data. In Python, one popular library to access and manipulate DICOM files is the pydicom module. To use the pydicom library, first find the DICOM file for a given patientId by simply looking for the matching file in the stage_1_train_images/ folder, and the use the pydicom.read_file() method to load the data:","metadata":{}},{"cell_type":"code","source":"fig=plt.figure(figsize=(15, 10))\ncolumns = 5; rows = 4\nfor i in range(1, columns*rows +1):\n    ds = pydicom.dcmread(train_images_dir + train_images[i])\n    fig.add_subplot(rows, columns, i)\n    plt.imshow(ds.pixel_array, cmap=plt.cm.bone)\n    fig.add_subplot","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(ds) # this is file type of image","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"im = ds.pixel_array\nprint(type(im))\nprint(im.dtype)\nprint(im.shape)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"5\"></a> <br>\n## 5- Visualization of data","metadata":{}},{"cell_type":"code","source":"sns.countplot(train.Label)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.Label.value_counts()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### To take a look at this first DICOM image, let's use the pylab.imshow() method:","metadata":{}},{"cell_type":"code","source":"\npylab.imshow(im, cmap=pylab.cm.gist_gray)\npylab.axis('on')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"6\"></a> <br>\n## 6- Working newTable ","metadata":{}},{"cell_type":"code","source":"train['Sub_type'] = train['ID'].str.split(\"_\", n = 3, expand = True)[2]\ntrain['PatientID'] = train['ID'].str.split(\"_\", n = 3, expand = True)[1]\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gbSub = train.groupby('Sub_type').sum()\ngbSub","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.barplot(y=gbSub.index, x=gbSub.Label, palette=\"deep\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig=plt.figure(figsize=(10, 8))\n\nsns.countplot(x=\"Sub_type\", hue=\"Label\", data=train)\n\nplt.title(\"Total Images by Subtype\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"7\"></a> <br>\n## 7- Visualization of hemorrhage epidural\n\nReference of Correcting windows : https://www.kaggle.com/omission/eda-view-dicom-images-with-correct-windowing @Richard_McKinley","metadata":{}},{"cell_type":"code","source":"\ndef 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    ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_images_dir\n\ndef view_images(images, title = '', aug = None):\n    width = 5\n    height = 2\n    fig, axs = plt.subplots(height, width, figsize=(15,5))\n    \n    for im in range(0, height * width):\n        ''''\n        image = pydicom.read_file(os.path.join(train_images_dir,'ID_'+images[im]+ '.dcm')).pixel_array\n        i = im // width\n        j = im % width\n        axs[i,j].imshow(image, cmap=plt.cm.bone) \n        axs[i,j].axis('off')'''''\n        \n        data = pydicom.read_file(os.path.join(train_images_dir,'ID_'+images[im]+ '.dcm'))\n        image = data.pixel_array\n        window_center , window_width, intercept, slope = get_windowing(data)\n        image_windowed = window_image(image, window_center, window_width, intercept, slope)\n\n\n        i = im // width\n        j = im % width\n        axs[i,j].imshow(image_windowed, cmap=plt.cm.bone) \n        axs[i,j].axis('off')\n        \n        \n    plt.suptitle(title)\n    plt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"view_images(train[(train['Sub_type'] == 'epidural') & (train['Label'] == 1)][:10].PatientID.values, title = 'Images of hemorrhage epidural')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"8\"></a> <br>\n## 8- Visualization of hemorrhage intraparenchymal","metadata":{}},{"cell_type":"code","source":"view_images(train[(train['Sub_type'] == 'intraparenchymal') & (train['Label'] == 1)][:20].PatientID.values, title = 'Images of hemorrhage intraparenchymal')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"9\"></a> <br>\n## 9- Visualization of hemorrhage intraventricular","metadata":{}},{"cell_type":"code","source":"view_images(train[(train['Sub_type'] == 'intraventricular') & (train['Label'] == 1)][:20].PatientID.values, title = 'Images of hemorrhage intraventricular')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"10\"></a> <br>\n## 10- Visualization of hemorrhage subarachnoid","metadata":{}},{"cell_type":"code","source":"view_images(train[(train['Sub_type'] == 'subarachnoid') & (train['Label'] == 1)][:20].PatientID.values, title = 'Images of hemorrhage subarachnoid')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"11\"></a> <br>\n## 11- Visualization of hemorrhage subdural","metadata":{}},{"cell_type":"code","source":"view_images(train[(train['Sub_type'] == 'subdural') & (train['Label'] == 1)][:20].PatientID.values, title = 'Images of hemorrhage subdural')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"###  **I hope you find this kernel helpful and some <font color=\"red\"><b>UPVOTES</b></font> would be very much appreciated**","metadata":{}},{"cell_type":"markdown","source":"###  Good luck!","metadata":{}},{"cell_type":"markdown","source":"###### [Go to top](#top)","metadata":{}}]}