{"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":"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\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 read-only \"../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\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-07-05T11:55:45.584989Z","iopub.execute_input":"2021-07-05T11:55:45.585374Z","iopub.status.idle":"2021-07-05T11:55:45.591219Z","shell.execute_reply.started":"2021-07-05T11:55:45.585343Z","shell.execute_reply":"2021-07-05T11:55:45.590207Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Welcome to the Sample python script to read Dicom file and convert into jpg format. Dataset is being used from [SIIM-FISABIO-RSNA COVID-19 Detection](https://www.kaggle.com/c/siim-covid19-detection/data) competition.\n![](https://storage.googleapis.com/kaggle-competitions/kaggle/26680/logos/header.png)","metadata":{}},{"cell_type":"code","source":"import pydicom as dicom\nfrom PIL import Image\nimport numpy as np # linear algebra\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport os\nimport ast\nfrom colorama import Style","metadata":{"execution":{"iopub.status.busy":"2021-07-05T13:08:53.464087Z","iopub.execute_input":"2021-07-05T13:08:53.464630Z","iopub.status.idle":"2021-07-05T13:08:53.471864Z","shell.execute_reply.started":"2021-07-05T13:08:53.464574Z","shell.execute_reply":"2021-07-05T13:08:53.470809Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Display list of content of directory siim-covid19-detection","metadata":{}},{"cell_type":"code","source":"path = '/kaggle/input/siim-covid19-detection/'\nos.listdir(path)","metadata":{"execution":{"iopub.status.busy":"2021-07-05T13:25:59.133129Z","iopub.execute_input":"2021-07-05T13:25:59.133504Z","iopub.status.idle":"2021-07-05T13:25:59.142449Z","shell.execute_reply.started":"2021-07-05T13:25:59.133475Z","shell.execute_reply":"2021-07-05T13:25:59.141315Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load Data","metadata":{}},{"cell_type":"code","source":"train_image = pd.read_csv(path+'train_image_level.csv')","metadata":{"execution":{"iopub.status.busy":"2021-07-05T13:26:06.123141Z","iopub.execute_input":"2021-07-05T13:26:06.123508Z","iopub.status.idle":"2021-07-05T13:26:06.167874Z","shell.execute_reply.started":"2021-07-05T13:26:06.123464Z","shell.execute_reply":"2021-07-05T13:26:06.166854Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_image.head().style.applymap(lambda x: 'background-color:lightgreen')","metadata":{"execution":{"iopub.status.busy":"2021-07-05T13:26:08.453934Z","iopub.execute_input":"2021-07-05T13:26:08.454299Z","iopub.status.idle":"2021-07-05T13:26:08.469607Z","shell.execute_reply.started":"2021-07-05T13:26:08.454270Z","shell.execute_reply":"2021-07-05T13:26:08.468506Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Displaying content of the folder of the first row in train_image","metadata":{}},{"cell_type":"code","source":"for dirname, _, filenames in os.walk(path+'/train/5776db0cec75'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","metadata":{"execution":{"iopub.status.busy":"2021-07-05T13:26:15.145906Z","iopub.execute_input":"2021-07-05T13:26:15.146277Z","iopub.status.idle":"2021-07-05T13:26:15.157611Z","shell.execute_reply.started":"2021-07-05T13:26:15.146247Z","shell.execute_reply":"2021-07-05T13:26:15.156388Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path_train = path+'train/'+train_image.loc[0, 'StudyInstanceUID']+'/'+'81456c9c5423'+'/'\nprint(path_train)","metadata":{"execution":{"iopub.status.busy":"2021-07-05T13:26:35.897145Z","iopub.execute_input":"2021-07-05T13:26:35.897483Z","iopub.status.idle":"2021-07-05T13:26:35.904768Z","shell.execute_reply.started":"2021-07-05T13:26:35.897455Z","shell.execute_reply":"2021-07-05T13:26:35.903683Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_id = train_image.loc[0, 'id']\nprint(image_id)","metadata":{"execution":{"iopub.status.busy":"2021-07-05T13:27:24.642070Z","iopub.execute_input":"2021-07-05T13:27:24.642451Z","iopub.status.idle":"2021-07-05T13:27:24.647576Z","shell.execute_reply.started":"2021-07-05T13:27:24.642421Z","shell.execute_reply":"2021-07-05T13:27:24.646868Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Read value of column \"id\" and replace _image with .dcm extension","metadata":{}},{"cell_type":"code","source":"img_id = train_image.loc[0, 'id'].replace('_image', '.dcm')\nprint(img_id)","metadata":{"execution":{"iopub.status.busy":"2021-07-05T13:25:00.985141Z","iopub.execute_input":"2021-07-05T13:25:00.985667Z","iopub.status.idle":"2021-07-05T13:25:00.991076Z","shell.execute_reply.started":"2021-07-05T13:25:00.985636Z","shell.execute_reply":"2021-07-05T13:25:00.990048Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Read Dicom file and Display image","metadata":{}},{"cell_type":"code","source":"data_file = dicom.dcmread(path_train+img_id)\n# Extract image data of the dicom file\nimg = data_file.pixel_array\nfig, ax = plt.subplots(1, 1, figsize=(16, 8))\nax.imshow(img)","metadata":{"execution":{"iopub.status.busy":"2021-07-05T13:27:49.743826Z","iopub.execute_input":"2021-07-05T13:27:49.744188Z","iopub.status.idle":"2021-07-05T13:27:51.617198Z","shell.execute_reply.started":"2021-07-05T13:27:49.744159Z","shell.execute_reply":"2021-07-05T13:27:51.616022Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Save file into Output folder with name as \"image_id\".jpg","metadata":{}},{"cell_type":"code","source":"im = data_file.pixel_array.astype(float)\nrescaled_image = (np.maximum(im,0)/im.max())*255 # float pixels\nfinal_image = np.uint8(rescaled_image) # integers pixels\nfinal_image = Image.fromarray(final_image)\nfinal_image.save('./'+image_id+'.jpg')\n","metadata":{"execution":{"iopub.status.busy":"2021-07-05T13:27:52.573152Z","iopub.execute_input":"2021-07-05T13:27:52.573730Z","iopub.status.idle":"2021-07-05T13:27:52.945017Z","shell.execute_reply.started":"2021-07-05T13:27:52.573681Z","shell.execute_reply":"2021-07-05T13:27:52.944157Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Display required number of Dicom Images and save them as jpg format","metadata":{}},{"cell_type":"code","source":"fig, axs = plt.subplots(3, 3, figsize=(20, 20))\nfig.subplots_adjust(hspace = .1, wspace=.1)\naxs = axs.ravel()\n\nfor row in range(9):\n    study = train_image.loc[row, 'StudyInstanceUID']\n    path_in = path+'train/'+study+'/'\n    folder = os.listdir(path_in)\n    path_file = path_in+folder[0]\n    filename = os.listdir(path_file)[0]\n    file_id = filename.split('.')[0]\n    \n    data_file = dicom.dcmread(path_file+'/'+file_id+'.dcm')\n    img = data_file.pixel_array\n    if (train_image.loc[row, 'boxes']!=train_image.loc[row, 'boxes']) == False:\n        boxes = ast.literal_eval(train_image.loc[row, 'boxes'])\n    \n        for box in boxes:\n            p = matplotlib.patches.Rectangle((box['x'], box['y']), box['width'], box['height'],\n                                     ec='r', fc='none', lw=2.)\n            axs[row].add_patch(p)\n    axs[row].imshow(img, cmap='gray')\n    axs[row].set_title(train_image.loc[row, 'label'].split(' ')[0])\n    axs[row].set_xticklabels([])\n    axs[row].set_yticklabels([])\n    im = data_file.pixel_array.astype(float)\n    rescaled_image = (np.maximum(im,0)/im.max())*255 # float pixels\n    final_image = np.uint8(rescaled_image) # integers pixels\n    final_image = Image.fromarray(final_image)\n    final_image.save('./'+file_id+'.jpg')","metadata":{"execution":{"iopub.status.busy":"2021-07-05T13:53:25.554181Z","iopub.execute_input":"2021-07-05T13:53:25.554548Z","iopub.status.idle":"2021-07-05T13:53:37.850054Z","shell.execute_reply.started":"2021-07-05T13:53:25.554511Z","shell.execute_reply":"2021-07-05T13:53:37.849280Z"},"trusted":true},"execution_count":null,"outputs":[]}]}