{"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\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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df=pd.read_csv(\"../input/vinbigdata-chest-xray-abnormalities-detection/sample_submission.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.describe(include=\"all\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.dtypes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nimport glob\nimport plotly.express as px\nimport seaborn as sns\nimport tqdm\nimport torch\nfrom itertools import combinations\n\nimport pydicom \nimport cv2\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut # voi = value of interest, lut = lookup table","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"DATA_DIR = '/kaggle/input/vinbigdata-chest-xray-abnormalities-detection/'\nTRAIN_DIR = os.path.join(DATA_DIR, 'train')\nTEST_DIR = os.path.join(DATA_DIR, 'test')\n\nLABEL_COLORS = [px.colors.label_rgb(px.colors.convert_to_RGB_255(x)) for x in sns.color_palette(\"Spectral\", 15)]\nLABEL_COLORS","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"LABEL_COLORS_TUPLES = [col[4:-1].split(\",\") for col in LABEL_COLORS]\nLABEL_COLORS_TUPLES = [tuple([int(num) for num in col]) for col in LABEL_COLORS_TUPLES ]\nLABEL_COLORS_TUPLES","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Helper Function"},{"metadata":{"trusted":true},"cell_type":"code","source":"def read_dicom(path: str, voi_lut=True, fix_monochrome=True) -> np.ndarray:\n    dicom = pydicom.read_file(path)\n    # if voi lut is available, use it 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    #MONOCHROME1 indicates that the greyscale ranges from bright to dark with ascending pixel values, \n    #MONOCHROME2 ranges from dark to bright with ascending pixel values\n    if dicom.PhotometricInterpretation == 'MONOCHROME1' and fix_monochrome:\n        data = np.amax(data) - data # np.amax() -> maximum of flattened array\n    data = data - np.min(data)\n    data = data / np.max(data)\n    data = (data * 255).astype(np.uint8)\n    return data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_image(img, title=\"\", figsize=(10,10), cmap=None):\n    plt.figure(figsize=figsize)\n    if cmap:\n        plt.imshow(img, cmap=cmap)\n    else:\n        plt.imshow(img)\n    plt.title(title)\n    plt.axis(False)\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_annotations(df: pd.DataFrame, image_id, rad_id=True) -> dict:\n    annotations = {}\n    if isinstance(image_id, str):\n        image_id = [image_id]\n    for im in image_id:\n        annos_df = df[df['image_id'] == im]\n        annos = []\n        for ann_idx in annos_df.index:\n            if annos_df.loc[ann_idx, 'class_id'] != 14:\n                if rad_id:\n                    annos.append([annos_df.loc[ann_idx, 'class_id'], \n                                annos_df.loc[ann_idx, 'x_min'],\n                                 annos_df.loc[ann_idx, 'y_min'],\n                                 annos_df.loc[ann_idx, 'x_max'],\n                                 annos_df.loc[ann_idx, 'y_max'],\n                                 annos_df.loc[ann_idx, 'rad_id']])\n                else:\n                    annos.append([annos_df.loc[ann_idx, 'class_id'], \n                                annos_df.loc[ann_idx, 'x_min'],\n                                 annos_df.loc[ann_idx, 'y_min'],\n                                 annos_df.loc[ann_idx, 'x_max'],\n                                 annos_df.loc[ann_idx, 'y_max']])\n        annotations[im] = annos\n        \n    return annotations","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def draw_boxes(df, img_id, id_to_classes, annotations, rad_id=True, plot_rad=True):\n    \"\"\"Plot image with bounding box annotations\"\"\"\n    img = read_dicom(TRAIN_DIR + \"/\" + img_id + \".dicom\")\n    img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n    for idx, annos in annotations.items():\n        for anno in annos:\n            img = cv2.rectangle(img, (int(anno[1]), int(anno[2])), (int(anno[3]), \n                                int(anno[4])), \n                                LABEL_COLORS_TUPLES[anno[0]], 1)\n            if plot_rad and rad_id:\n                label_text = id_to_classes[anno[0]] + f\"({anno[5]})\"\n            else:\n                label_text = id_to_classes[anno[0]]\n            font = cv2.FONT_HERSHEY_SIMPLEX \n            img = cv2.putText(img, label_text, \n                              (int(anno[1]), int(anno[2]) - 5), \n                              font, 1.5, LABEL_COLORS_TUPLES[anno[0]], 2)\n    \n    return img","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Train**"},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(os.path.join(DATA_DIR, 'train.csv'))\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class_ids = sorted(list(train['class_id'].unique()))\nclass_names = list(train['class_name'])\n\nid_to_classes = {id: list(train.query(f'class_id == {id}')['class_name'])[0] for id in class_ids}\nid_to_classes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class_value_counts = train['class_name'].value_counts().sort_index()\nclass_value_counts","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = px.bar(class_value_counts, \n             color=train['class_name'].value_counts().sort_index().index, \n             opacity=0.9, \n             color_discrete_sequence=LABEL_COLORS, \n             log_y=True, \n             title='Annotations per class',\n             text=class_value_counts)\nfig.update_traces(texttemplate='%{text:.2s}', textposition='outside')\nfig.update_layout(legend_title=None, xaxis_title=\"\", yaxis_title=\"count\")\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"annos_per_img = train.groupby('image_id')[\"class_name\"].unique().apply(lambda x: len(x))\nfig = px.histogram(annos_per_img,\n                   nbins=max(annos_per_img),\n                   labels={'value': 'number of unique abnormalities'}, \n                   title='Annotations per patient', \n                   log_y=True)\n\nfig.update_layout(showlegend=False, \n                  xaxis_title='number of unique abnormalities', \n                  yaxis_title='number of imgs')\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"annos = get_annotations(train, '9a5094b2563a1ef3ff50dc5c7ff71345', True)\nannos","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img = draw_boxes(train, '9a5094b2563a1ef3ff50dc5c7ff71345', id_to_classes, annos)\nplot_image(img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df=read.csv(\"../input/vinbigdata-chest-xray-abnormalities-detection/sample_submission.csv\")\ndf.dim","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}