{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Chest X-Rays and Bounding Boxes\n\nThis notebook shows you how to display a DICOM image and the corresponding bounding boxes using matplotlib.  \nIt is based on:\n- https://www.kaggle.com/raddar/convert-dicom-to-np-array-the-correct-way\n- https://www.kaggle.com/trungthanhnguyen0502/eda-vinbigdata-chest-x-ray-abnormalities"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"from pathlib import Path\nfrom random import randint\n\nimport pandas as pd\nimport numpy as np\nimport pydicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\nimport matplotlib.pyplot as plt\nimport cv2\nfrom glob import glob\n\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dataset_dir = Path('../input/vinbigdata-chest-xray-abnormalities-detection')\npath_train_set = dataset_dir / \"train\"\ndicom_paths = glob(f'{dataset_dir}/train/*.dicom')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def patient_id_to_path(patient_id, root=Path(\"./\")):\n    return root / f\"{patient_id}.dicom\"\n\n\ndef dicom_to_array(path, voi_lut = True, fix_monochrome = True):\n    \"\"\"Convert a DICOM chest xray to np.array.\n    \n    Raw dicom data is not actually linearly convertable to png/jpg. \n    In fact, most of DICOM's store pixel values in exponential scale.\n    This function applies the necessary transformations.\n    \n    \n    Source\n    ------\n    Kaggle user: raddar\n    https://www.kaggle.com/raddar/convert-dicom-to-np-array-the-correct-way\n    \"\"\"\n    dicom = pydicom.read_file(path)\n    \n    # VOI LUT (if available by DICOM device) is used to transform raw DICOM data to \"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        \n    return data\n\n\ndef plot_img(img, size=(7, 7), is_rgb=True, title=\"\", cmap='gray'):\n    plt.figure(figsize=size)\n    plt.axis('off')\n    plt.imshow(img, cmap=cmap)\n    plt.suptitle(title)\n    plt.show()\n\n\ndef 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.axis('off')\n    plt.suptitle(title)\n    plt.show()\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"imgs = [dicom_to_array(path) for path in dicom_paths[:4]]\nplot_imgs(imgs)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"df_train = pd.read_csv(f'{dataset_dir}/train.csv')\ndf_finding = df_train[df_train['class_name'] != 'No finding']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label2color = {class_id:[randint(0,255) for i in range(3)] for class_id in df_train.class_id.unique()}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def draw_bboxes(img, boxes, thickness=10, colors=None, img_size=(500,500)):\n    img_copy = img.copy()\n    \n    if len(img_copy.shape) == 2:\n        img_copy = np.stack([img_copy, img_copy, img_copy], axis=-1)\n    \n    if colors is None:\n        colors = [(255, 0, 0)] * len(boxes)\n    else:\n        assert len(colors) == len(boxes)\n    \n    for color, box in zip(colors, boxes):\n        img_copy = cv2.rectangle(\n            img_copy,\n            (int(box[0]), int(box[1])),\n            (int(box[2]), int(box[3])),\n            color, thickness)\n        \n    if img_size is not None:\n        img_copy = cv2.resize(img_copy, img_size)\n        \n    return img_copy","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"patient_id = df_finding.sample(1).image_id.iloc[0]\nboxes = df_finding.loc[df_finding.image_id == patient_id, ['class_id', 'x_min', 'y_min', 'x_max', 'y_max']].values\nimg = dicom_to_array(patient_id_to_path(patient_id, root=path_train_set))\nimg_bboxes_1 = draw_bboxes(img, boxes[:,1:], colors=[label2color[label] for label in boxes[:,0]])\nplot_img(img_bboxes_1)","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":4}