14.4. 锚框
在 Colab 中打开 Notebook
在 Colab 中打开 Notebook
在 Colab 中打开 Notebook
在 Colab 中打开 Notebook
在 SageMaker Studio Lab 中打开 Notebook

目标检测算法通常会在输入图像中采样大量的区域,然后判断这些区域中是否包含我们感兴趣的目标,并调整区域边界从而更准确地预测目标的 *真实边界框*(ground-truth bounding box)。不同的模型使用的区域采样方法可能不同。这里我们介绍其中的一种方法:它以每个像素为中心生成多个大小和宽高比(aspect ratio)不同的边界框。这些边界框被称为 *锚框*(anchor box)。我们将在 14.7节中基于锚框设计一个目标检测模型。

首先,让我们修改打印精度,以便更简洁地输出。

%matplotlib inline
import torch
from d2l import torch as d2l

torch.set_printoptions(2)  # Simplify printing accuracy
%matplotlib inline
from mxnet import gluon, image, np, npx
from d2l import mxnet as d2l

np.set_printoptions(2)  # Simplify printing accuracy
npx.set_np()

14.4.1. 生成多个锚框

假设输入图像的高度为 \(h\),宽度为 \(w\)。我们以图像的每个像素为中心生成不同形状的锚框。设 *缩放比* 为 \(s\in (0, 1]\),*宽高比*(宽度与高度的比率)是 \(r > 0\)。那么,锚框的宽度和高度分别是 \(ws\sqrt{r}\)\(hs/\sqrt{r}\)。请注意,当中心位置给定时,已知宽度和高度的锚框是确定的。

要生成多个不同形状的锚框,让我们设置一系列缩放比 \(s_1,\ldots, s_n\) 和一系列宽高比 \(r_1,\ldots, r_m\)。当使用这些缩放比和宽高比的所有组合,并以每个像素为中心时,输入图像将总共有 \(whnm\) 个锚框。虽然这些锚框可能会覆盖所有真实边界框,但计算复杂度很容易过高。在实践中,我们只考虑那些包含 \(s_1\)\(r_1\) 的组合:

(14.4.1)\[(s_1, r_1), (s_1, r_2), \ldots, (s_1, r_m), (s_2, r_1), (s_3, r_1), \ldots, (s_n, r_1).\]

也就是说,以同一像素为中心的锚框的数量是 \(n+m-1\)。对于整个输入图像,我们将总共生成 \(wh(n+m-1)\) 个锚框。

上述生成锚框的方法在下面的 multibox_prior 函数中实现。我们指定输入图像、缩放比列表和宽高比列表,然后该函数将返回所有的锚框。

#@save
def multibox_prior(data, sizes, ratios):
    """Generate anchor boxes with different shapes centered on each pixel."""
    in_height, in_width = data.shape[-2:]
    device, num_sizes, num_ratios = data.device, len(sizes), len(ratios)
    boxes_per_pixel = (num_sizes + num_ratios - 1)
    size_tensor = torch.tensor(sizes, device=device)
    ratio_tensor = torch.tensor(ratios, device=device)
    # Offsets are required to move the anchor to the center of a pixel. Since
    # a pixel has height=1 and width=1, we choose to offset our centers by 0.5
    offset_h, offset_w = 0.5, 0.5
    steps_h = 1.0 / in_height  # Scaled steps in y axis
    steps_w = 1.0 / in_width  # Scaled steps in x axis

    # Generate all center points for the anchor boxes
    center_h = (torch.arange(in_height, device=device) + offset_h) * steps_h
    center_w = (torch.arange(in_width, device=device) + offset_w) * steps_w
    shift_y, shift_x = torch.meshgrid(center_h, center_w, indexing='ij')
    shift_y, shift_x = shift_y.reshape(-1), shift_x.reshape(-1)

    # Generate `boxes_per_pixel` number of heights and widths that are later
    # used to create anchor box corner coordinates (xmin, xmax, ymin, ymax)
    w = torch.cat((size_tensor * torch.sqrt(ratio_tensor[0]),
                   sizes[0] * torch.sqrt(ratio_tensor[1:])))\
                   * in_height / in_width  # Handle rectangular inputs
    h = torch.cat((size_tensor / torch.sqrt(ratio_tensor[0]),
                   sizes[0] / torch.sqrt(ratio_tensor[1:])))
    # Divide by 2 to get half height and half width
    anchor_manipulations = torch.stack((-w, -h, w, h)).T.repeat(
                                        in_height * in_width, 1) / 2

    # Each center point will have `boxes_per_pixel` number of anchor boxes, so
    # generate a grid of all anchor box centers with `boxes_per_pixel` repeats
    out_grid = torch.stack([shift_x, shift_y, shift_x, shift_y],
                dim=1).repeat_interleave(boxes_per_pixel, dim=0)
    output = out_grid + anchor_manipulations
    return output.unsqueeze(0)
#@save
def multibox_prior(data, sizes, ratios):
    """Generate anchor boxes with different shapes centered on each pixel."""
    in_height, in_width = data.shape[-2:]
    device, num_sizes, num_ratios = data.ctx, len(sizes), len(ratios)
    boxes_per_pixel = (num_sizes + num_ratios - 1)
    size_tensor = np.array(sizes, ctx=device)
    ratio_tensor = np.array(ratios, ctx=device)
    # Offsets are required to move the anchor to the center of a pixel. Since
    # a pixel has height=1 and width=1, we choose to offset our centers by 0.5
    offset_h, offset_w = 0.5, 0.5
    steps_h = 1.0 / in_height  # Scaled steps in y-axis
    steps_w = 1.0 / in_width  # Scaled steps in x-axis

    # Generate all center points for the anchor boxes
    center_h = (np.arange(in_height, ctx=device) + offset_h) * steps_h
    center_w = (np.arange(in_width, ctx=device) + offset_w) * steps_w
    shift_x, shift_y = np.meshgrid(center_w, center_h)
    shift_x, shift_y = shift_x.reshape(-1), shift_y.reshape(-1)

    # Generate `boxes_per_pixel` number of heights and widths that are later
    # used to create anchor box corner coordinates (xmin, xmax, ymin, ymax)
    w = np.concatenate((size_tensor * np.sqrt(ratio_tensor[0]),
                        sizes[0] * np.sqrt(ratio_tensor[1:]))) \
                        * in_height / in_width  # Handle rectangular inputs
    h = np.concatenate((size_tensor / np.sqrt(ratio_tensor[0]),
                        sizes[0] / np.sqrt(ratio_tensor[1:])))
    # Divide by 2 to get half height and half width
    anchor_manipulations = np.tile(np.stack((-w, -h, w, h)).T,
                                   (in_height * in_width, 1)) / 2

    # Each center point will have `boxes_per_pixel` number of anchor boxes, so
    # generate a grid of all anchor box centers with `boxes_per_pixel` repeats
    out_grid = np.stack([shift_x, shift_y, shift_x, shift_y],
                         axis=1).repeat(boxes_per_pixel, axis=0)
    output = out_grid + anchor_manipulations
    return np.expand_dims(output, axis=0)

