{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import pandas as pd\ndf_train = pd.read_csv('/kaggle/input/vinbigdata-original-image-dataset/vinbigdata/train.csv')\ndf_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_img_id = '4b56bc6d22b192f075f13231419dfcc8'\ntest_df = df_train[df_train['image_id'] == test_img_id]\ntest_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2\nimport matplotlib.pyplot as plt\nimages_dir = '/kaggle/input/vinbigdata-original-image-dataset/vinbigdata/train/'\n\nlabels = [\n    \"Aortic enlargement\",\n    \"Atelectasis\",\n    \"Calcification\",\n    \"Cardiomegaly\",\n    \"Consolidation\",\n    \"ILD\",\n    \"Infiltration\",\n    \"Lung Opacity\",\n    \"Nodule/Mass\",\n    \"Other lesion\",\n    \"Pleural effusion\",\n    \"Pleural thickening\",\n    \"Pneumothorax\",\n    \"Pulmonary fibrosis\"\n]\n\ndef drawBBox(img_id, df):\n    image_path = images_dir + img_id + '.jpg'\n    img = cv2.imread(image_path)\n    dh, dw, _ = img.shape\n\n    for index, row in df.iterrows():\n        class_name = row['class_name']\n        l = int(row['x_min'])\n        r = int(row['x_max'])\n        t = int(row['y_min'])\n        b = int(row['y_max'])\n        color = (0,0,255)\n        cv2.putText(img, class_name, (l, t), cv2.FONT_HERSHEY_SIMPLEX, 1.5, color, 3)\n        cv2.rectangle(img, (l, t), (r, b), (255,0,0), 2)\n\n    plt.figure(num=None, figsize=(10, 10), dpi=80, facecolor='w', edgecolor='k')\n    plt.imshow(img)\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"drawBBox(test_img_id, test_df)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"You can take the average of the **Aortic enlargement** coordinates using [IOU](https://www.pyimagesearch.com/2016/11/07/intersection-over-union-iou-for-object-detection/). I try with IOU score > 0.5"},{"metadata":{"trusted":true},"cell_type":"code","source":"def bb_iou(boxA, boxB):\n    # determine the (x, y)-coordinates of the intersection rectangle\n    xA = max(boxA[0], boxB[0])\n    yA = max(boxA[1], boxB[1])\n    xB = min(boxA[2], boxB[2])\n    yB = min(boxA[3], boxB[3])\n    # compute the area of intersection rectangle\n    interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)\n    # compute the area of both the prediction and ground-truth\n    # rectangles\n    boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)\n    boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)\n    # compute the intersection over union by taking the intersection\n    # area and dividing it by the sum of prediction + ground-truth\n    # areas - the interesection area\n    iou = interArea / float(boxAArea + boxBArea - interArea)\n    # return the intersection over union value\n    return iou","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def averageCoordinates(df, threshold):\n    tmp_df = df.reset_index()\n    duplicate = {}\n    for index1, row1 in tmp_df.iterrows():\n        if index1 < len(tmp_df) - 1:\n            next_index = index1 + 1\n            for index2, row2 in tmp_df.loc[next_index:,:].iterrows():\n                if row1[\"class_id\"] == row2[\"class_id\"]:\n                    boxA = [row1['x_min'], row1['y_min'], row1['x_max'], row1['y_max']]\n                    boxB = [row2['x_min'], row2['y_min'], row2['x_max'], row2['y_max']]\n                    iou = bb_iou(boxA, boxB)\n                    print(\"class_id\", row1[\"class_id\"])\n                    print(\"iou\", iou)\n                    if iou > threshold:\n                        if row1[\"index\"] not in duplicate:\n                            duplicate[row1[\"index\"]] = []\n                        duplicate[row1[\"index\"]].append(row2[\"index\"])\n\n    # print(duplicate)\n    remove_keys = []\n    for k in duplicate:\n        for i in duplicate[k]:\n            if i in duplicate:\n                for id in duplicate[i]:\n                    if id not in duplicate[k]:\n                        duplicate[k].append(id)\n                if i not in remove_keys:\n                    remove_keys.append(i)\n    # print(remove_keys)\n    for i in remove_keys:\n        del duplicate[i]\n\n    rows = []\n    removed_index = []\n    for k in duplicate:\n        row = tmp_df[tmp_df['index'] == k].iloc[0]\n        X_min = [row['x_min']]\n        X_max = [row['x_max']]\n        Y_min = [row['y_min']]\n        Y_max = [row['y_max']]\n        removed_index.append(k)\n        for i in duplicate[k]:\n            removed_index.append(i)\n            row = tmp_df[tmp_df['index'] == i].iloc[0]\n            X_min.append(row['x_min'])\n            X_max.append(row['x_max'])\n            Y_min.append(row['y_min'])\n            Y_max.append(row['y_max'])\n        X_min_avg = sum(X_min) / len(X_min)\n        X_max_avg = sum(X_max) / len(X_max)\n        Y_min_avg = sum(Y_min) / len(Y_min)\n        Y_max_avg = sum(Y_max) / len(Y_max)\n        new_row = [row['image_id'], row['class_name'], row['class_id'], X_min_avg, Y_min_avg, X_max_avg, Y_max_avg, row['width'], row['height']]\n        rows.append(new_row)\n\n    for index, row in tmp_df.iterrows():\n        if row['index'] not in removed_index:\n            new_row = [row['image_id'], row['class_name'], row['class_id'], row['x_min'], row['y_min'], row['x_max'], row['y_max'], row['width'], row['height']]\n            rows.append(new_row)\n\n    new_df = pd.DataFrame(rows, columns =['image_id', 'class_name', 'class_id', 'x_min', 'y_min', 'x_max', 'y_max', 'width', 'height'])\n    return new_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_df = averageCoordinates(test_df, 0.5)\nnew_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"drawBBox(test_img_id, new_df)","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}