import os
import pandas as pd
import torchvision32.6 The Object Detection Dataset
There is no small dataset such as MNIST and Fashion-MNIST in the field of object detection. In order to quickly demonstrate object detection models, we collected and labeled a small dataset. First, we took photos of free bananas from our office and generated 1000 banana images with different rotations and sizes. Then we placed each banana image at a random position on some background image. In the end, we labeled bounding boxes for those bananas on the images.
32.6.1 Downloading the Dataset
The banana detection dataset with all the image and csv label files can be downloaded directly from the Internet.
import os
import pandas as pd
from PIL import Imageimport os
import pandas as pd
from PIL import Imageimport os
import pandas as pd
from mxnet import imaged2l.DATA_HUB['banana-detection'] = (
d2l.DATA_URL + 'banana-detection.zip',
'5de26c8fce5ccdea9f91267273464dc968d20d72')32.6.2 Reading the Dataset
We are going to read the banana detection dataset in the read_data_bananas function below. The dataset includes a csv file for object class labels and ground-truth bounding box coordinates at the upper-left and lower-right corners.
def read_data_bananas(is_train=True):
"""Read the banana detection dataset images and labels."""
data_dir = d2l.download_extract('banana-detection')
csv_fname = os.path.join(data_dir, 'bananas_train' if is_train
else 'bananas_val', 'label.csv')
csv_data = pd.read_csv(csv_fname)
csv_data = csv_data.set_index('img_name')
images, targets = [], []
for img_name, target in csv_data.iterrows():
images.append(torchvision.io.read_image(
os.path.join(data_dir, 'bananas_train' if is_train else
'bananas_val', 'images', f'{img_name}')))
# Here `target` contains (class, upper-left x, upper-left y,
# lower-right x, lower-right y), where all the images have the same
# banana class (index 0)
targets.append(list(target))
return images, torch.tensor(targets).unsqueeze(1) / 256
def read_data_bananas(is_train=True):
"""Read the banana detection dataset images and labels."""
from PIL import Image
data_dir = d2l.download_extract('banana-detection')
csv_fname = os.path.join(data_dir, 'bananas_train' if is_train
else 'bananas_val', 'label.csv')
csv_data = pd.read_csv(csv_fname)
csv_data = csv_data.set_index('img_name')
images, targets = [], []
for img_name, target in csv_data.iterrows():
img = Image.open(
os.path.join(data_dir, 'bananas_train' if is_train else
'bananas_val', 'images', f'{img_name}'))
images.append(tf.constant(np.array(img), dtype=tf.float32))
# Here `target` contains (class, upper-left x, upper-left y,
# lower-right x, lower-right y), where all the images have the same
# banana class (index 0)
targets.append(list(target))
return images, tf.expand_dims(tf.constant(targets, dtype=tf.float32),
axis=1) / 256
def read_data_bananas(is_train=True):
"""Read the banana detection dataset images and labels."""
from PIL import Image
data_dir = d2l.download_extract('banana-detection')
csv_fname = os.path.join(data_dir, 'bananas_train' if is_train
else 'bananas_val', 'label.csv')
csv_data = pd.read_csv(csv_fname)
csv_data = csv_data.set_index('img_name')
images, targets = [], []
for img_name, target in csv_data.iterrows():
img = Image.open(
os.path.join(data_dir, 'bananas_train' if is_train else
'bananas_val', 'images', f'{img_name}'))
images.append(jnp.array(img).transpose(2, 0, 1))
# Here `target` contains (class, upper-left x, upper-left y,
# lower-right x, lower-right y), where all the images have the same
# banana class (index 0)
targets.append(list(target))
return images, jnp.expand_dims(jnp.array(targets), axis=1) / 256
def read_data_bananas(is_train=True):
"""Read the banana detection dataset images and labels."""
data_dir = d2l.download_extract('banana-detection')
csv_fname = os.path.join(data_dir, 'bananas_train' if is_train
else 'bananas_val', 'label.csv')
csv_data = pd.read_csv(csv_fname)
csv_data = csv_data.set_index('img_name')
images, targets = [], []
for img_name, target in csv_data.iterrows():
images.append(image.imread(
os.path.join(data_dir, 'bananas_train' if is_train else
'bananas_val', 'images', f'{img_name}')))
# Here `target` contains (class, upper-left x, upper-left y,
# lower-right x, lower-right y), where all the images have the same
# banana class (index 0)
targets.append(list(target))
return images, mnp.expand_dims(mnp.array(targets), 1) / 256By using the read_data_bananas function to read images and labels, the following BananasDataset class will allow us to create a customized dataset class for loading the banana detection dataset.
class BananasDataset(torch.utils.data.Dataset):
"""A customized dataset to load the banana detection dataset."""
def __init__(self, is_train):
self.features, self.labels = read_data_bananas(is_train)
print('read ' + str(len(self.features)) + (f' training examples' if
is_train else f' validation examples'))
def __getitem__(self, idx):
return (self.features[idx].float(), self.labels[idx])
def __len__(self):
return len(self.features)
class BananasDataset:
"""A customized dataset to load the banana detection dataset."""
def __init__(self, is_train):
self.features, self.labels = read_data_bananas(is_train)
print('read ' + str(len(self.features)) + (f' training examples' if
is_train else f' validation examples'))
def __getitem__(self, idx):
return (self.features[idx], self.labels[idx])
def __len__(self):
return len(self.features)
class BananasDataset:
"""A customized dataset to load the banana detection dataset."""
def __init__(self, is_train):
self.features, self.labels = read_data_bananas(is_train)
print('read ' + str(len(self.features)) + (f' training examples' if
is_train else f' validation examples'))
def __getitem__(self, idx):
return (self.features[idx].astype(jnp.float32), self.labels[idx])
def __len__(self):
return len(self.features)
class BananasDataset(gluon.data.Dataset):
"""A customized dataset to load the banana detection dataset."""
def __init__(self, is_train):
self.features, self.labels = read_data_bananas(is_train)
print('read ' + str(len(self.features)) + (f' training examples' if
is_train else f' validation examples'))
def __getitem__(self, idx):
return (self.features[idx].astype('float32').transpose(2, 0, 1),
self.labels[idx])
def __len__(self):
return len(self.features)Finally, we define the load_data_bananas function to return two data iterator instances for both the training and test sets. For the test dataset, there is no need to read it in random order.
def load_data_bananas(batch_size):
"""Load the banana detection dataset."""
train_iter = torch.utils.data.DataLoader(BananasDataset(is_train=True),
batch_size, shuffle=True)
val_iter = torch.utils.data.DataLoader(BananasDataset(is_train=False),
batch_size)
return train_iter, val_iter
def load_data_bananas(batch_size):
"""Load the banana detection dataset."""
train_dataset = BananasDataset(is_train=True)
val_dataset = BananasDataset(is_train=False)
# Stack images: result shape is (N, H, W, C) — NHWC for TF
train_images = tf.stack(train_dataset.features)
val_images = tf.stack(val_dataset.features)
train_iter = tf.data.Dataset.from_tensor_slices(
(train_images, train_dataset.labels))
# `drop_remainder=True` keeps every training minibatch the same
# shape so the SSD `train_step` (`@tf.function`-wrapped at the call
# site in :numref:`sec_ssd`) traces once per epoch shape instead of
# retracing for the smaller last batch.
train_iter = train_iter.shuffle(len(train_dataset.features)).batch(
batch_size, drop_remainder=True).prefetch(tf.data.AUTOTUNE)
val_iter = tf.data.Dataset.from_tensor_slices(
(val_images, val_dataset.labels))
val_iter = val_iter.batch(batch_size).prefetch(tf.data.AUTOTUNE)
return train_iter, val_iter
def load_data_bananas(batch_size):
"""Load the banana detection dataset."""
train_dataset = BananasDataset(is_train=True)
val_dataset = BananasDataset(is_train=False)
train_iter = d2l.ArrayDataLoader(
jnp.stack(train_dataset.features), train_dataset.labels,
batch_size=batch_size, shuffle=True)
val_iter = d2l.ArrayDataLoader(
jnp.stack(val_dataset.features), val_dataset.labels,
batch_size=batch_size)
return train_iter, val_iter
def load_data_bananas(batch_size):
"""Load the banana detection dataset."""
train_iter = gluon.data.DataLoader(BananasDataset(is_train=True),
batch_size, shuffle=True)
val_iter = gluon.data.DataLoader(BananasDataset(is_train=False),
batch_size)
return train_iter, val_iterLet’s read a minibatch and print the shapes of both images and labels in this minibatch. The shape of the image minibatch looks familiar: it is the same as in our earlier image classification tasks. The shape of the label minibatch is (batch size, \(m\), 5), where \(m\) is the largest possible number of bounding boxes that any image has in the dataset.
The image minibatch has the shape (batch size, number of channels, height, width).
TensorFlow keeps the channels last, so the image minibatch has the shape (batch size, height, width, number of channels).
The image minibatch has the shape (batch size, number of channels, height, width).
The image minibatch has the shape (batch size, number of channels, height, width).
Although computation in minibatches is more efficient, it requires that all the image examples contain the same number of bounding boxes to form a minibatch via concatenation. In general, images may have a varying number of bounding boxes; thus, images with fewer than \(m\) bounding boxes will be padded with illegal bounding boxes until \(m\) is reached. Then the label of each bounding box is represented by an array of length 5. The first element in the array is the class of the object in the bounding box, where -1 indicates an illegal bounding box for padding. The remaining four elements of the array are the (\(x\), \(y\))-coordinate values of the upper-left corner and the lower-right corner of the bounding box (the range is between 0 and 1). For the banana dataset, since there is only one bounding box on each image, we have \(m=1\).
batch_size, edge_size = 32, 256
train_iter, _ = load_data_bananas(batch_size)
batch = next(iter(train_iter))
batch[0].shape, batch[1].shaperead 1000 training examples
read 100 validation examples
(torch.Size([32, 3, 256, 256]), torch.Size([32, 1, 5]))
read 1000 training examples
read 100 validation examples
(TensorShape([32, 256, 256, 3]), TensorShape([32, 1, 5]))
read 1000 training examples
read 100 validation examples
((32, 3, 256, 256), (32, 1, 5))
read 1000 training examples
read 100 validation examples
((32, 3, 256, 256), (32, 1, 5))
32.6.3 Demonstration
Let’s demonstrate ten images with their labeled ground-truth bounding boxes. We can see that the rotations, sizes, and positions of bananas vary across all these images. Of course, this is just a simple artificial dataset. In practice, real-world datasets are usually much more complicated.
imgs = (batch[0][:10].permute(0, 2, 3, 1)) / 255
axes = d2l.show_images(imgs, 2, 5, scale=2)
for ax, label in zip(axes, batch[1][:10]):
d2l.show_bboxes(ax, [label[0][1:5] * edge_size], colors=['w'])
# Images are already NHWC (H, W, C) in TF; normalize to [0, 1]
imgs = batch[0][:10] / 255
axes = d2l.show_images(imgs, 2, 5, scale=2)
for ax, label in zip(axes, batch[1][:10]):
d2l.show_bboxes(ax, [label[0][1:5] * edge_size], colors=['w'])
imgs = jnp.transpose(batch[0][:10], (0, 2, 3, 1)) / 255
axes = d2l.show_images(imgs, 2, 5, scale=2)
for ax, label in zip(axes, np.array(batch[1][:10])):
d2l.show_bboxes(ax, [label[0][1:5] * edge_size], colors=['w'])
imgs = (batch[0][:10].transpose(0, 2, 3, 1)) / 255
axes = d2l.show_images(imgs, 2, 5, scale=2)
for ax, label in zip(axes, batch[1][:10]):
d2l.show_bboxes(ax, [label[0][1:5] * edge_size], colors=['w'])
32.6.4 Summary
- The banana detection dataset we collected can be used to demonstrate object detection models.
- The data loading for object detection is similar to that for image classification. However, in object detection the labels also contain information of ground-truth bounding boxes, which is missing in image classification.
32.6.5 Exercises
- Demonstrate other images with ground-truth bounding boxes in the banana detection dataset. How do they differ with respect to bounding boxes and objects?
- Say that we want to apply data augmentation, such as random cropping, to object detection. How can it be different from that in image classification? Hint: what if a cropped image only contains a small portion of an object?
- Compute the width, height, aspect ratio (width divided by height), and area of every training box returned by
read_data_bananas, in units of the image size. Plot their histograms and report the minimum, median, and maximum of each. Then generate one anchor per position (size 0.2, ratio 1) withd2l.multibox_prioron feature maps of size \(4 \times 4\), \(8 \times 8\), \(16 \times 16\), and \(32 \times 32\), and used2l.box_iouto report for each the fraction of training boxes whose best anchor has IoU at least 0.5. What is the coarsest feature map that covers at least 99% of the boxes? On the \(8 \times 8\) map, how much does adding the sizes and ratios of your choice raise the fraction, compared with halving the grid step? - Implement the random crop of problem 2 for the banana dataset: crop a random \(192 \times 192\) window from each \(256 \times 256\) training image, resize the window back to \(256 \times 256\), and shift, clip, and rescale the box label accordingly. Plot a few augmented images with their boxes to check the labels. Report the fraction of training images in which less than half of the banana’s area remains inside the window. What label would you give such an image?
- Images with fewer than \(m\) boxes are padded with illegal boxes of class \(-1\). Check what the implementation of
multibox_targetin Section 32.4 does with such a box: append the row[-1, 0, 0, 0, 0]to the dog and cat labels of the example in Section 32.4.3, and compare the returned class labels, masks, and offsets with and without it.- Which anchor does the loop in
assign_anchor_to_bboxassign to the padding box, and why that one? - What class label, mask, and offset label does that anchor receive, and how would they affect the loss of a detector trained on these labels?
- Modify
multibox_targetso that it ignores padding boxes, and check that its output then matches the unpadded case.
- Which anchor does the loop in