我们可以看到返回的锚框变量 Y 的形状是(批量大小,锚框数量,4)。

img = d2l.plt.imread('../img/catdog.jpg')
h, w = img.shape[:2]

print(h, w)
X = torch.rand(size=(1, 3, h, w))  # Construct input data
Y = multibox_prior(X, sizes=[0.75, 0.5, 0.25], ratios=[1, 2, 0.5])
Y.shape
561 728
torch.Size([1, 2042040, 4])
img = image.imread('../img/catdog.jpg').asnumpy()
h, w = img.shape[:2]

print(h, w)
X = np.random.uniform(size=(1, 3, h, w))  # Construct input data
Y = multibox_prior(X, sizes=[0.75, 0.5, 0.25], ratios=[1, 2, 0.5])
Y.shape
561 728
[22:09:19] ../src/storage/storage.cc:196: Using Pooled (Naive) StorageManager for CPU
(1, 2042040, 4)

将锚框变量 Y 的形状更改为(图像高度,图像宽度,以同一像素为中心的锚框数,4)后,我们就可以获得以指定像素位置为中心的所有锚框。在下文中,我们访问以(250, 250)为中心的第一个锚框。它有四个元素:锚框左上角的 \((x, y)\) 轴坐标和右下角的 \((x, y)\) 轴坐标。两个轴的坐标值分别除以图像的宽度和高度。

boxes = Y.reshape(h, w, 5, 4)
boxes[250, 250, 0, :]
tensor([0.06, 0.07, 0.63, 0.82])
boxes = Y.reshape(h, w, 5, 4)
boxes[250, 250, 0, :]
array([0.06, 0.07, 0.63, 0.82])

为了显示图像中以一个像素为中心的所有锚框,我们定义了下面的 show_bboxes 函数来在图像上绘制多个边界框。

#@save
def show_bboxes(axes, bboxes, labels=None, colors=None):
    """Show bounding boxes."""

    def make_list(obj, default_values=None):
        if obj is None:
            obj = default_values
        elif not isinstance(obj, (list, tuple)):
            obj = [obj]
        return obj

    labels = make_list(labels)
    colors = make_list(colors, ['b', 'g', 'r', 'm', 'c'])
    for i, bbox in enumerate(bboxes):
        color = colors[i % len(colors)]
        rect = d2l.bbox_to_rect(bbox.detach().numpy(), color)
        axes.add_patch(rect)
        if labels and len(labels) > i:
            text_color = 'k' if color == 'w' else 'w'
            axes.text(rect.xy[0], rect.xy[1], labels[i],
                      va='center', ha='center', fontsize=9, color=text_color,
                      bbox=dict(facecolor=color, lw=0))
#@save
def show_bboxes(axes, bboxes, labels=None, colors=None):
    """Show bounding boxes."""

    def make_list(obj, default_values=None):
        if obj is None:
            obj = default_values
        elif not isinstance(obj, (list, tuple)):
            obj = [obj]
        return obj

    labels = make_list(labels)
    colors = make_list(colors, ['b', 'g', 'r', 'm', 'c'])
    for i, bbox in enumerate(bboxes):
        color = colors[i % len(colors)]
        rect = d2l.bbox_to_rect(bbox.asnumpy(), color)
        axes.add_patch(rect)
        if labels and len(labels) > i:
            text_color = 'k' if color == 'w' else 'w'
            axes.text(rect.xy[0], rect.xy[1], labels[i],
                      va='center', ha='center', fontsize=9, color=text_color,
                      bbox=dict(facecolor=color, lw=0))

正如我们刚才看到的,变量 boxes\(x\)\(y\) 轴的坐标值已分别除以图像的宽度和高度。绘制锚框时,我们需要恢复它们的原始坐标值;因此,我们下面定义了变量 bbox_scale。现在,我们可以在图像中绘制所有以 (250, 250) 为中心的锚框。如您所见,缩放比为0.75、宽高比为1的蓝色锚框很好地包围了图像中的狗。

d2l.set_figsize()
bbox_scale = torch.tensor((w, h, w, h))
fig = d2l.plt.imshow(img)
show_bboxes(fig.axes, boxes[250, 250, :, :] * bbox_scale,
            ['s=0.75, r=1', 's=0.5, r=1', 's=0.25, r=1', 's=0.75, r=2',
             's=0.75, r=0.5'])
../_images/output_anchor_f592d1_48_0.svg
d2l.set_figsize()
bbox_scale = np.array((w, h, w, h))
fig = d2l.plt.imshow(img)
show_bboxes(fig.axes, boxes[250, 250, :, :] * bbox_scale,
            ['s=0.75, r=1', 's=0.5, r=1', 's=0.25, r=1', 's=0.75, r=2',
             's=0.75, r=0.5'])
../_images/output_anchor_f592d1_51_0.svg

14.4.2. 交并比(IoU)

我们刚才提到,一个锚框“很好地”包围了图像中的狗。如果已知目标的真实边界框,这里的“很好”该如何量化?直观地说,我们可以测量锚框与真实边界框之间的相似性。我们知道,*Jaccard指数*可以测量两组集合的相似性。给定集合 \(\mathcal{A}\)\(\mathcal{B}\),它们的 Jaccard 指数是它们交集的大小除以它们并集的大小:

