{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Some abnormal bounding boxes\nThere are some very large and very small bounding boxes in the dataset. Thanks to [Andrew Lukyanenko](https://www.kaggle.com/c/global-wheat-detection/discussion/149032) for bringing this up. ","execution_count":null},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport cv2\nimport re\nimport os\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"def expand_bbox(x):\n    r = np.array(re.findall(\"([0-9]+[.]?[0-9]*)\", x))\n    if len(r) == 0:\n        r = [-1, -1, -1, -1]\n    return r\n\ndf = pd.read_csv(\"/kaggle/input/global-wheat-detection/train.csv\")\n\ndf['x'] = -1\ndf['y'] = -1\ndf['w'] = -1\ndf['h'] = -1\n\ndf[['x', 'y', 'w', 'h']] = np.stack(df['bbox'].apply(lambda x: expand_bbox(x)))\n\ndf['x'] = df['x'].astype(float)\ndf['y'] = df['y'].astype(float)\ndf['w'] = df['w'].astype(float)\ndf['h'] = df['h'].astype(float)\n\ndf.drop(columns=['bbox'], inplace=True)\ndf['x1'] = df['x'] + df['w']\ndf['y1'] = df['y'] + df['h']\ndf['area'] = df['w'] * df['h']\n\ndf[\"image_id\"] = df[\"image_id\"] + \".jpg\"\n\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for cols in df[['x','y','w','h','x1','y1', 'area']].columns:\n    print(f\"min of {cols} column = {np.min(df[cols])} and max of {cols} column = {np.max(df[cols])}\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Small bounding boxes\nFor the small bounding box, I set the threshold to 50. But there are many unsual bounding boxes for the area less than 100.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"small_boxes = df[df['area'] < 50]\nsmall_boxes = small_boxes[['image_id','x','y','w','h','x1','y1','area']]\nsmall_boxes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"size = len(small_boxes['image_id'].unique())\nfig, ax = plt.subplots(nrows = size, ncols = 1, figsize=(50, 50))\nfor i, img_idx in enumerate(small_boxes['image_id'].unique()):\n    images = cv2.imread(os.path.join(\"/kaggle/input/global-wheat-detection/train\", img_idx), cv2.IMREAD_COLOR)\n    images = cv2.cvtColor(images, cv2.COLOR_BGR2RGB).astype(np.float32)\n    images /= 255.0\n    data = small_boxes[small_boxes['image_id'] == img_idx]\n    bbox = data[['x', 'y', 'x1', 'y1']].values\n    area = data['area'].values.item()\n    for box in bbox:\n        ax[i,].add_patch(\n            patches.Rectangle(\n            (box[0], box[1]),\n            box[2]-box[0],\n            box[3]-box[1],\n            linewidth=2,\n            fill=False,\n            color='red'))\n        ax[i,].set_axis_off()\n        ax[i,].set_title(f\"Image with very small bounding box id = {img_idx}, area = {area}\")\n        ax[i,].imshow(images)\nplt.show()\nplt.close()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Large bounding boxes\nFor the large bounding box, I set the threshold to 160000. The area of bounding box between even 100000 and 160000 has some big wheat heads ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"large_boxes = df[df['area'] > 160000] \nlarge_boxes = large_boxes[['image_id','x','y','w','h','x1','y1','area']]\nlarge_boxes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"size = len(large_boxes['image_id'].unique())\nfig, ax = plt.subplots(nrows = size, ncols = 1, figsize=(50, 50))\nfor i, img_idx in enumerate(large_boxes['image_id'].unique()):\n    images = cv2.imread(os.path.join(\"/kaggle/input/global-wheat-detection/train\", img_idx), cv2.IMREAD_COLOR)\n    images = cv2.cvtColor(images, cv2.COLOR_BGR2RGB).astype(np.float32)\n    images /= 255.0\n    data = large_boxes[large_boxes['image_id'] == img_idx]\n    bbox = data[['x', 'y', 'x1', 'y1']].values\n    area = data['area'].values.item()\n    for box in bbox:\n        ax[i,].add_patch(\n            patches.Rectangle(\n            (box[0], box[1]),\n            box[2]-box[0],\n            box[3]-box[1],\n            linewidth=2,\n            fill=False,\n            color='red'))\n        ax[i,].set_axis_off()\n        ax[i,].set_title(f\"Image with very large bounding box id = {img_idx}, area = {area}\")\n        ax[i,].imshow(images)\nplt.show()\nplt.close()","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}