{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom glob import glob\nfrom tqdm import tqdm\nimport ast\nimport cv2\nfrom PIL import Image\nimport matplotlib.patches as patches\nimport albumentations as albu\nfrom albumentations.pytorch.transforms import ToTensor\nfrom albumentations.core.transforms_interface import DualTransform\nfrom albumentations.augmentations.bbox_utils import denormalize_bbox, normalize_bbox","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Setup the paths to train and test images\nTRAIN_DIR = '../input/global-wheat-detection/train/'\nTEST_DIR = '../input/global-wheat-detection/test/'\n# Glob the directories and get the lists of train and test images\ntrain_fns = glob(TRAIN_DIR + '*')\ntest_fns = glob(TEST_DIR + '*')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_data = pd.read_csv(\"/kaggle/input/global-wheat-detection/train.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data.sample(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# How many unique images?\nlen(train_data[\"image_id\"].unique())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Total number of images in the training directory\nprint('Number of train images is {}'.format(len(train_fns)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Number of images without heads are: {}'.format(len(train_fns)- len(train_data[\"image_id\"].unique())))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"This means that 3422 - 3373 i.e. 49 images do not have any annotations.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# stats about data\ntrain_data.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# is there any data with width or height greater than or less than 1024\nprint(train_data[train_data['width'] > 1024])\nprint(\"--------------\")\nprint(train_data[train_data['width'] < 1024])\nprint(\"--------------\")\nprint(train_data[train_data['height'] > 1024])\nprint(\"--------------\")\nprint(train_data[train_data['height'] < 1024])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def count_missing_data(data_df):\n    total = data_df.isnull().sum().sort_values(ascending = False)\n    percent = (data_df.isnull().sum()/data_df.isnull().count()*100).sort_values(ascending = False)\n    return pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"count_missing_data(train_data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Unique sources of data\nsources = train_data['source'].unique()\nprint(\"There are {} unique sources of data: {}\".format(len(sources), sources))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# How many images from each sources\ntrain_data['source'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"f, ax = plt.subplots(1,1, figsize=(11,5))\nsns.countplot(train_data['source'],order = train_data['source'].value_counts().index, palette='Set3')\n\ntotal = float(len(train_data))\nfor p in ax.patches:\n    height = p.get_height()\n    ax.text(p.get_x()+p.get_width()/2.,\n            height + 3,\n            '{:1.2f}% ({:d})'.format(100*height/total, height),\n            ha=\"center\") \nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Create dataframe with all training images\n\ntrain_images_df = pd.DataFrame([fns.split('/')[-1][:-4] for fns in glob(TRAIN_DIR + '*')])\ntrain_images_df.columns=['image_id']\n\n# merge it with bboxes dataframe\ntrain_images_df = train_images_df.merge(train_data, on='image_id', how='left')\n\n\n# replace null values with list of 0\ntrain_images_df['bbox'] = train_images_df.bbox.fillna('[0,0,0,0]')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n# Separating out the coordinates\nbbox_xmin, bbox_ymin, bbox_width,bbox_height  = [], [], [], []\nfor i in tqdm(train_images_df[\"bbox\"]):\n    cooridinates_list = ast.literal_eval(i)\n    bbox_xmin.append(cooridinates_list[0])\n    bbox_ymin.append(cooridinates_list[1])\n    bbox_width.append(cooridinates_list[2])\n    bbox_height.append(cooridinates_list[3])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(bbox_xmin), len(bbox_ymin), len(bbox_width), len(bbox_height)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ntrain_images_df[\"bbox_xmin\"] = bbox_xmin\ntrain_images_df[\"bbox_ymin\"] = bbox_ymin\ntrain_images_df[\"bbox_width\"] = bbox_width\ntrain_images_df[\"bbox_height\"] = bbox_height\ntrain_images_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Locating the wheat location\n\ntrain_images_df['x_center']=(train_images_df['bbox_xmin'] + train_images_df['bbox_width'])/2\ntrain_images_df['y_center']=(train_images_df['bbox_ymin'] + train_images_df['height'])/2\n# Plot x and y centers\nsns.jointplot(\"x_center\", \"y_center\",kind=\"kde\", data=train_images_df, height=9, alpha=0.5)\nplt.suptitle('Wheat location')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Aspect ratio of bounding boxes in the sample\ntrain_images_df['aspect_ratio'] = train_images_df['bbox_width']/train_images_df['bbox_height']\nsns.distplot(train_images_df['aspect_ratio'].dropna(), norm_hist=True)\nplt.title('Distribution plot: Aspect ratio of bounding boxes of images in the sample')\nplt.show()\n\n# Area of bounding boxes in the sample\ntrain_images_df['bbox_area'] = train_images_df['bbox_width']* train_images_df['bbox_height']\nsns.distplot(train_images_df['bbox_area'].dropna(), norm_hist=True)\nplt.title('Distribution plot: Area of bounding boxes of images in the sample')\nplt.show()\n\n# Relationship between aspect ratio and area of bounding boxes of images in the sample\nsns.relplot(x='bbox_area', y='aspect_ratio', data=train_images_df, height=5, alpha=0.7, aspect=1.4)\nplt.title('Aspect ratio and area of bounding boxes of images in the sample')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Sample Images from the Dataset","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Visualizing some samples from the training set\n\nsample_indices = np.random.choice(np.unique(train_data[\"image_id\"].tolist()), 10)\n\nfig, ax = plt.subplots(nrows=2, ncols=5, figsize=(20, 10))\ncount=0\n\nfor row in ax:\n    for col in row:\n        img = plt.imread(TRAIN_DIR  + sample_indices[count] + \".jpg\")\n        col.grid(False)\n        col.set_xticks([])\n        col.set_yticks([])\n        col.imshow(img)\n        count += 1\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Images with the Bounding Box ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_bbox(image_id, df, col, color='white'):\n    bboxes = df[df['image_id'] == image_id]\n    \n    for i in range(len(bboxes)):\n        # Create a Rectangle patch\n        rect = patches.Rectangle(\n            (bboxes['bbox_xmin'].iloc[i], bboxes['bbox_ymin'].iloc[i]),\n            bboxes['bbox_width'].iloc[i], \n            bboxes['bbox_height'].iloc[i], \n            linewidth=2, \n            edgecolor=color, \n            facecolor='none')\n\n        # Add the patch to the Axes\n        col.add_patch(rect)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(nrows=2, ncols=5, figsize=(20, 10))\ncount=0\nfor row in ax:\n    for col in row:\n        img = plt.imread(TRAIN_DIR + sample_indices[count] + \".jpg\")\n        col.grid(False)\n        col.set_xticks([])\n        col.set_yticks([])\n        get_bbox(sample_indices[count], train_images_df, col, color='red')\n        col.imshow(img)\n        count += 1\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Images with no bounding boxes","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Images with bounding box\nimages_with_bbox = train_data[\"image_id\"].unique()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images_without_bbox = list(set(train_fns) - set(images_with_bbox))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Visualizing some images without any bounding box \n\nfig, ax = plt.subplots(nrows=2, ncols=5, figsize=(20, 10))\ncount=0\n\nfor row in ax:\n    for col in row:\n        img = plt.imread(images_without_bbox[count])\n        col.grid(False)\n        col.set_xticks([])\n        col.set_yticks([])\n        col.imshow(img)\n        count += 1\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_images_df.sample(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# This function will take dataframe and image_id for which we want bounding boxes and return list of x, y, w, h\n\ndef get_all_bboxes(dataframe, image_id):\n  image_bounding_boxes = dataframe[dataframe.image_id == image_id]\n  \n  bounding_boxes = []\n  for _, row in image_bounding_boxes.iterrows():\n    bounding_boxes.append((row.bbox_xmin, row.bbox_ymin, row.bbox_width, row.bbox_height))\n    \n  return bounding_boxes\n        \n    \n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_image_examples(dataframe, rows = 2, cols = 5, title = 'Image examples', size = (20, 10)):\n  fig, axs = plt.subplots(rows, cols, figsize=size)\n  for row in range(rows):\n    for col in range(cols):\n      idx = np.random.randint(len(dataframe), size = 1)[0]\n      img_id = dataframe.iloc[idx].image_id\n      \n      img = Image.open(TRAIN_DIR + img_id + '.jpg')\n      axs[row, col].imshow(img)\n      \n      bboxes = get_all_bboxes(dataframe, img_id)\n      \n      for bbox in bboxes:\n        rect = patches.Rectangle((bbox[0], bbox[1]), bbox[2], bbox[3], linewidth=1, edgecolor='r', facecolor='none')\n        axs[row, col].add_patch(rect)\n        \n        axs[row, col].axis('off')    \n  plt.suptitle(title)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# number of bouding boxes per train image\ntrain_images_df['count'] = train_images_df.apply(lambda row: 1 if np.isfinite(row.width) else 0, axis=1)\ntrain_images_df_count = train_images_df.groupby('image_id').sum().reset_index()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_images_df['bbox_xmax'] = train_images_df['bbox_xmin'] + train_images_df['bbox_width']\ntrain_images_df['bbox_ymax'] = train_images_df['bbox_ymin'] + train_images_df['bbox_height']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"less_spikes_ids = train_images_df_count[train_images_df_count['count'] < 10].image_id\nplot_image_examples(train_images_df[train_images_df[\"image_id\"].isin(less_spikes_ids)], title='Example images with small number of spikes')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"more_spikes_ids = train_images_df_count[train_images_df_count['count'] > 100].image_id\nplot_image_examples(train_images_df[train_images_df[\"image_id\"].isin(more_spikes_ids)], title='Example images with more number of spikes')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Image with usask_1 source\nusask_1_images = train_images_df[train_images_df['source'] == 'usask_1'].image_id\nplot_image_examples(train_images_df[train_images_df.image_id.isin(usask_1_images)], title='Images with source usask_1')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Image with arvalis_1 source\narvalis_1_images = train_images_df[train_images_df['source'] == 'arvalis_1'].image_id\nplot_image_examples(train_images_df[train_images_df.image_id.isin(arvalis_1_images)], title='Images with source arvalis_1')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Image with inrae_1 source\ninrae_1_images = train_images_df[train_images_df['source'] == 'inrae_1'].image_id\nplot_image_examples(train_images_df[train_images_df.image_id.isin(inrae_1_images)], title='Images with source inrae_1')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Image with arvalis_3 source\narvalis_3_images = train_images_df[train_images_df['source'] == 'arvalis_3'].image_id\nplot_image_examples(train_images_df[train_images_df.image_id.isin(arvalis_3_images)], title='Images with source arvalis_3')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Image with rres_1 source\nrres_1_images = train_images_df[train_images_df['source'] == 'rres_1'].image_id\nplot_image_examples(train_images_df[train_images_df.image_id.isin(rres_1_images)], title='Images with source rres_1')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Image with arvalis_2 source\n\narvalis_2_images = train_images_df[train_images_df['source'] == 'arvalis_2'].image_id\nplot_image_examples(train_images_df[train_images_df.image_id.isin(arvalis_2_images)], title='Images with source arvalis_2')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Image with ethz_1 source\n\nethz_1_images = train_images_df[train_images_df['source'] == 'ethz_1'].image_id\nplot_image_examples(train_images_df[train_images_df.image_id.isin(ethz_1_images)], title='Images with source ethz_1')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_images_df[\"bbox_area\"].max()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Example images with large bounding box area\nlarge_boxes_ids = train_images_df[train_images_df['bbox_area'] > 200000].image_id\nplot_image_examples(train_images_df[train_images_df.image_id.isin(large_boxes_ids)], title='Example images with large bbox area')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"min_area = train_images_df[train_images_df['bbox_area'] > 0].bbox_area.min()\nprint('The smallest bouding box area is {}'.format(min_area))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Example images with small bounding box area\nsmall_boxes_ids = train_images_df[(train_images_df['bbox_area'] < 25) & (train_images_df['bbox_area'] > 0)].image_id\nplot_image_examples(train_images_df[train_images_df.image_id.isin(small_boxes_ids)], title='Example images with small bbox area')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# compute the total bounding boxes area per image\narea_per_image = train_images_df.groupby(by='image_id').sum().reset_index()\n\n# compute the percentage of the image area covered by bounding boxes\narea_per_image_percentage = area_per_image.copy()\narea_per_image_percentage['bbox_area'] = area_per_image_percentage['bbox_area'] / (1024*1024) * 100","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Example images with small percentage of area covered by bounding boxes\n\nsmall_area_perc_ids = area_per_image_percentage[area_per_image_percentage['bbox_area'] < 7].image_id\nplot_image_examples(train_images_df[train_images_df.image_id.isin(small_area_perc_ids)], title='Example images with small percentage of area covered by bounding boxes')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Example images with large percentage of area covered by bounding boxes\nlarge_area_perc_ids = area_per_image_percentage[area_per_image_percentage['bbox_area'] > 95].image_id\nplot_image_examples(train_images_df[train_images_df.image_id.isin(large_area_perc_ids)], title='Example images with large percentage of area covered by bounding boxes')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_image_brightness(image):\n    # convert to grayscale\n    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n    \n    # get average brightness\n    return np.array(gray).mean()\n\ndef add_brightness(df):\n    brightness = []\n    for _, row in df.iterrows():\n        img_id = row.image_id\n        image = cv2.imread(TRAIN_DIR + img_id + '.jpg')\n        brightness.append(get_image_brightness(image))\n        \n    brightness_df = pd.DataFrame(brightness)\n    brightness_df.columns = ['brightness']\n    df = pd.concat([df, brightness_df], ignore_index=True, axis=1)\n    df.columns = ['image_id', 'brightness']\n    \n    return df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images_df = pd.DataFrame(train_images_df.image_id.unique())\nimages_df.columns = ['image_id']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# add brightness to the dataframe\nimages_df = pd.DataFrame(train_images_df.image_id.unique())\nimages_df.columns = ['image_id']\nbrightness_df = add_brightness(images_df)\n\ntrain_images_df = train_images_df.merge(brightness_df, on='image_id')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# darkest images\ndark_ids = train_images_df[train_images_df['brightness'] < 30].image_id\nplot_image_examples(train_images_df[train_images_df.image_id.isin(dark_ids)], title=\"darkest images\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Brightest images\nbright_ids = train_images_df[train_images_df['brightness'] > 130].image_id\nplot_image_examples(train_images_df[train_images_df.image_id.isin(bright_ids)], title='Brightest images')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_percentage_of_green_pixels(image):\n  # convert to HSV\n  hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n  \n  # get the green mask\n  hsv_lower = (40, 40, 40) \n  hsv_higher = (70, 255, 255)\n  green_mask = cv2.inRange(hsv, hsv_lower, hsv_higher)\n  \n  return float(np.sum(green_mask)) / 255 / (1024 * 1024)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_percentage_of_yellow_pixels(image):\n  # convert to HSV\n  hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n  \n  # get the green mask\n  hsv_lower = (25, 40, 40)\n  hsv_higher = (35, 255, 255)\n  yellow_mask = cv2.inRange(hsv, hsv_lower, hsv_higher)\n  \n  return float(np.sum(yellow_mask)) / 255 / (1024 * 1024)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def add_green_pixels_percentage(df):\n  green = []\n  for _, row in df.iterrows():\n    img_id = row.image_id\n    image = cv2.imread(TRAIN_DIR + img_id + '.jpg')\n    green.append(get_percentage_of_green_pixels(image))\n    \n  green_df = pd.DataFrame(green)\n  green_df.columns = ['green_pixels']\n  df = pd.concat([df, green_df], ignore_index=True, axis=1)\n  df.columns = ['image_id', 'green_pixels']\n  \n  return df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def add_yellow_pixels_percentage(df):\n  yellow = []\n  for _, row in df.iterrows():\n    img_id = row.image_id\n    image = cv2.imread(TRAIN_DIR + img_id + '.jpg')\n    yellow.append(get_percentage_of_yellow_pixels(image))\n    \n  yellow_df = pd.DataFrame(yellow)\n  yellow_df.columns = ['yellow_pixels']\n  df = pd.concat([df, yellow_df], ignore_index=True, axis=1)\n  df.columns = ['image_id', 'yellow_pixels']\n    \n  return df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# add a column with the percentage of green pixels\ngreen_pixels_df = add_green_pixels_percentage(images_df)\ntrain_images_df = train_images_df.merge(green_pixels_df, on='image_id')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# The most green images\ngreen_ids = train_images_df[train_images_df['green_pixels'] > 0.55].image_id\nplot_image_examples(train_images_df[train_images_df.image_id.isin(green_ids)], title='The most green images')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# add a column with the percentage of yellow pixels\nyellow_pixels_df = add_yellow_pixels_percentage(images_df)\ntrain_images_df = train_images_df.merge(yellow_pixels_df, on='image_id')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# The most yellow images\nyellow_ids = train_images_df[train_images_df['yellow_pixels'] > 0.55].image_id\nplot_image_examples(train_images_df[train_images_df.image_id.isin(yellow_ids)], title='The most yellow images')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Here we are trying little Augmentation\nexample_transforms = albu.Compose([\n    albu.RandomSizedBBoxSafeCrop(512, 512, erosion_rate=0.0, interpolation=1, p=1.0),\n    albu.HorizontalFlip(p=0.5),\n    albu.VerticalFlip(p=0.5),\n    albu.OneOf([albu.RandomContrast(),\n                albu.RandomGamma(),\n                albu.RandomBrightness()], p=1.0),\n    albu.CLAHE(p=1.0)], p=1.0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def apply_transforms(transforms, df, n_transforms=3):\n  idx = np.random.randint(len(df), size=1)[0]\n  \n  image_id = df.iloc[idx].image_id\n  bboxes = []\n  for _, row in df[df.image_id == image_id].iterrows():\n    bboxes.append([row.bbox_xmin, row.bbox_ymin, row.bbox_width, row.bbox_height])\n    \n  image = Image.open(TRAIN_DIR + image_id + '.jpg')\n  \n  fig, axs = plt.subplots(1, n_transforms+1, figsize=(15,7))\n  \n  # plot the original image\n  axs[0].imshow(image)\n  axs[0].set_title('original')\n  for bbox in bboxes:\n    rect = patches.Rectangle((bbox[0],bbox[1]),bbox[2],bbox[3],linewidth=1,edgecolor='r',facecolor='none')\n    axs[0].add_patch(rect)\n    \n  # apply transforms n_transforms times\n  for i in range(n_transforms):\n    params = {'image': np.asarray(image),\n              'bboxes': bboxes,\n              'category_id': [1 for j in range(len(bboxes))]}\n    augmented_boxes = transforms(**params)\n    bboxes_aug = augmented_boxes['bboxes']\n    image_aug = augmented_boxes['image']\n    \n    # plot the augmented image and augmented bounding boxes\n    axs[i+1].imshow(image_aug)\n    axs[i+1].set_title('augmented_' + str(i+1))\n    for bbox in bboxes_aug:\n      rect = patches.Rectangle((bbox[0],bbox[1]),bbox[2],bbox[3],linewidth=1,edgecolor='r',facecolor='none')\n      axs[i+1].add_patch(rect)\n  plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"apply_transforms(example_transforms, train_images_df, n_transforms=3)","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}