(14.4.2)\[J(\mathcal{A},\mathcal{B}) = \frac{\left|\mathcal{A} \cap \mathcal{B}\right|}{\left| \mathcal{A} \cup \mathcal{B}\right|}.\]

实际上,我们可以将任何边界框的像素区域视为一个像素集。这样,我们就可以通过它们像素集的 Jaccard 指数来测量两个边界框的相似性。对于两个边界框,我们通常将其 Jaccard 指数称为 *交并比*(Intersection over Union,*IoU*),即它们的交集面积与并集面积之比,如 图 14.4.1 所示。IoU 的取值范围在 0 和 1 之间:0 表示两个边界框根本不重叠,而 1 表示两个边界框相等。

../_images/iou.svg

图 14.4.1 IoU是两个边界框的交集面积与并集面积之比。

对于本节的其余部分,我们将使用 IoU 来衡量锚框与真实边界框之间以及不同锚框之间的相似性。给定两个锚框或边界框的列表,下面的 box_iou 计算这两个列表中成对的 IoU。

#@save
def box_iou(boxes1, boxes2):
    """Compute pairwise IoU across two lists of anchor or bounding boxes."""
    box_area = lambda boxes: ((boxes[:, 2] - boxes[:, 0]) *
                              (boxes[:, 3] - boxes[:, 1]))
    # Shape of `boxes1`, `boxes2`, `areas1`, `areas2`: (no. of boxes1, 4),
    # (no. of boxes2, 4), (no. of boxes1,), (no. of boxes2,)
    areas1 = box_area(boxes1)
    areas2 = box_area(boxes2)
    # Shape of `inter_upperlefts`, `inter_lowerrights`, `inters`: (no. of
    # boxes1, no. of boxes2, 2)
    inter_upperlefts = torch.max(boxes1[:, None, :2], boxes2[:, :2])
    inter_lowerrights = torch.min(boxes1[:, None, 2:], boxes2[:, 2:])
    inters = (inter_lowerrights - inter_upperlefts).clamp(min=0)
    # Shape of `inter_areas` and `union_areas`: (no. of boxes1, no. of boxes2)
    inter_areas = inters[:, :, 0] * inters[:, :, 1]
    union_areas = areas1[:, None] + areas2 - inter_areas
    return inter_areas / union_areas
#@save
def box_iou(boxes1, boxes2):
    """Compute pairwise IoU across two lists of anchor or bounding boxes."""
    box_area = lambda boxes: ((boxes[:, 2] - boxes[:, 0]) *
                              (boxes[:, 3] - boxes[:, 1]))
    # Shape of `boxes1`, `boxes2`, `areas1`, `areas2`: (no. of boxes1, 4),
    # (no. of boxes2, 4), (no. of boxes1,), (no. of boxes2,)
    areas1 = box_area(boxes1)
    areas2 = box_area(boxes2)
    # Shape of `inter_upperlefts`, `inter_lowerrights`, `inters`: (no. of
    # boxes1, no. of boxes2, 2)
    inter_upperlefts = np.maximum(boxes1[:, None, :2], boxes2[:, :2])
    inter_lowerrights = np.minimum(boxes1[:, None, 2:], boxes2[:, 2:])
    inters = (inter_lowerrights - inter_upperlefts).clip(min=0)
    # Shape of `inter_areas` and `union_areas`: (no. of boxes1, no. of boxes2)
    inter_areas = inters[:, :, 0] * inters[:, :, 1]
    union_areas = areas1[:, None] + areas2 - inter_areas
    return inter_areas / union_areas

14.4.3. 在训练数据中为锚框打标签

在训练数据集中,我们将每个锚框视为一个训练样本。为了训练目标检测模型,我们需要为每个锚框提供 *类别* 和 *偏移量* 标签,其中前者是与锚框相关的对象的类别,后者是真实边界框相对于锚框的偏移量。在预测过程中,我们为每个图像生成多个锚框,预测所有锚框的类别和偏移量,根据预测的偏移量调整它们的位置以获得预测的边界框,最后只输出那些满足特定条件的预测边界框。

我们知道,一个目标检测训练集带有 *真实边界框* 的位置标签和它们所包围对象的类别。为了标记任何生成的 *锚框*,我们参考其 *分配* 的、与该锚框最接近的真实边界框的标记位置和类别。下面,我们描述一种将最接近的真实边界框分配给锚框的算法。

14.4.3.1. 将真实边界框分配给锚框

给定一张图像,假设锚框是 \(A_1, A_2, \ldots, A_{n_a}\),真实边界框是 \(B_1, B_2, \ldots, B_{n_b}\),其中 \(n_a \geq n_b\)。让我们定义一个矩阵 \(\mathbf{X} \in \mathbb{R}^{n_a \times n_b}\),其中第 \(i^\textrm{th}\) 行第 \(j^\textrm{th}\) 列的元素 \(x_{ij}\) 是锚框 \(A_i\) 和真实边界框 \(B_j\) 的 IoU。该算法包括以下步骤:

  1. 在矩阵 \(\mathbf{X}\) 中找到最大的元素,并将其行和列索引分别记为 \(i_1\)\(j_1\)。然后将真实边界框 \(B_{j_1}\) 分配给锚框 \(A_{i_1}\)。这很直观,因为 \(A_{i_1}\)\(B_{j_1}\) 是所有锚框和真实边界框对中最接近的。在第一次分配后,丢弃矩阵 \(\mathbf{X}\) 中第 \({i_1}^\textrm{th}\) 行和第 \({j_1}^\textrm{th}\) 列的所有元素。

  2. 在矩阵 \(\mathbf{X}\) 中找到剩余元素中的最大值,并将其行和列索引分别记为 \(i_2\)\(j_2\)。我们将真实边界框 \(B_{j_2}\) 分配给锚框 \(A_{i_2}\),并丢弃矩阵 \(\mathbf{X}\) 中第 \({i_2}^\textrm{th}\) 行和第 \({j_2}^\textrm{th}\) 列的所有元素。

  3. 此时,矩阵 \(\mathbf{X}\) 中两行和两列的元素已被丢弃。我们继续进行,直到矩阵 \(\mathbf{X}\)\(n_b\) 列的所有元素都被丢弃。此时,我们已经为 \(n_b\) 个锚框各自分配了一个真实边界框。

  4. 只遍历剩余的 \(n_a - n_b\) 个锚框。例如,给定任何锚框 \(A_i\),在矩阵 \(\mathbf{X}\) 的第 \(i^\textrm{th}\) 行中找到与 \(A_i\) 具有最大IoU的真实边界框 \(B_j\),并且仅当此IoU大于预定义的阈值时,才将 \(B_j\) 分配给 \(A_i\)

