{"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":"The World Health Organization (WHO) undertook the development of a rapid guide on the use of chest imaging in the diagnosis and management of coronavirus disease 2019 (COVID-19). The rapid guide was developed over 2 months by using standard WHO processes, except for the use of “rapid reviews” and online meetings of the panel. The evidence review was supplemented by a survey of stakeholders regarding their views on the acceptability, feasibility, impact on equity, and resource use of the relevant chest imaging modalities (chest radiography, chest CT, and lung US). The guideline development group had broad expertise and country representation. The rapid guide includes three diagnosis recommendations and four management recommendations. The recommendations cover patients with confirmed or who are suspected of having COVID-19 with different levels of disease severity, throughout the care pathway from outpatient facility or hospital entry to home discharge. All recommendations are conditional and are based on low certainty evidence (n = 2), very low certainty evidence (n = 2), or expert opinion (n = 3). The remarks accompanying the recommendations suggest which patients are likely to benefit from chest imaging and what factors should be considered when choosing the specific imaging modality. The guidance offers considerations about implementation, monitoring, and evaluation, and also identifies research needs.","metadata":{}},{"cell_type":"code","source":"\n!conda install gdcm -c conda-forge -y\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os\nimport pydicom\nimport glob\nfrom tqdm.notebook import tqdm\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\nimport matplotlib.pyplot as plt\nfrom skimage import exposure\n#import gdcm\nimport cv2\nimport warnings\nfrom fastai.vision.all import *\nfrom fastai.medical.imaging import *\nwarnings.filterwarnings('ignore')\ndataset_path = Path('../input/siim-covid19-detection')\nimport vtk\n# numba\nimport numba\nfrom numba import jit\nfrom vtk.util import numpy_support\n","metadata":{"execution":{"iopub.status.busy":"2021-05-28T12:18:49.762019Z","iopub.execute_input":"2021-05-28T12:18:49.762661Z","iopub.status.idle":"2021-05-28T12:19:25.948394Z","shell.execute_reply.started":"2021-05-28T12:18:49.762610Z","shell.execute_reply":"2021-05-28T12:19:25.947229Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_img(img, size=(7, 7), is_rgb=True, title=\"\", cmap='gray'):\n    plt.figure(figsize=size)\n    plt.imshow(img, cmap=cmap)\n    plt.suptitle(title)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2021-05-28T12:19:25.950506Z","iopub.execute_input":"2021-05-28T12:19:25.950900Z","iopub.status.idle":"2021-05-28T12:19:25.956609Z","shell.execute_reply.started":"2021-05-28T12:19:25.950864Z","shell.execute_reply":"2021-05-28T12:19:25.955649Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_imgs(imgs, cols=4, size=7, is_rgb=True, title=\"\", cmap='gray', img_size=(500,500)):\n    rows = len(imgs)//cols + 1\n    fig = plt.figure(figsize=(cols*size, rows*size))\n    for i, img in enumerate(imgs):\n        if img_size is not None:\n            img = cv2.resize(img, img_size)\n        fig.add_subplot(rows, cols, i+1)\n        plt.imshow(img, cmap=cmap)\n    plt.suptitle(title)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2021-05-28T12:19:25.958199Z","iopub.execute_input":"2021-05-28T12:19:25.958499Z","iopub.status.idle":"2021-05-28T12:19:25.975575Z","shell.execute_reply.started":"2021-05-28T12:19:25.958468Z","shell.execute_reply":"2021-05-28T12:19:25.973999Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndef image_path(row):\n    study_path = dataset_path/'train'/row.StudyInstanceUID\n    for i in get_dicom_files(study_path):\n        if row.id.split('_')[0] == i.stem: return i \n        \n\n\n\nclass Config:\n    n_folds: int = 5\n    seed: int = 2021\n    num_classes: int = 2 \n    img_size: int = 256\n    fold_num: int = 0\n    device: str = 'cuda:0'\n","metadata":{"execution":{"iopub.status.busy":"2021-05-28T12:19:25.977278Z","iopub.execute_input":"2021-05-28T12:19:25.977653Z","iopub.status.idle":"2021-05-28T12:19:25.990109Z","shell.execute_reply.started":"2021-05-28T12:19:25.977618Z","shell.execute_reply":"2021-05-28T12:19:25.988766Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def seed_everything(seed):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = True\n    \nseed_everything(Config.seed)","metadata":{"execution":{"iopub.status.busy":"2021-05-28T12:19:29.187158Z","iopub.execute_input":"2021-05-28T12:19:29.187516Z","iopub.status.idle":"2021-05-28T12:19:29.197866Z","shell.execute_reply.started":"2021-05-28T12:19:29.187484Z","shell.execute_reply":"2021-05-28T12:19:29.196850Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Thanks https://www.kaggle.com/tanlikesmath/siim-covid-19-detection-a-simple-eda\ndef dicom2array(path, voi_lut=True, fix_monochrome=True):\n    # Original from: https://www.kaggle.com/raddar/convert-dicom-to-np-array-the-correct-way\n    dicom = pydicom.read_file(path)\n    \n    # VOI LUT (if available by DICOM device) is used to transform raw DICOM data to \n    # \"human-friendly\" view\n    if voi_lut:\n        data = apply_voi_lut(dicom.pixel_array, dicom)\n    else:\n        data = dicom.pixel_array\n               \n    # depending on this value, X-ray may look inverted - fix that:\n    if fix_monochrome and dicom.PhotometricInterpretation == \"MONOCHROME1\":\n        data = np.amax(data) - data\n        \n    data = data - np.min(data)\n    data = data / np.max(data)\n    data = (data * 255).astype(np.uint8)\n    return data\n        ","metadata":{"execution":{"iopub.status.busy":"2021-05-28T12:20:30.389280Z","iopub.status.idle":"2021-05-28T12:20:30.389806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dicom_paths = get_dicom_files(dataset_path/'train')\nimgs = [dicom2array(path) for path in dicom_paths[:4]]\nplot_imgs(imgs)\n","metadata":{"execution":{"iopub.status.busy":"2021-05-28T12:20:30.390720Z","iopub.status.idle":"2021-05-28T12:20:30.391128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_image_df = pd.read_csv(dataset_path/'train_image_level.csv')\n\n\n# Thanks https://www.kaggle.com/tanlikesmath/siim-covid-19-detection-a-simple-eda\ntrain_image_df['class'] = train_image_df.label.apply(lambda x: x.split()[0])\n\n\ntrain_image_df['x_min'] = train_image_df.label.apply(lambda x: float(x.split()[2]))\ntrain_image_df['y_min'] = train_image_df.label.apply(lambda x: float(x.split()[3]))\ntrain_image_df['x_max'] = train_image_df.label.apply(lambda x: float(x.split()[4]))\ntrain_image_df['y_max'] = train_image_df.label.apply(lambda x: float(x.split()[5]))\n\n\n\ndef get_bbox_area(row):\n    return (row['x_max']-row['x_min'])*(row['y_max']-row['y_min'])\n\n\ntrain_image_df['bbox_area'] = train_image_df.apply(get_bbox_area, axis=1)\n\ntrain_image_df['image_path'] = train_image_df.apply(image_path, axis=1)\n\ntrain_image_df['bbox_area'].hist()","metadata":{"execution":{"iopub.status.busy":"2021-05-28T12:20:31.061850Z","iopub.execute_input":"2021-05-28T12:20:31.062203Z","iopub.status.idle":"2021-05-28T12:20:39.626095Z","shell.execute_reply.started":"2021-05-28T12:20:31.062174Z","shell.execute_reply":"2021-05-28T12:20:39.624892Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_image_df.tail()","metadata":{"execution":{"iopub.status.busy":"2021-05-28T12:26:43.104863Z","iopub.execute_input":"2021-05-28T12:26:43.105232Z","iopub.status.idle":"2021-05-28T12:26:43.138229Z","shell.execute_reply.started":"2021-05-28T12:26:43.105200Z","shell.execute_reply":"2021-05-28T12:26:43.137272Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"thickness = 3\nscale = 5\n\nimgs = []\nimage_paths = train_image_df['image_path'].values\nclass_ids = train_image_df['class']\n\n# map label_id to specify color\nlabel2color = {class_id:[random.randint(0,255) for i in range(3)] for class_id in class_ids}\nfor i in range(8):\n    image_path = random.choice(image_paths)\n    print(image_path)\n    img = dicom2array(str(image_path))\n    print(img)\n\n    img = cv2.resize(img, (224,224), fx=1/scale, fy=1/scale, interpolation = cv2.INTER_CUBIC)\n    img = np.stack([img, img, img], axis=-1)\n    \n    box = train_image_df.loc[train_image_df['image_path'] == image_path, ['x_min', 'y_min', 'x_max', 'y_max']].values[0]/scale\n    label = train_image_df.loc[train_image_df['image_path'] == image_path, ['class']].values[0][0]\n    \n    color = label2color[label]\n    img = cv2.rectangle(\n        img,\n        (int(box[0]), int(box[1])),\n        (int(box[2]), int(box[3])),\n        color, thickness)\n    \n    img = cv2.resize(img, (500,500))\n    imgs.append(img)\n    \nplot_imgs(imgs, cmap=None)","metadata":{},"execution_count":null,"outputs":[]}]}