{"cells":[{"metadata":{},"cell_type":"markdown","source":"In this notebook I want to share how to visualize image data with bounding boxes and possible augmentations with bounding boxes (90, 180, 270 degrees rotatation and Horizontal, Vertical flip). This is simple but powerful technique that can help in training.\n\nPlease go through the notebook.","execution_count":null},{"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    print(dirname)\n\n# You can write up to 5GB 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 matplotlib.pyplot as plt\n%matplotlib inline\nimport cv2","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_csv = '../input/global-wheat-detection/train.csv'\ndata = pd.read_csv(train_csv)\ndata","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.isnull().any()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(f'Total number of train images: {data.image_id.nunique()}')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Extract bbox column to xmin, ymin, width, height, then create xmax, ymax, and area columns\n\ndata[['xmin','ymin','w','h']] = pd.DataFrame(data.bbox.str.strip('[]').str.split(',').tolist()).astype(float)\ndata['xmax'], data['ymax'], data['area'] = data['xmin'] + data['w'], data['ymin'] + data['h'], data['w'] * data['h']\ndata.drop(['bbox'], axis=1, inplace= True)\ndata","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"DATA_DIR = '../input/global-wheat-detection/train/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def show_image(image_id):\n    \n    fig, ax = plt.subplots(1, 2, figsize = (24, 24))\n    ax = ax.flatten()\n    \n    bbox = data[data['image_id'] == image_id ]\n    img_path = os.path.join(DATA_DIR, image_id + '.jpg')\n    \n    image = cv2.imread(img_path)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)\n    image /= 255.0\n    image2 = image\n    \n    ax[0].set_title('Original Image')\n    ax[0].imshow(image)\n    \n    for idx, row in bbox.iterrows():\n        x1 = row['xmin']\n        y1 = row['ymin']\n        x2 = row['xmax']\n        y2 = row['ymax']\n        label = row['source']\n        \n        cv2.rectangle(image2, (int(x1),int(y1)), (int(x2),int(y2)), (255,255,255), 2)\n        font = cv2.FONT_HERSHEY_SIMPLEX\n        cv2.putText(image2, label, (int(x1),int(y1-10)), font, 0.8, (255,255,255), 2)\n    \n    ax[1].set_title('Image with Bondary Box')\n    ax[1].imshow(image2)\n\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"show_image(data.image_id.unique()[90])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"show_image(data.image_id.unique()[300])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"show_image(data.image_id.unique()[1900])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"show_image(data.image_id.unique()[2500])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def augument_bbox(width, height, xmin, ymin, xmax, ymax, aug_type=90):\n    bbh = xmax - xmin\n    bbw = ymax - ymin\n    if aug_type == 90:\n        ymin = xmin\n        xmin = height - ymax\n        xmax = xmin + bbw\n        ymax = ymin + bbh\n    if aug_type == 180:\n        xmin = width - xmax\n        ymin = height - ymax\n        xmax = xmin + bbh\n        ymax = ymin + bbw\n    if aug_type == 270:\n        xmin = ymin\n        ymin = width - xmax\n        xmax = xmin + bbw\n        ymax = ymin + bbh\n    if aug_type == 'Horizontal':\n        ymin = ymin\n        xmin = width - xmax\n        xmax = xmin + bbh\n        ymax = ymin + bbw\n    if aug_type == 'Vertical':\n        xmin = xmin\n        ymin = height - ymax\n        xmax = xmin + bbh\n        ymax = ymin + bbw\n    return xmin, ymin, xmax, ymax","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def show_aug_images(image_id, aug_types):\n    for aug_type in aug_types:\n\n        fig, ax = plt.subplots(1, 2, figsize = (24, 24))\n        ax = ax.flatten()\n\n        bbox = data[data['image_id'] == image_id ]\n        img_path = os.path.join(DATA_DIR, image_id + '.jpg')\n\n        image = cv2.imread(img_path, cv2.IMREAD_COLOR)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)\n        image /= 255.0\n        \n        if aug_type == 90:\n            image2 = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)\n            color = (255, 0, 0)\n        if aug_type == 180:\n            image2 = cv2.rotate(image, cv2.ROTATE_180)\n            color = (0, 255, 0)\n        if aug_type == 270:\n            image2 = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)\n            color = (0, 0, 255)\n        if aug_type == 'Horizontal':\n            image2 = cv2.flip(image, 1)\n            color = (255, 255, 0)\n        if aug_type == 'Vertical':\n            image2 = cv2.flip(image, 0)\n            color = (0, 255, 255)\n        \n        for idx, row in bbox.iterrows():\n            x1 = row['xmin']\n            y1 = row['ymin']\n            x2 = row['xmax']\n            y2 = row['ymax']\n            label = row['source']\n\n            cv2.rectangle(image, (int(x1),int(y1)), (int(x2),int(y2)), (255,255,255), 4)\n            if aug_type == 90:\n                cv2.circle(image, (int(x1), int(y2)), 6, (0, 0, 255), -1)\n            if aug_type == 180:\n                cv2.circle(image, (int(x2), int(y2)), 6, (255, 0, 0), -1)\n            if aug_type == 270:\n                cv2.circle(image, (int(x2), int(y1)), 6, (0, 255, 0), -1)\n            if aug_type == 'Horizontal':\n                cv2.circle(image, (int(x2), int(y1)), 6, (0, 0, 255), -1)\n            if aug_type == 'Vertical':\n                cv2.circle(image, (int(x1), int(y2)), 6, (255, 0, 0), -1)\n\n        ax[0].set_title('Original Image with Bondary Boxes')\n        ax[0].imshow(image)\n\n        for idx, row in bbox.iterrows():\n            x1 = row['xmin']\n            y1 = row['ymin']\n            x2 = row['xmax']\n            y2 = row['ymax']\n            width = row['width'] \n            height = row['height']\n            label = row['source']\n            \n            x1, y1, x2, y2 = augument_bbox(int(width), int(height), int(x1), int(y1), int(x2), int(y2), aug_type)\n            \n            cv2.rectangle(image2, (int(x1),int(y1)), (int(x2),int(y2)), color, 4)\n            if aug_type == 90:\n                cv2.circle(image2, (int(x1), int(y1)), 6, (0, 0, 255), -1)\n            if aug_type == 180:\n                cv2.circle(image2, (int(x1), int(y1)), 6, (255, 0, 0), -1)\n            if aug_type == 270:\n                cv2.circle(image2, (int(x1), int(y1)), 6, (0, 255, 0), -1)\n            if aug_type == 'Horizontal':\n                cv2.circle(image2, (int(x1), int(y1)), 6, (0, 0, 255), -1)\n            if aug_type == 'Vertical':\n                cv2.circle(image2, (int(x1), int(y1)), 6, (255, 0, 0), -1)\n\n        ax[1].set_title(str(aug_type) + ' (degrees rotated/Flipped) Agumented Image with Bondary Boxes')\n        ax[1].imshow(image2)\n\n        plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"aug_types = [90, 180, 270, 'Horizontal', 'Vertical']\nshow_aug_images(data.image_id.unique()[90], aug_types)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"show_aug_images(data.image_id.unique()[300], aug_types)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"show_aug_images(data.image_id.unique()[1900], aug_types)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"show_aug_images(data.image_id.unique()[2500], aug_types)","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}