让我们用一个具体的例子来说明上述算法。如 图 14.4.2(左)所示,假设矩阵 \(\mathbf{X}\) 中的最大值为 \(x_{23}\),我们将真实边界框 \(B_3\) 分配给锚框 \(A_2\)。然后,我们丢弃矩阵中第2行和第3列的所有元素,在剩余元素(阴影区域)中找到最大的 \(x_{71}\),并将真实边界框 \(B_1\) 分配给锚框 \(A_7\)。接下来,如 图 14.4.2(中)所示,丢弃矩阵中第7行和第1列的所有元素,在剩余元素(阴影区域)中找到最大的 \(x_{54}\),并将真实边界框 \(B_4\) 分配给锚框 \(A_5\)。最后,如 图 14.4.2(右)所示,丢弃矩阵中第5行和第4列的所有元素,在剩余元素(阴影区域)中找到最大的 \(x_{92}\),并将真实边界框 \(B_2\) 分配给锚框 \(A_9\)。之后,我们只需要遍历剩余的锚框 \(A_1, A_3, A_4, A_6, A_8\),并根据阈值确定是否为它们分配真实边界框。

../_images/anchor-label.svg

图 14.4.2 将真实边界框分配给锚框。

该算法在下面的 assign_anchor_to_bbox 函数中实现。

#@save
def assign_anchor_to_bbox(ground_truth, anchors, device, iou_threshold=0.5):
    """Assign closest ground-truth bounding boxes to anchor boxes."""
    num_anchors, num_gt_boxes = anchors.shape[0], ground_truth.shape[0]
    # Element x_ij in the i-th row and j-th column is the IoU of the anchor
    # box i and the ground-truth bounding box j
    jaccard = box_iou(anchors, ground_truth)
    # Initialize the tensor to hold the assigned ground-truth bounding box for
    # each anchor
    anchors_bbox_map = torch.full((num_anchors,), -1, dtype=torch.long,
                                  device=device)
    # Assign ground-truth bounding boxes according to the threshold
    max_ious, indices = torch.max(jaccard, dim=1)
    anc_i = torch.nonzero(max_ious >= iou_threshold).reshape(-1)
    box_j = indices[max_ious >= iou_threshold]
    anchors_bbox_map[anc_i] = box_j
    col_discard = torch.full((num_anchors,), -1)
    row_discard = torch.full((num_gt_boxes,), -1)
    for _ in range(num_gt_boxes):
        max_idx = torch.argmax(jaccard)  # Find the largest IoU
        box_idx = (max_idx % num_gt_boxes).long()
        anc_idx = (max_idx / num_gt_boxes).long()
        anchors_bbox_map[anc_idx] = box_idx
        jaccard[:, box_idx] = col_discard
        jaccard[anc_idx, :] = row_discard
    return anchors_bbox_map
#@save
def assign_anchor_to_bbox(ground_truth, anchors, device, iou_threshold=0.5):
    """Assign closest ground-truth bounding boxes to anchor boxes."""
    num_anchors, num_gt_boxes = anchors.shape[0], ground_truth.shape[0]
    # Element x_ij in the i-th row and j-th column is the IoU of the anchor
    # box i and the ground-truth bounding box j
    jaccard = box_iou(anchors, ground_truth)
    # Initialize the tensor to hold the assigned ground-truth bounding box for
    # each anchor
    anchors_bbox_map = np.full((num_anchors,), -1, dtype=np.int32, ctx=device)
    # Assign ground-truth bounding boxes according to the threshold
    max_ious, indices = np.max(jaccard, axis=1), np.argmax(jaccard, axis=1)
    anc_i = np.nonzero(max_ious >= iou_threshold)[0]
    box_j = indices[max_ious >= iou_threshold]
    anchors_bbox_map[anc_i] = box_j
    col_discard = np.full((num_anchors,), -1)
    row_discard = np.full((num_gt_boxes,), -1)
    for _ in range(num_gt_boxes):
        max_idx = np.argmax(jaccard)  # Find the largest IoU
        box_idx = (max_idx % num_gt_boxes).astype('int32')
        anc_idx = (max_idx / num_gt_boxes).astype('int32')
        anchors_bbox_map[anc_idx] = box_idx
        jaccard[:, box_idx] = col_discard
        jaccard[anc_idx, :] = row_discard
    return anchors_bbox_map

14.4.3.2. 标记类别和偏移量

现在我们可以为每个锚框标记类别和偏移量。假设一个锚框 \(A\) 被分配了一个真实边界框 \(B\)。一方面,锚框 \(A\) 的类别将被标记为 \(B\) 的类别。另一方面,锚框 \(A\) 的偏移量将根据 \(B\)\(A\) 的中心坐标之间的相对位置以及这两个框之间的相对大小来标记。鉴于数据集中不同框的位置和大小各不相同,我们可以对这些相对位置和大小应用变换,这可能会导致偏移量分布更均匀,更容易拟合。这里我们描述一种常见的变换。给定 \(A\)\(B\) 的中心坐标分别为 \((x_a, y_a)\)\((x_b, y_b)\),它们的宽度分别为 \(w_a\)\(w_b\),它们的高度分别为 \(h_a\)\(h_b\)。我们可以将 \(A\) 的偏移量标记为:

(14.4.3)\[\left( \frac{ \frac{x_b - x_a}{w_a} - \mu_x }{\sigma_x}, \frac{ \frac{y_b - y_a}{h_a} - \mu_y }{\sigma_y}, \frac{ \log \frac{w_b}{w_a} - \mu_w }{\sigma_w}, \frac{ \log \frac{h_b}{h_a} - \mu_h }{\sigma_h}\right),\]

