{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../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\nimport 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\nimport cv2\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"data = pd.read_csv('../input/rsna-intracranial-hemorrhage-detection/stage_1_train.csv')\nlabel = data.Label.values\ndata = data.ID.str.rsplit(\"_\", n=1, expand=True)\ndata.loc[:,'label'] = label\ndata.columns = ['id','subtype','label']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.head(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_images_dir = '../input/rsna-intracranial-hemorrhage-detection/stage_1_train_images/'\ntest_images_dir = '../input/rsna-intracranial-hemorrhage-detection/stage_1_test_images/'\n# train_images = [f for f in listdir(train_images_dir) if isfile(join(train_images_dir, f))]\n# test_images = [f for f in listdir(test_images_dir) if isfile(join(test_images_dir, f))]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Number of train images:', len(train_images))\nprint('Number of test images:', len(test_images))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# fig=plt.figure(figsize=(15, 10))\n# columns = 3; rows = 1\n# for i in range(1, columns*rows +1):\n#     ds = pydicom.dcmread(train_images_dir + train_images[i])\n#     print(\"****************************\")\n#     print(\"For the image {} the window center is {} and length is {} \".format(train_images[i] , ds[('0028','1050')].value, ds[('0028','1051')].value))\n#     print(\"Pixel Spacing is as : \", ds[('0028','0030')].value)\n#     fig.add_subplot(rows, columns, i)\n#     plt.imshow(ds.pixel_array, cmap=plt.cm.bone)\n#     fig.add_subplot","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# pixel_space_X = []\n# pixel_space_Y = []\n# over = []\n# under = []\n# for train_image in (train_images[:1500]):\n#     ds = pydicom.dcmread(train_images_dir + train_image)\n#     pixel_space_X.append(float(ds[('0028','0030')].value[0]))\n#     if float(ds[('0028','0030')].value[0]) > 0.50:\n#         over.append(train_image)\n#         print(ds[('0028','0030')].value[1])\n#     if float(ds[('0028','0030')].value[0]) < 0.45:\n#         under.append(train_image)\n#     pixel_space_Y.append(float(ds[('0028','0030')].value[1]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# #print(over)\n# ds = pydicom.dcmread(train_images_dir + over[1])\n# plt.imshow(ds.pixel_array,cmap=plt.cm.bone)\n# print(ds[('0028','0030')].value[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# ds = pydicom.dcmread(train_images_dir + under[6])\n# plt.imshow(ds.pixel_array,cmap=plt.cm.bone)\n# print(ds[('0028','0030')].value[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# fig, ax = plt.subplots(1,2,figsize=(20,5))\n# sns.distplot(pixel_space_X, ax=ax[0], color=\"Blue\", kde=False)\n# ax[0].set_title(\"Pixel spacing width \\n distribution\")\n# ax[0].set_ylabel(\"Frequency given 1000 images\")\n# sns.distplot(pixel_space_Y, ax=ax[1], color=\"Green\", kde=False)\n# ax[1].set_title(\"Pixel spacing height \\n distribution\");\n# ax[1].set_ylabel(\"Frequency given 1000 images\");","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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":"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] = 0\n    img[img>img_max] = 255\n    return img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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        i = im // width\n        j = im % width\n        axs[i,j].imshow(image_windowed, cmap=plt.cm.bone)\n        #cv2.imwrite(images[im] + '.png',image_windowed)\n        axs[i,j].axis('off')\n        \n        \n    plt.suptitle(title)\n    plt.show()\n        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def save_and_resize(filenames, load_dir):    \n    save_dir = 'sample_jpg_files/'\n    if not os.path.exists(save_dir):\n        os.makedirs(save_dir)\n\n    for filename in filenames:\n        path = load_dir + filename\n        new_path = save_dir + filename.replace('.dcm', '.png')\n        \n        dcm = pydicom.dcmread(path)\n        window_center , window_width, intercept, slope = get_windowing(dcm)\n        img = dcm.pixel_array\n        img = window_image(img, window_center, window_width, intercept, slope)\n        plt.imshow(img)\n#         ////////\n        #resized = cv2.resize(img, (512, 512))\n        res = cv2.imwrite(new_path, img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('../input/rsna-intracranial-hemorrhage-detection/stage_1_train.csv')\ntrain['Sub_type'] = train['ID'].str.split(\"_\", n = 3, expand = True)[2]\ntrain['PatientID'] = train['ID'].str.split(\"_\", n = 3, expand = True)[1]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"view_images(train[:20].PatientID.values, title = 'Images of hemorrhage subarachnoid')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"file_names = os.listdir(train_images_dir)\nsave_and_resize(filenames=file_names[0:20], load_dir = train_images_dir)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir(\"sample_jpg_files/\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"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}