{"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)\nimport os\nimport pydicom\nimport cv2\nfrom functools import reduce\nfrom glob import glob\nfrom tqdm.notebook import tqdm\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\nimport matplotlib.pyplot as plt\nimport seaborn as sns\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\n\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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"dataset_dir = '../input/vinbigdata-chest-xray-abnormalities-detection'\ntrain_dir = f'{dataset_dir}/train'\ntest_dir = f'{dataset_dir}/test'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pwd","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Read example dicom\nsample_id = '000434271f63a053c4128a0ba6352c7f'\npath_file = os.path.join(train_dir, f'{sample_id}.dicom')\nexample = pydicom.read_file(path_file)\nprint(type(example))\nprint(example)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"example.pixel_array","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def dicom2arr(path, voi_lut=True, fix_monochrome=True):\n    dicom = pydicom.read_file(path)\n    data = apply_voi_lut(dicom.pixel_array, dicom) if (voi_lut) else dicom.pixel_array\n    if (fix_monochrome and (dicom.PhotometricInterpretation == \"MONOCHROME1\")):\n        data = np.amax(data) - data\n    data = data.astype(np.float)\n    data -= np.min(data)\n    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":"arr_example = dicom2arr(path_file)\nprint(arr_example)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def visualize_data(info_imgs, figsize=None, color_map=None, thickness=10, axes_shape=None):\n    num_imgs = len(info_imgs)\n    fig, axes = plt.subplots(num_imgs//axes_shape[1] + (1 if (num_imgs % axes_shape[1] != 0) else 0), axes_shape[1], figsize=figsize)\n    for i in range(axes.shape[0]):\n        for j in range(axes.shape[1]):\n            img = info_imgs[i * axes.shape[1] + j][\"img\"]\n            bboxes = info_imgs[i * axes.shape[1] + j].get(\"bboxes\", None)\n            title = info_imgs[i * axes.shape[1] + j].get(\"title\", None)\n            if (bboxes is not None):\n                for k, bbox in enumerate(bboxes):\n                    img = cv2.rectangle(img, tuple(bbox[:2]), tuple(bbox[2:]), color_map[info_imgs[i * axes.shape[1] + j][\"class_id\"][k]], thickness)\n            axes[i, j].imshow(img, cmap=\"gray\")\n            if (title is not None):\n                axes[i, j].set_title(title)\n    plt.show()\n    return","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dicom_paths = glob(f'{dataset_dir}/train/*.dicom')[:8]\nimgs = [{\"img\": dicom2arr(path)} for path in dicom_paths]\nvisualize_data(imgs, figsize=(20, 12), axes_shape = (-1, 4))\n\n# Visualize img with histogram equalization to obtain high contrast image\npreprocess_imgs = [{\"img\": cv2.equalizeHist(img[\"img\"])} for img in imgs]\nvisualize_data(preprocess_imgs, figsize=(20, 12), axes_shape = (-1, 4))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from bokeh.plotting import figure as bokeh_figure\nfrom bokeh.io import output_notebook, show, output_file\nfrom bokeh.models import ColumnDataSource, HoverTool, Panel\nfrom bokeh.models.widgets import Tabs\nimport pandas as pd\nfrom PIL import Image\nfrom sklearn import preprocessing\nimport random\nfrom random import randint\n\n\ntrain_df = pd.read_csv('../input/train-csv-of-vinbd-chest-xray-abnormalities/train.csv')\n\n# convert rad_id to int type\nle = preprocessing.LabelEncoder()\ntrain_df['rad_label'] = le.fit_transform(train_df['rad_id'])\ntrain_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Number of radiologists: \", le.classes_.shape[0])\nprint(\"Radiologists: \", le.classes_)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"diseases, counts = np.unique(train_df[\"class_name\"].values, return_counts=True)\nprint(\"Number of classes: \", diseases.shape[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"info_imgs = []\ncolor_map = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 0, 255), (0, 255, 255), (255, 255, 0), (255, 51, 187), (0, 128, 255), (0, 0, 0), (255, 255, 255), (30, 105, 210), (179, 222, 245), (128, 128, 128), (21, 0, 128)]\ncolor_name = [\"Blue\", \"Green\", \"Red\", \"Pink\", \"Yellow\", \"Aqua\", \"Purple\", \"Orange\", \"Black\", \"White\", \"Brown\", \"Wheat\", \"Gray\", \"Burgundy\"]\nclasses_name = [\"Aortic enlargement\", \"Atelectasis\", \"Calcification\", \"Cardiomegaly\", \"Consolidation\", \"ILD\", \"Infiltration\", \"Lung Opacity\", \"Nodule/Mass\", \"Other lesion\", \"Pleural effusion\", \"Pleural thickening\", \"Pneumothorax\", \"Pulmonary fibrosis\", \"No finding\"]\nfor i in range(diseases.shape[0] - 1):\n    print(f\"{color_name[i]}: \", classes_name[i])\nidentifiers = pd.unique(train_df.loc[train_df[\"class_id\"] != 14][\"image_id\"])\nindexes = np.random.permutation(identifiers.shape[0])[:8]\nfor index in indexes:\n    identifier_df = train_df.loc[train_df[\"image_id\"] == identifiers[index], [\"class_name\", \"x_min\", \"y_min\", \"x_max\", \"y_max\", \"class_id\"]]\n    img = dicom2arr(f'{train_dir}/{identifiers[index]}.dicom')\n    img = cv2.equalizeHist(img) \n    img = np.repeat(np.expand_dims(img, axis=-1), 3, axis=-1)\n    class_name = identifier_df.iloc[0][\"class_name\"]\n    bboxes = None\n    classes = None\n    if (class_name != classes_name[-1]):\n        bboxes = []\n        classes = []\n        identifier_df.apply(lambda x: bboxes.append([int(x[\"x_min\"]), int(x[\"y_min\"]), int(x[\"x_max\"]), int(x[\"y_max\"])]), axis=1)\n        identifier_df.apply(lambda x: classes.append(x[\"class_id\"]), axis=1)\n    info_imgs.append({\"img\": img, \"bboxes\": bboxes, \"title\": identifiers[index], \"class_id\": classes})\nvisualize_data(info_imgs, figsize=(20, 12), color_map=color_map, thickness=10, axes_shape=(-1, 4)) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"unique_class, count_class = np.unique(train_df[\"class_name\"].values, return_counts=True)\nindexes = np.argsort(count_class)[::-1]\nfig, axes = plt.subplots(1, 2, figsize=(20, 12))\naxes[0].bar(unique_class[indexes], counts[indexes], width=0.5, color=sns.color_palette(\"RdGy\", n_colors=20))\naxes[0].set_xticklabels(unique_class[indexes], rotation='90')\naxes[0].set_title('Bar chart for classes', fontsize=15, fontweight='bold')\n\naxes[1].pie(count_class[indexes], labels=unique_class[indexes], autopct='%1.2f%%',colors=sns.color_palette(\"RdGy\", n_colors=20))\naxes[1].set_title('Pie chart for classes', fontsize=15, fontweight='bold')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.image_id.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# rad: radiologits\nunique_rad, count_rad = np.unique(train_df[\"rad_id\"].values, return_counts=True)\nplt.figure(figsize=(12, 8))\nplt.bar(unique_rad, count_rad, width=1, color=sns.color_palette(\"RdGy\", n_colors=20))\nplt.title(\"Bar chart for rad\")\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.isna().sum(axis=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.loc[train_df[\"class_id\"] != 14].isna().sum(axis=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_train_df = train_df[train_df['class_name'] != \"No finding\"].copy()\nnew_train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_train_df.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_train_df.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_train_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.figure(figsize=(12, 6))\nsns.distplot(new_train_df['x_min']);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.figure(figsize=(12, 6))\nsns.distplot(new_train_df['x_max']);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.figure(figsize=(12, 6))\nsns.distplot(new_train_df['y_min']);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.figure(figsize=(12, 6))\nsns.distplot(new_train_df['y_max']);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Statistic Measure for Width, Height is very important to know method for improve model's quality\nnew_train_df[\"width_bbox\"] = new_train_df[\"x_max\"] - new_train_df[\"x_min\"]\nnew_train_df[\"height_bbox\"] = new_train_df[\"y_max\"] - new_train_df[\"y_min\"]\nprint(\"Statistic Measure for Width: \")\nnew_train_df[\"width_bbox\"].describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Statistic Measure for Height: \")\nnew_train_df[\"height_bbox\"].describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from scipy.stats import gaussian_kde\n\nnew_train_df[\"width_bbox_normalize\"] = new_train_df.apply(lambda row: row[\"width_bbox\"]/row[\"width\"], axis=1)\nnew_train_df[\"height_bbox_normalize\"] = new_train_df.apply(lambda row: row[\"height_bbox\"]/row[\"height\"], axis=1)\nx_val = new_train_df[\"width_bbox_normalize\"].values\ny_val = new_train_df[\"height_bbox_normalize\"].values\n\n# Calculate the point density\nxy = np.vstack([x_val,y_val])\nz = gaussian_kde(xy)(xy)\n\nfig, ax = plt.subplots(figsize = (10, 10))\nax.scatter(x_val, y_val, c=z, s=100, cmap='viridis')\nax.set_xlabel('bbox_width')\nax.set_ylabel('bbox_height')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_train_df[\"area\"] = (new_train_df[\"x_max\"] - new_train_df[\"x_min\"]) * (new_train_df[\"y_max\"] - new_train_df[\"y_min\"])\nfig = plt.figure(figsize=(12, 6))\nsns.distplot(new_train_df['area']);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_train_df['area'].describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.gcf().set_size_inches(12, 21)\nplt.subplots_adjust(wspace=0.4, hspace=0.4)\nfor i in range(7):\n    for j in range(2):\n        plt.subplot(7, 2, i * 2 + j + 1)\n        plt.title(classes_name[i * 2 + j])\n        sns.distplot(new_train_df.loc[new_train_df[\"class_id\"] == i * 2 + j, ['area']]);\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Imbalance Dataset\n# Mode of Area from 180 to 152684","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}