其中常量的默认值为 \(\mu_x = \mu_y = \mu_w = \mu_h = 0, \sigma_x=\sigma_y=0.1\), and \(\sigma_w=\sigma_h=0.2\)。这个转换在下面的 offset_boxes 函数中实现。

#@save
def offset_boxes(anchors, assigned_bb, eps=1e-6):
    """Transform for anchor box offsets."""
    c_anc = d2l.box_corner_to_center(anchors)
    c_assigned_bb = d2l.box_corner_to_center(assigned_bb)
    offset_xy = 10 * (c_assigned_bb[:, :2] - c_anc[:, :2]) / c_anc[:, 2:]
    offset_wh = 5 * torch.log(eps + c_assigned_bb[:, 2:] / c_anc[:, 2:])
    offset = torch.cat([offset_xy, offset_wh], axis=1)
    return offset
#@save
def offset_boxes(anchors, assigned_bb, eps=1e-6):
    """Transform for anchor box offsets."""
    c_anc = d2l.box_corner_to_center(anchors)
    c_assigned_bb = d2l.box_corner_to_center(assigned_bb)
    offset_xy = 10 * (c_assigned_bb[:, :2] - c_anc[:, :2]) / c_anc[:, 2:]
    offset_wh = 5 * np.log(eps + c_assigned_bb[:, 2:] / c_anc[:, 2:])
    offset = np.concatenate([offset_xy, offset_wh], axis=1)
    return offset

如果一个锚框没有被分配真实边界框,我们只需将该锚框的类别标记为“背景”。类别为背景的锚框通常被称为 *负类* 锚框,其余的被称为 *正类* 锚框。我们实现了下面的 multibox_target 函数,使用真实边界框(labels 参数)为锚框(anchors 参数)标记类别和偏移量。此函数将背景类别设置为零,并将新类别的整数索引加一。

#@save
def multibox_target(anchors, labels):
    """Label anchor boxes using ground-truth bounding boxes."""
    batch_size, anchors = labels.shape[0], anchors.squeeze(0)
    batch_offset, batch_mask, batch_class_labels = [], [], []
    device, num_anchors = anchors.device, anchors.shape[0]
    for i in range(batch_size):
        label = labels[i, :, :]
        anchors_bbox_map = assign_anchor_to_bbox(
            label[:, 1:], anchors, device)
        bbox_mask = ((anchors_bbox_map >= 0).float().unsqueeze(-1)).repeat(
            1, 4)
        # Initialize class labels and assigned bounding box coordinates with
        # zeros
        class_labels = torch.zeros(num_anchors, dtype=torch.long,
                                   device=device)
        assigned_bb = torch.zeros((num_anchors, 4), dtype=torch.float32,
                                  device=device)
        # Label classes of anchor boxes using their assigned ground-truth
        # bounding boxes. If an anchor box is not assigned any, we label its
        # class as background (the value remains zero)
        indices_true = torch.nonzero(anchors_bbox_map >= 0)
        bb_idx = anchors_bbox_map[indices_true]
        class_labels[indices_true] = label[bb_idx, 0].long() + 1
        assigned_bb[indices_true] = label[bb_idx, 1:]
        # Offset transformation
        offset = offset_boxes(anchors, assigned_bb) * bbox_mask
        batch_offset.append(offset.reshape(-1))
        batch_mask.append(bbox_mask.reshape(-1))
        batch_class_labels.append(class_labels)
    bbox_offset = torch.stack(batch_offset)
    bbox_mask = torch.stack(batch_mask)
    class_labels = torch.stack(batch_class_labels)
    return (bbox_offset, bbox_mask, class_labels)
#@save
def multibox_target(anchors, labels):
    """Label anchor boxes using ground-truth bounding boxes."""
    batch_size, anchors = labels.shape[0], anchors.squeeze(0)
    batch_offset, batch_mask, batch_class_labels = [], [], []
    device, num_anchors = anchors.ctx, anchors.shape[0]
    for i in range(batch_size):
        label = labels[i, :, :]
        anchors_bbox_map = assign_anchor_to_bbox(
            label[:, 1:], anchors, device)
        bbox_mask = np.tile((np.expand_dims((anchors_bbox_map >= 0),
                                            axis=-1)), (1, 4)).astype('int32')
        # Initialize class labels and assigned bounding box coordinates with
        # zeros
        class_labels = np.zeros(num_anchors, dtype=np.int32, ctx=device)
        assigned_bb = np.zeros((num_anchors, 4), dtype=np.float32,
                                ctx=device)
        # Label classes of anchor boxes using their assigned ground-truth
        # bounding boxes. If an anchor box is not assigned any, we label its
        # class as background (the value remains zero)
        indices_true = np.nonzero(anchors_bbox_map >= 0)[0]
        bb_idx = anchors_bbox_map[indices_true]
        class_labels[indices_true] = label[bb_idx, 0].astype('int32') + 1
        assigned_bb[indices_true] = label[bb_idx, 1:]
        # Offset transformation
        offset = offset_boxes(anchors, assigned_bb) * bbox_mask
        batch_offset.append(offset.reshape(-1))
        batch_mask.append(bbox_mask.reshape(-1))
        batch_class_labels.append(class_labels)
    bbox_offset = np.stack(batch_offset)
    bbox_mask = np.stack(batch_mask)
    class_labels = np.stack(batch_class_labels)
    return (bbox_offset, bbox_mask, class_labels)

14.4.3.3. 一个例子

让我们通过一个具体的例子来说明锚框的标记。我们为加载图像中的狗和猫定义了真实边界框,其中第一个元素是类别(0为狗,1为猫),其余四个元素是左上角和右下角的 \((x, y)\) 轴坐标(范围在0和1之间)。我们还使用左上角和右下角的坐标构造了五个要标记的锚框:\(A_0, \ldots, A_4\)(索引从0开始)。然后我们在图像中绘制这些真实边界框和锚框。

ground_truth = torch.tensor([[0, 0.1, 0.08, 0.52, 0.92],
                         [1, 0.55, 0.2, 0.9, 0.88]])
anchors = torch.tensor([[0, 0.1, 0.2, 0.3], [0.15, 0.2, 0.4, 0.4],
                    [0.63, 0.05, 0.88, 0.98], [0.66, 0.45, 0.8, 0.8],
                    [0.57, 0.3, 0.92, 0.9]])

