{"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":"# Viewing Dicom CT images with correct  windowing\n\nCT image values correspond to [Hounsfield units](https://en.wikipedia.org/wiki/Hounsfield_scale) (HU).  But the values stored in CT Dicoms are not Hounsfield units, but instead a scaled version.  To extract the Hounsfield units we need to apply a linear transformation, which can be deduced from the Dicom tags.\n\nOnce we have transformed the pixel values to Hounsfield units, we can apply a *windowing*: the usual values for a head CT are a center of 40 and a width of 80, but we can also extract this from the Dicom headers.\n","metadata":{}},{"cell_type":"code","source":"from glob import glob\nimport os\nimport pandas as pd\nimport numpy as np\nimport re\nfrom PIL import Image\nimport seaborn as sns\nfrom random import randrange\n\n#checnking the input files\nprint(os.listdir(\"../input/rsna-intracranial-hemorrhage-detection/rsna-intracranial-hemorrhage-detection/\"))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-02T14:39:59.312196Z","iopub.execute_input":"2022-12-02T14:39:59.312865Z","iopub.status.idle":"2022-12-02T14:40:00.278026Z","shell.execute_reply.started":"2022-12-02T14:39:59.312808Z","shell.execute_reply":"2022-12-02T14:40:00.276964Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Load Data","metadata":{}},{"cell_type":"code","source":"#reading all dcm files into train and text\ntrain = sorted(glob(\"../input/rsna-intracranial-hemorrhage-detection/rsna-intracranial-hemorrhage-detection/stage_2_train/*.dcm\"))\ntest = sorted(glob(\"../input/rsna-intracranial-hemorrhage-detection/rsna-intracranial-hemorrhage-detection/stage_2_test/*.dcm\"))\nprint(\"train files: \", len(train))\nprint(\"test files: \", len(test))\n\npd.reset_option('max_colwidth')","metadata":{"execution":{"iopub.status.busy":"2022-10-24T16:23:59.433052Z","iopub.execute_input":"2022-10-24T16:23:59.433768Z","iopub.status.idle":"2022-10-24T16:24:05.122651Z","shell.execute_reply.started":"2022-10-24T16:23:59.433705Z","shell.execute_reply":"2022-10-24T16:24:05.121481Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = pd.read_csv('../input/rsna-intracranial-hemorrhage-detection/rsna-intracranial-hemorrhage-detection/stage_2_train.csv')","metadata":{"execution":{"iopub.status.busy":"2022-10-24T16:24:05.124244Z","iopub.execute_input":"2022-10-24T16:24:05.124638Z","iopub.status.idle":"2022-10-24T16:24:09.246285Z","shell.execute_reply.started":"2022-10-24T16:24:05.124574Z","shell.execute_reply":"2022-10-24T16:24:09.245328Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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    ","metadata":{"execution":{"iopub.status.busy":"2022-10-24T16:24:09.248055Z","iopub.execute_input":"2022-10-24T16:24:09.248399Z","iopub.status.idle":"2022-10-24T16:24:09.254721Z","shell.execute_reply.started":"2022-10-24T16:24:09.248338Z","shell.execute_reply":"2022-10-24T16:24:09.253349Z"},"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]\n    \n    \n    ","metadata":{"execution":{"iopub.status.busy":"2022-10-24T16:24:09.258935Z","iopub.execute_input":"2022-10-24T16:24:09.259375Z","iopub.status.idle":"2022-10-24T16:24:09.269293Z","shell.execute_reply.started":"2022-10-24T16:24:09.259308Z","shell.execute_reply":"2022-10-24T16:24:09.268193Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pydicom\nimport matplotlib.pyplot as plt\ncase = 5\n\ndata = pydicom.dcmread(train[case])\n\n#print(data)\nwindow_center , window_width, intercept, slope = get_windowing(data)\n\n\n#displaying the image\nimg = pydicom.read_file(train[case]).pixel_array\n\nimg = window_image(img, window_center, window_width, intercept, slope)\nplt.imshow(img, cmap=plt.cm.bone)\nplt.grid(False)\n\nprint(data)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-10-24T16:24:09.271689Z","iopub.execute_input":"2022-10-24T16:24:09.272089Z","iopub.status.idle":"2022-10-24T16:24:09.535669Z","shell.execute_reply.started":"2022-10-24T16:24:09.272016Z","shell.execute_reply":"2022-10-24T16:24:09.534754Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Visualize Sample Images","metadata":{}},{"cell_type":"markdown","source":"Visualize Sample Images with different diagnosis","metadata":{}},{"cell_type":"code","source":"TRAIN_IMG_PATH = \"../input/rsna-intracranial-hemorrhage-detection/rsna-intracranial-hemorrhage-detection/stage_2_train/\"\nTEST_IMG_PATH = \"../input/rsna-intracranial-hemorrhage-detection/rsna-intracranial-hemorrhage-detection/stage_2_test/\"\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        data = pydicom.read_file(os.path.join(TRAIN_IMG_PATH,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    plt.suptitle(title)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-10-24T16:24:09.537044Z","iopub.execute_input":"2022-10-24T16:24:09.537523Z","iopub.status.idle":"2022-10-24T16:24:09.547452Z","shell.execute_reply.started":"2022-10-24T16:24:09.537468Z","shell.execute_reply":"2022-10-24T16:24:09.546074Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['image'] = train_df['ID'].str.slice(stop=12)\ntrain_df['diagnosis'] = train_df['ID'].str.slice(start=13)\n\nview_images(train_df[(train_df['diagnosis'] == 'epidural') & (train_df['Label'] == 1)][:10].image.values, title = 'Images with epidural')","metadata":{"execution":{"iopub.status.busy":"2022-10-24T16:24:09.549819Z","iopub.execute_input":"2022-10-24T16:24:09.550154Z","iopub.status.idle":"2022-10-24T16:24:15.690468Z","shell.execute_reply.started":"2022-10-24T16:24:09.550094Z","shell.execute_reply":"2022-10-24T16:24:15.689575Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"view_images(train_df[(train_df['diagnosis'] == 'intraparenchymal') & (train_df['Label'] == 1)][:10].image.values, title = 'Images with intraparenchymal')","metadata":{"execution":{"iopub.status.busy":"2022-10-24T16:24:15.69184Z","iopub.execute_input":"2022-10-24T16:24:15.692272Z","iopub.status.idle":"2022-10-24T16:24:16.862209Z","shell.execute_reply.started":"2022-10-24T16:24:15.692201Z","shell.execute_reply":"2022-10-24T16:24:16.860862Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"view_images(train_df[(train_df['diagnosis'] == 'intraventricular')& (train_df['Label'] == 1)][:10].image.values, title = 'Images with intraventricular')","metadata":{"execution":{"iopub.status.busy":"2022-10-24T16:24:16.864045Z","iopub.execute_input":"2022-10-24T16:24:16.864618Z","iopub.status.idle":"2022-10-24T16:24:18.093341Z","shell.execute_reply.started":"2022-10-24T16:24:16.864557Z","shell.execute_reply":"2022-10-24T16:24:18.09208Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"view_images(train_df[(train_df['diagnosis'] == 'subarachnoid')& (train_df['Label'] == 1)][:10].image.values, title = 'Images with subarachnoid')","metadata":{"execution":{"iopub.status.busy":"2022-10-24T16:24:18.095279Z","iopub.execute_input":"2022-10-24T16:24:18.095736Z","iopub.status.idle":"2022-10-24T16:24:19.223659Z","shell.execute_reply.started":"2022-10-24T16:24:18.095652Z","shell.execute_reply":"2022-10-24T16:24:19.22263Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"view_images(train_df[(train_df['diagnosis'] == 'subdural') & (train_df['Label'] == 1)][:10].image.values, title = 'Images with subarachnoid')","metadata":{"execution":{"iopub.status.busy":"2022-10-24T16:24:19.225191Z","iopub.execute_input":"2022-10-24T16:24:19.225755Z","iopub.status.idle":"2022-10-24T16:24:20.336465Z","shell.execute_reply.started":"2022-10-24T16:24:19.225688Z","shell.execute_reply":"2022-10-24T16:24:20.335434Z"},"trusted":true},"execution_count":null,"outputs":[]}]}