fig = d2l.plt.imshow(img)
show_bboxes(fig.axes, ground_truth[:, 1:] * bbox_scale, ['dog', 'cat'], 'k')
show_bboxes(fig.axes, anchors * bbox_scale, ['0', '1', '2', '3', '4']);
../_images/output_anchor_f592d1_93_0.svg
ground_truth = np.array([[0, 0.1, 0.08, 0.52, 0.92],
                         [1, 0.55, 0.2, 0.9, 0.88]])
anchors = np.array([[0, 0.1, 0.2, 0.3], [0.15, 0.2, 0.4, 0.4],
                    [0.63, 0.05, 0.88, 0.98], [0.66, 0.45, 0.8, 0.8],
                    [0.57, 0.3, 0.92, 0.9]])

fig = d2l.plt.imshow(img)
show_bboxes(fig.axes, ground_truth[:, 1:] * bbox_scale, ['dog', 'cat'], 'k')
show_bboxes(fig.axes, anchors * bbox_scale, ['0', '1', '2', '3', '4']);
../_images/output_anchor_f592d1_96_0.svg

使用上面定义的 multibox_target 函数,我们可以根据狗和猫的真实边界框为这些锚框标记类别和偏移量。在这个例子中,背景、狗和猫的类别索引分别是0、1和2。下面我们为锚框和真实边界框的样本添加一个维度。

labels = multibox_target(anchors.unsqueeze(dim=0),
                         ground_truth.unsqueeze(dim=0))
labels = multibox_target(np.expand_dims(anchors, axis=0),
                         np.expand_dims(ground_truth, axis=0))

返回结果中有三项,它们都是张量格式。第三项包含输入锚框的标记类别。

让我们根据图像中的锚框和真实边界框位置来分析下面返回的类别标签。首先,在所有锚框和真实边界框对中,锚框 \(A_4\) 与猫的真实边界框的IoU是最大的。因此,\(A_4\) 的类别被标记为猫。去掉包含 \(A_4\) 或猫的真实边界框的对后,在其余的对中,锚框 \(A_1\) 和狗的真实边界框的IoU最大。所以 \(A_1\) 的类别被标记为狗。接下来,我们需要遍历剩下的三个未标记的锚框:\(A_0\)\(A_2\)\(A_3\)。对于 \(A_0\),具有最大IoU的真实边界框的类别是狗,但IoU低于预定义阈值(0.5),所以类别被标记为背景;对于 \(A_2\),具有最大IoU的真实边界框的类别是猫,并且IoU超过了阈值,所以类别被标记为猫;对于 \(A_3\),具有最大IoU的真实边界框的类别是猫,但该值低于阈值,所以类别被标记为背景。

labels[2]
tensor([[0, 1, 2, 0, 2]])
labels[2]
array([[0, 1, 2, 0, 2]], dtype=int32)

返回的第二项是一个形状为(批量大小,锚框数乘以四)的掩码变量。掩码变量中的每四个元素对应于每个锚框的四个偏移值。由于我们不关心背景检测,负类别的偏移量不应影响目标函数。通过逐元素乘法,掩码变量中的零将在计算目标函数之前过滤掉负类别的偏移量。

labels[1]
tensor([[0., 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 1., 1.,
         1., 1.]])
labels[1]
array([[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]],
      dtype=int32)

返回的第一项包含了为每个锚框标记的四个偏移值。请注意,负类别锚框的偏移量被标记为零。

labels[0]
tensor([[-0.00e+00, -0.00e+00, -0.00e+00, -0.00e+00,  1.40e+00,  1.00e+01,
          2.59e+00,  7.18e+00, -1.20e+00,  2.69e-01,  1.68e+00, -1.57e+00,
         -0.00e+00, -0.00e+00, -0.00e+00, -0.00e+00, -5.71e-01, -1.00e+00,
          4.17e-06,  6.26e-01]])
labels[0]
array([[-0.00e+00, -0.00e+00, -0.00e+00, -0.00e+00,  1.40e+00,  1.00e+01,
         2.59e+00,  7.18e+00, -1.20e+00,  2.69e-01,  1.68e+00, -1.57e+00,
        -0.00e+00, -0.00e+00, -0.00e+00, -0.00e+00, -5.71e-01, -1.00e+00,
         4.17e-06,  6.26e-01]])

14.4.4. 使用非极大值抑制预测边界框

在预测过程中,我们为图像生成多个锚框,并为每个锚框预测类别和偏移量。因此,根据一个锚框及其预测的偏移量,可以得到一个*预测边界框*。下面我们实现了 offset_inverse 函数,该函数以锚框和偏移量预测作为输入,并应用逆偏移变换以返回预测的边界框坐标。

#@save
def offset_inverse(anchors, offset_preds):
    """Predict bounding boxes based on anchor boxes with predicted offsets."""
    anc = d2l.box_corner_to_center(anchors)
    pred_bbox_xy = (offset_preds[:, :2] * anc[:, 2:] / 10) + anc[:, :2]
    pred_bbox_wh = torch.exp(offset_preds[:, 2:] / 5) * anc[:, 2:]
    pred_bbox = torch.cat((pred_bbox_xy, pred_bbox_wh), axis=1)
    predicted_bbox = d2l.box_center_to_corner(pred_bbox)
    return predicted_bbox
#@save
def offset_inverse(anchors, offset_preds):
    """Predict bounding boxes based on anchor boxes with predicted offsets."""
    anc = d2l.box_corner_to_center(anchors)
    pred_bbox_xy = (offset_preds[:, :2] * anc[:, 2:] / 10) + anc[:, :2]
    pred_bbox_wh = np.exp(offset_preds[:, 2:] / 5) * anc[:, 2:]
    pred_bbox = np.concatenate((pred_bbox_xy, pred_bbox_wh), axis=1)
    predicted_bbox = d2l.box_center_to_corner(pred_bbox)
    return predicted_bbox

当有很多锚框时,可能会输出许多相似的(有显著重叠)预测边界框来包围同一个物体。为了简化输出,我们可以使用*非极大值抑制*(non-maximum suppression,NMS)来合并属于同一物体的相似预测边界框。

非极大值抑制的工作原理如下。对于一个预测边界框 \(B\),目标检测模型会计算每个类别的预测似然度。设 \(p\) 为最大的预测似然度,与该概率对应的类别是 \(B\) 的预测类别。具体来说,我们将 \(p\) 称为预测边界框 \(B\) 的*置信度*(或分数)。在同一张图像上,所有预测的非背景边界框按置信度降序排序,生成一个列表 \(L\)。然后我们通过以下步骤操作排序后的列表 \(L\)

  1. \(L\) 中选择置信度最高的预测边界框 \(B_1\) 作为基准,并从 \(L\) 中移除所有与 \(B_1\) 的IoU超过预定义阈值 \(\epsilon\) 的非基准预测边界框。此时,\(L\) 保留了置信度最高的预测边界框,但丢弃了其他与其过于相似的框。简而言之,那些具有*非极大*置信度分数的框被*抑制*了。

  2. \(L\) 中选择置信度第二高的预测边界框 \(B_2\) 作为另一个基准,并从 \(L\) 中移除所有与 \(B_2\) 的IoU超过 \(\epsilon\) 的非基准预测边界框。

  3. 重复上述过程,直到 \(L\) 中所有的预测边界框都已作为基准使用。此时,\(L\) 中任意一对预测边界框的IoU都低于阈值 \(\epsilon\);因此,没有一对是彼此过于相似的。

  4. 输出列表 \(L\) 中的所有预测边界框。

下面的 nms 函数按降序对置信度分数进行排序并返回它们的索引。

#@save
def nms(boxes, scores, iou_threshold):
    """Sort confidence scores of predicted bounding boxes."""
    B = torch.argsort(scores, dim=-1, descending=True)
    keep = []  # Indices of predicted bounding boxes that will be kept
    while B.numel() > 0:
        i = B[0]
        keep.append(i)
        if B.numel() == 1: break
        iou = box_iou(boxes[i, :].reshape(-1, 4),
                      boxes[B[1:], :].reshape(-1, 4)).reshape(-1)
        inds = torch.nonzero(iou <= iou_threshold).reshape(-1)
        B = B[inds + 1]
    return torch.tensor(keep, device=boxes.device)
#@save
def nms(boxes, scores, iou_threshold):
    """Sort confidence scores of predicted bounding boxes."""
    B = scores.argsort()[::-1]
    keep = []  # Indices of predicted bounding boxes that will be kept
    while B.size > 0:
        i = B[0]
        keep.append(i)
        if B.size == 1: break
        iou = box_iou(boxes[i, :].reshape(-1, 4),
                      boxes[B[1:], :].reshape(-1, 4)).reshape(-1)
        inds = np.nonzero(iou <= iou_threshold)[0]
        B = B[inds + 1]
    return np.array(keep, dtype=np.int32, ctx=boxes.ctx)

我们定义了下面的 multibox_detection 函数来对预测边界框应用非极大值抑制。如果您发现实现有点复杂,请不要担心:我们将在实现之后通过一个具体的例子展示它的工作原理。

#@save
def multibox_detection(cls_probs, offset_preds, anchors, nms_threshold=0.5,
                       pos_threshold=0.009999999):
    """Predict bounding boxes using non-maximum suppression."""
    device, batch_size = cls_probs.device, cls_probs.shape[0]
    anchors = anchors.squeeze(0)
    num_classes, num_anchors = cls_probs.shape[1], cls_probs.shape[2]
    out = []
    for i in range(batch_size):
        cls_prob, offset_pred = cls_probs[i], offset_preds[i].reshape(-1, 4)
        conf, class_id = torch.max(cls_prob[1:], 0)
        predicted_bb = offset_inverse(anchors, offset_pred)
        keep = nms(predicted_bb, conf, nms_threshold)
        # Find all non-`keep` indices and set the class to background
        all_idx = torch.arange(num_anchors, dtype=torch.long, device=device)
        combined = torch.cat((keep, all_idx))
        uniques, counts = combined.unique(return_counts=True)
        non_keep = uniques[counts == 1]
        all_id_sorted = torch.cat((keep, non_keep))
        class_id[non_keep] = -1
        class_id = class_id[all_id_sorted]
        conf, predicted_bb = conf[all_id_sorted], predicted_bb[all_id_sorted]
        # Here `pos_threshold` is a threshold for positive (non-background)
        # predictions
        below_min_idx = (conf < pos_threshold)
        class_id[below_min_idx] = -1
        conf[below_min_idx] = 1 - conf[below_min_idx]
        pred_info = torch.cat((class_id.unsqueeze(1),
                               conf.unsqueeze(1),
                               predicted_bb), dim=1)
        out.append(pred_info)
    return torch.stack(out)
#@save
def multibox_detection(cls_probs, offset_preds, anchors, nms_threshold=0.5,
                       pos_threshold=0.009999999):
    """Predict bounding boxes using non-maximum suppression."""
    device, batch_size = cls_probs.ctx, cls_probs.shape[0]
    anchors = np.squeeze(anchors, axis=0)
    num_classes, num_anchors = cls_probs.shape[1], cls_probs.shape[2]
    out = []
    for i in range(batch_size):
        cls_prob, offset_pred = cls_probs[i], offset_preds[i].reshape(-1, 4)
        conf, class_id = np.max(cls_prob[1:], 0), np.argmax(cls_prob[1:], 0)
        predicted_bb = offset_inverse(anchors, offset_pred)
        keep = nms(predicted_bb, conf, nms_threshold)
        # Find all non-`keep` indices and set the class to background
        all_idx = np.arange(num_anchors, dtype=np.int32, ctx=device)
        combined = np.concatenate((keep, all_idx))
        unique, counts = np.unique(combined, return_counts=True)
        non_keep = unique[counts == 1]
        all_id_sorted = np.concatenate((keep, non_keep))
        class_id[non_keep] = -1
        class_id = class_id[all_id_sorted].astype('float32')
        conf, predicted_bb = conf[all_id_sorted], predicted_bb[all_id_sorted]
        # Here `pos_threshold` is a threshold for positive (non-background)
        # predictions
        below_min_idx = (conf < pos_threshold)
        class_id[below_min_idx] = -1
        conf[below_min_idx] = 1 - conf[below_min_idx]
        pred_info = np.concatenate((np.expand_dims(class_id, axis=1),
                                np.expand_dims(conf, axis=1),
                                predicted_bb), axis=1)
        out.append(pred_info)
    return np.stack(out)

现在让我们将上述实现应用于一个包含四个锚框的具体例子。为简单起见,我们假设预测的偏移量都为零。这意味着预测的边界框就是锚框。对于背景、狗和猫中的每个类别,我们还定义了其预测的似然度。

anchors = torch.tensor([[0.1, 0.08, 0.52, 0.92], [0.08, 0.2, 0.56, 0.95],
                      [0.15, 0.3, 0.62, 0.91], [0.55, 0.2, 0.9, 0.88]])
offset_preds = torch.tensor([0] * anchors.numel())
cls_probs = torch.tensor([[0] * 4,  # Predicted background likelihood
                      [0.9, 0.8, 0.7, 0.1],  # Predicted dog likelihood
                      [0.1, 0.2, 0.3, 0.9]])  # Predicted cat likelihood
anchors = np.array([[0.1, 0.08, 0.52, 0.92], [0.08, 0.2, 0.56, 0.95],
                      [0.15, 0.3, 0.62, 0.91], [0.55, 0.2, 0.9, 0.88]])
offset_preds = np.array([0] * d2l.size(anchors))
cls_probs = np.array([[0] * 4,  # Predicted background likelihood
                      [0.9, 0.8, 0.7, 0.1],  # Predicted dog likelihood
                      [0.1, 0.2, 0.3, 0.9]])  # Predicted cat likelihood

我们可以在图像上绘制这些带有置信度的预测边界框。

fig = d2l.plt.imshow(img)
show_bboxes(fig.axes, anchors * bbox_scale,
            ['dog=0.9', 'dog=0.8', 'dog=0.7', 'cat=0.9'])
../_images/output_anchor_f592d1_174_0.svg
fig = d2l.plt.imshow(img)
show_bboxes(fig.axes, anchors * bbox_scale,
            ['dog=0.9', 'dog=0.8', 'dog=0.7', 'cat=0.9'])
../_images/output_anchor_f592d1_177_0.svg

现在我们可以调用 multibox_detection 函数来执行非极大值抑制,其中阈值设置为0.5。请注意,我们在张量输入中为样本添加了一个维度。

我们可以看到返回结果的形状是(批量大小,锚框数,6)。最内层维度的六个元素给出了同一个预测边界框的输出信息。第一个元素是预测的类别索引,从0开始(0是狗,1是猫)。值-1表示背景或在非极大值抑制中被移除。第二个元素是预测边界框的置信度。其余四个元素分别是预测边界框左上角和右下角的 \((x, y)\) 轴坐标(范围在0和1之间)。

output = multibox_detection(cls_probs.unsqueeze(dim=0),
                            offset_preds.unsqueeze(dim=0),
                            anchors.unsqueeze(dim=0),
                            nms_threshold=0.5)
output
tensor([[[ 0.00,  0.90,  0.10,  0.08,  0.52,  0.92],
         [ 1.00,  0.90,  0.55,  0.20,  0.90,  0.88],
         [-1.00,  0.80,  0.08,  0.20,  0.56,  0.95],
         [-1.00,  0.70,  0.15,  0.30,  0.62,  0.91]]])
output = multibox_detection(np.expand_dims(cls_probs, axis=0),
                            np.expand_dims(offset_preds, axis=0),
                            np.expand_dims(anchors, axis=0),
                            nms_threshold=0.5)
output
array([[[ 1.  ,  0.9 ,  0.55,  0.2 ,  0.9 ,  0.88],
        [ 0.  ,  0.9 ,  0.1 ,  0.08,  0.52,  0.92],
        [-1.  ,  0.8 ,  0.08,  0.2 ,  0.56,  0.95],
        [-1.  ,  0.7 ,  0.15,  0.3 ,  0.62,  0.91]]])

在移除了类别为-1的预测边界框后,我们可以输出由非极大值抑制保留的最终预测边界框。

fig = d2l.plt.imshow(img)
for i in output[0].detach().numpy():
    if i[0] == -1:
        continue
    label = ('dog=', 'cat=')[int(i[0])] + str(i[1])
    show_bboxes(fig.axes, [torch.tensor(i[2:]) * bbox_scale], label)
../_images/output_anchor_f592d1_192_0.svg
fig = d2l.plt.imshow(img)
for i in output[0].asnumpy():
    if i[0] == -1:
        continue
    label = ('dog=', 'cat=')[int(i[0])] + str(i[1])
    show_bboxes(fig.axes, [np.array(i[2:]) * bbox_scale], label)
../_images/output_anchor_f592d1_195_0.svg

在实践中,我们甚至可以在执行非极大值抑制之前就移除置信度较低的预测边界框,从而减少该算法的计算量。我们还可以对非极大值抑制的输出进行后处理,例如,只在最终输出中保留置信度较高的结果。

14.4.5. 小结

  • 我们以图像的每个像素为中心生成不同形状的锚框。

  • 交并比(IoU),也称为Jaccard指数,衡量两个边界框的相似性。它是它们交集面积与并集面积之比。

  • 在训练集中,我们需要为每个锚框提供两种类型的标签。一种是与锚框相关的对象的类别,另一种是真实边界框相对于锚框的偏移量。

  • 在预测过程中,我们可以使用非极大值抑制(NMS)来移除相似的预测边界框,从而简化输出。

14.4.6. 练习

  1. multibox_prior 函数中更改 sizesratios 的值。生成的锚框会有什么变化?

  2. 构造并可视化两个IoU为0.5的边界框。它们是如何相互重叠的?

  3. 修改 14.4.3节14.4.4节 中的变量 anchors。结果会如何变化?

  4. 非极大值抑制是一种通过*移除*来抑制预测边界框的贪心算法。有没有可能一些被移除的框实际上是有用的?如何修改这个算法以进行*软*抑制?你可以参考Soft-NMS (Bodla et al., 2017)

  5. 非极大值抑制可以被学习,而不是手工设计吗?