3.6.锚框

锚框

13.4. 锚框 — 动手学深度学习 2.0.0 documentation (d2l.ai)

​ 一类目标检测算法是基于锚框的,步骤如下:

​ 使用多个被称为锚框的区域(边缘框),预测每个锚框里是否含有关注的物体,如果有,则预测从这个锚框到真实物体边缘框的偏移(s是缩放比,r是宽高比)

在这里插入图片描述

1. 交并比(IoU)

​ 为了对偏移进行预测,我们需要定量地去描述某个锚框和真实边界框的符合程度,直观地说,可以衡量锚框和真实边框之间的相似性的一个参数。

杰卡德系数可以衡量两组之间的相似性,给定集合 A , B A,B A,B,他们的杰卡德系数是:
J ( A , B ) = ∣ A ∩ B ∣ ∣ A ∪ B ∣ J(A,B) = \frac{|A\cap B|}{|A\cup B|} J(A,B)=ABAB
​ 因为任何边界框,都可以被视为一组像素,例如左上右下坐标为((1,2),(2,1)),那么显然含有像素点[(1,1),(1,2),(2,1),(2,2)],通过这个方式,就可以衡量两个边界框的相似性。对于两个边界框,它们的杰卡德系数通常被称为交并比,即两个边界框相交面积与相并面积之比。显然0表示完全不重合,1表示完全重合。

在这里插入图片描述

2.基于锚框的算法

2.1 分配真实边界框

​ 其中一种算法是:首先提出很多个锚框,每个锚框都是一个训练样本,均赋予一个锚框标号。每个锚框,要么标注成背景,要么关联一个真实边缘框。

​ 可能会生成大量的锚框,导致有大量的负类样本(背景),具体如下:

​ 假定锚框是 A 1 , A 2 , ⋯   , A n A_1,A_2,\cdots,A_n A1,A2,,An,真实边界框是 B 1 , B 2 , ⋯   , B n b B_1,B_2,\cdots,B_{n_b} B1,B2,,Bnb,其中 n a ≥ n b n_a\ge n_b nanb。定义矩阵 X ∈ R n a × n b X\in \R ^{n_a\times n_b} XRna×nb,其中 x i j x_{ij} xij表示锚框 A i A_i Ai和真实边框 B j B_j Bj的IoU

​ 实现步骤如下:

  1. X X X中找到最大的元素(即重叠最多的),假设为 x i 1 j 1 x_{i_1j_1} xi1j1,那么将真实边界框 B j 1 B_{j_1} Bj1分配给锚框 A i 1 A_{i_1} Ai1,并丢弃 i 1 i_1 i1 j 1 j_1 j1列的所有元素(因为已经找到了最匹配的)
  2. 在剩余元素中找最大的元素,重复步骤1,直到真实边界框被分配完(也就是说丢完了)
  3. 只遍历剩下的 n a − n b n_a-n_b nanb个锚框,例如,给定任何锚框 A i A_i Ai,在矩阵 X X X的第 i i i行找到与 A i A_i Ai的IoU最大的真实边界框 B j B_j Bj,只有当这个IoU大于预定义的阈值时,才将 B j B_j Bj分配给 A i A_i Ai (当然也可以直接当成背景,但这样会导致负类太多)

在这里插入图片描述

​ 如图,在分配完后,我们还需要遍历剩余的锚框 A 1 , A 3 , A 4 , A 6 , A 8 A_1,A_3,A_4,A_6,A_8 A1,A3,A4,A6,A8即可。

2.2 使用非极大值抑制(NMS)预测

​ 每个锚框都会预测一个边缘框,那其实很多框都是相似的,我们可以使用NMS来合并相似的预测,基本思路是先选中非背景类的最大预测值,然后去掉所有和这个预测边框IoU大于 θ \theta θ的预测。

​ 实现步骤如下:

​ 对于一个预测边界框 B B B,目标检测模型会计算每个类别的预测概率,假设最大的预测概率为 p p p,则该概率所对应的类别 B B B即为预测的类别,将这个概率称为预测边界框 B B B置信度。在同一张图像中,所有预测的非背景边界框都被按置信度降序排列,以生成列表 L L L

​ 接着选取置信度最高的边界框 B 1 B_1 B1作为基准,将所有与 B 1 B_1 B1的IoU超过预定阈值 θ \theta θ的非基准预测边界框移除,这一操作去除了太过相似的其他预测边界框,简而言之,那些具有非极大值置信度的边界框被抑制了

​ 然后选取第二高的,一直做,直到 L L L中所有的预测边界框都曾被用作基准,这时任意一对预测边界框的IoU都小于阈值 θ \theta θ,避免了边界框的相似。

3.代码实现

3.1 生成锚框

假设输入图像高度为 h h h,宽度为 w w w,以图像的每个像素为中心生成不同形状的锚框:缩放比为 s ∈ ( 0 , 1 ] s\in(0,1] s(0,1],宽高比为 r > 0 r>0 r>0,那么锚框的宽度和高度分别是 w s r ws\sqrt{r} wsr h s r \cfrac{hs}{\sqrt{r}} r hs

​ 由于缩放比取值和宽高比取值有很多,假设分别为 s 1 , ⋯   , s n s_1,\cdots,s_n s1,,sn r 1 , ⋯   , r m r_1,\cdots,r_m r1,,rm,显然组合起来太多了,因此我们只考虑包含 s 1 s_1 s1 r 1 r_1 r1的组合:
( s 1 , r 1 ) , ( s 1 , r 2 ) , ⋯   , ( s 1 , r m ) , ( s 2 , r 1 ) , ( s 3 , r 1 ) , ⋯   , ( s m , r 1 ) (s_1,r_1),(s_1,r_2),\cdots,(s_1,r_m),(s_2,r_1),(s_3,r_1),\cdots,(s_m,r_1) (s1,r1),(s1,r2),,(s1,rm),(s2,r1),(s3,r1),,(sm,r1)
​ 也就是说,对于一个像素点,锚框数量为 n + m − 1 n+m-1 n+m1,对于整个输入图像,将生成 w h ( n + m − 1 ) wh(n+m-1) wh(n+m1)个锚框

import torch
from d2l import torch as d2l

torch.set_printoptions(2)  # 精简输出精度


# @save
def multibox_prior(data, sizes, ratios):
    """生成以每个像素为中心具有不同形状的锚框"""
    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)

    # 为了将锚点移动到像素的中心,需要设置偏移量。
    # 因为一个像素的高为1且宽为1,我们选择偏移我们的中心0.5
    offset_h, offset_w = 0.5, 0.5
    steps_h = 1.0 / in_height  # 在y轴上缩放步长
    steps_w = 1.0 / in_width  # 在x轴上缩放步长

    # 生成锚框的所有中心点,是两个列表
    center_h = (torch.arange(in_height, device=device) + offset_h) * steps_h
    center_w = (torch.arange(in_width, device=device) + offset_w) * steps_w

    # meshgrid生成坐标,比如[1,2] 和[3,4],就会生成[(1,3),(1,4),(2,3),(2,4)],取出来的x和y就是([1,1],[2,2])和([3,3],[4,4])
    # 就是取横纵坐标的
    shift_y, shift_x = torch.meshgrid(center_h, center_w, indexing='ij')
    # reshape(-1)表示自动转换成一维向量,并计算长度
    shift_y, shift_x = shift_y.reshape(-1), shift_x.reshape(-1)

    # 生成“boxes_per_pixel”个高和宽,
    # 之后用于创建锚框的四角坐标(xmin,xmax,ymin,ymax)
    # 这里拼接有两个部分,第一部分是宽高比是r1的组合,第二部分是缩放比是s1的组合
    w = torch.cat((size_tensor * torch.sqrt(ratio_tensor[0]),
                   sizes[0] * torch.sqrt(ratio_tensor[1:]))) \
        * in_height / in_width  # 处理矩形输入,最后再调整宽度以匹配图像的宽高比
    h = torch.cat((size_tensor / torch.sqrt(ratio_tensor[0]),
                   sizes[0] / torch.sqrt(ratio_tensor[1:])))
    # 除以2来获得半高和半宽
    # 转置之后变为(boxes_per_pixel,4),再重复像素点次数次,使得每个像素点都有boxes_per_pixel哥锚框
    # repeat是重复每一行若干次,即最后的形状是 ((in_height * in_width *boxes_per_pixel),4) 的形状
    anchor_manipulations = torch.stack((-w, -h, w, h)).T.repeat(
        in_height * in_width, 1) / 2

    # 每个中心点都将有“boxes_per_pixel”个锚框,
    # 所以生成含所有锚框中心的网格,重复了“boxes_per_pixel”次
    # stack(dim=1)表示在第一个维度进行堆叠,形成的形状是(in_height*in_weight,4)
    # 随后的repeat在第0个维度上repeat,形成的形状是 ((in_height * in_width *boxes_per_pixel),4)
    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)  # 添加一个维度,使输出张量的形状为(1,num_anchors,4),方便后续处理


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

print(h, w)
X = torch.rand(size=(1, 3, h, w))
Y = multibox_prior(X, sizes=[0.75, 0.5, 0.25], ratios=[1, 2, 0.5])
print(Y.shape)
# 将锚框变量Y的形状更改为(图像高度,图像宽度,以同一像素为中心的锚框的数量,4) 锚框数量为3+3-1=5,4代表表示边界框的4个数字
boxes = Y.reshape(h, w, 5, 4) # 有400多万个锚框
print(boxes[1080, 1920, 0, :])

#@save
def show_bboxes(axes, bboxes, labels=None, colors=None):
    """显示所有边界框"""
    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))


d2l.set_figsize()
bbox_scale = torch.tensor((w, h, w, h))
fig = d2l.plt.imshow(img)
show_bboxes(fig.axes, boxes[1080, 1920, :, :] * 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'])

d2l.plt.show()

在这里插入图片描述

3.2 交并比(IoU)

​ 注意新增的注释中对形状的解释

#@save
def box_iou(boxes1, boxes2):
    """计算两个锚框或边界框列表中成对的交并比"""
    box_area = lambda boxes: ((boxes[:, 2] - boxes[:, 0]) *
                              (boxes[:, 3] - boxes[:, 1]))
    # boxes1,boxes2,areas1,areas2的形状:
    # boxes1:(boxes1的数量,4),
    # boxes2:(boxes2的数量,4),
    # areas1:(boxes1的数量,),
    # areas2:(boxes2的数量,)
    areas1 = box_area(boxes1)
    areas2 = box_area(boxes2)
    # inter_upperlefts,inter_lowerrights,inters的形状:
    # (boxes1的数量,boxes2的数量,2) 、
    # 找左上右下
    # None的含义是将(N1,2)的形状扩充为(N1,1,2),即左上右下坐标有单独的维度
    # 第三个维度[0]是宽的意思,[1]是高的意思
    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) #clamp限制元素的大小,即最小不能为负,可能没有交集
    # inter_areasandunion_areas的形状:(boxes1的数量,boxes2的数量)
    inter_areas = inters[:, :, 0] * inters[:, :, 1]# 这时候inters的形状是(数量,1,宽和高)
    #这样一取出来相乘,inter_areas的形状就变为(数量,1)
    union_areas = areas1[:, None] + areas2 - inter_areas
    return inter_areas / union_areas

3.3 分配真实边界框

​ 注意注释:

def assign_anchor_to_bbox(ground_truth, anchors, device, iou_threshold=0.5):
    """将最接近的真实边界框分配给锚框"""
    num_anchors, num_gt_boxes = anchors.shape[0], ground_truth.shape[0]
    # 位于第i行和第j列的元素x_ij是锚框i和真实边界框j的IoU
    jaccard = box_iou(anchors, ground_truth)
    # 对于每个锚框,分配的真实边界框的张量
    anchors_bbox_map = torch.full((num_anchors,), -1, dtype=torch.long,
                                  device=device)  # 初始值为-1表示未分配
    # 根据阈值,决定是否分配真实边界框
    # max_ious,indices形状都是(num_anchors,),前者是最大iou值,后者是对应的索引
    max_ious, indices = torch.max(jaccard, dim=1)  # 即找到每一行(锚框)对应的真实边框(列),按行找最大值,列上比较,dim=1
    anc_i = torch.nonzero(max_ious >= iou_threshold).reshape(-1)  # 包含的是满足括号条件的索引
    box_j = indices[max_ious >= iou_threshold]  # 返回所有 max_ious 大于或等于阈值的对应索引。
    # anc_i 是满足条件的锚框索引,box_j 是对应的真实边界框索引。
    anchors_bbox_map[anc_i] = box_j
    col_discard = torch.full((num_anchors,), -1)
    row_discard = torch.full((num_gt_boxes,), -1)
    # 至此构建好了索引,使用这些索引来更新map
    for _ in range(num_gt_boxes):
        max_idx = torch.argmax(jaccard)  #max_idx返回的是第几个元素,比如jaccard是3*5 的,第jaccard[1][2]最大,返回13
        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

3.4 标记类别和偏移量

​ 现在假设每个锚框A都被分配了一个真实边界框B,一方面锚框A的类别将被标记为B的类别,另一方面,锚框A的偏移量将根据B和A的中心坐标位置以及这两个框的相对大小进行标记,鉴于数据集内不同的框的位置和大小不同,我们可以对那些相对位置和大小应用变换,使其获得分布更均匀且易于拟合的偏移量。

​ 一种常见的变换是:给定边界框A和B,中心坐标分别为 ( x a , y a ) , ( x b , y b ) (x_a,y_a),(x_b,y_b) (xa,ya),(xb,yb),宽度分别为 w a , w b w_a,w_b wa,wb,高度分别为 h a , h b h_a,h_b ha,hb,那么可以将A的偏移量标记为:
( x b − x a w a − μ x σ x , y b − y a h a − μ y σ y , l o g w b w a − μ w σ w , l o g h b h a − μ h σ h ) (\cfrac{\cfrac{x_b-x_a}{w_a}-\mu_x}{\sigma_x},\cfrac{\cfrac{y_b-y_a}{h_a}-\mu_y}{\sigma_y},\cfrac{{log\frac{w_b}{w_a}}-\mu_w}{\sigma_w},\cfrac{{log\frac{h_b}{h_a}}-\mu_h}{\sigma_h}) (σxwaxbxaμxσyhaybyaμy,σwlogwawbμw,σhloghahbμh)
​ 其中常量的默认值为 μ x = μ y = μ w = μ h = 0 , σ x = σ y = 0.1 , σ w = σ h = 0.2 \mu_x=\mu_y=\mu_w=\mu_h =0,\sigma_x =\sigma _y =0.1,\sigma_w =\sigma_h =0.2 μx=μy=μw=μh=0,σx=σy=0.1,σw=σh=0.2

​ 使用offset_boxes函数实现:

def offset_boxes(anchors, assigned_bb, eps=1e-6):
    """对锚框偏移量的转换"""
    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:]) #eps避免为0
    offset = torch.cat([offset_xy, offset_wh], axis=1)
    return offset

​ 如果一个锚框没有被分配真实边界框,将锚框的类别标记为背景,称为负类锚框,其余被称为正类锚框。使用真实边界框(labels参数)实现multibox_target函数,来标记锚框的类别和偏移量,此函数将背景类别的索引设置为0,然后新类别的索引递增1.

def multibox_target(anchors, labels):
    """使用真实边界框标记锚框"""
    # labels 是形状为 (batch_size, num_labels, 5) 的张量,
    # 描述每个样本的真实边界框及其类别(后四个值是边界框坐标,第1个值是类别标签)。
    #anchors.squeeze(0) 将 anchors 的形状从 (1, num_anchors, 4) 变为 (num_anchors, 4)。
    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指示哪些锚框被分配了真实边界框
        # unsqueeze(-1)在最后添加一个维度,将形状(num_anchors,)变为(num_anchors,1)
        # repeat(1,4)在最后一个维度重复4次,变为(num_anchors,4),每个锚框的4个坐标都将共享一个掩码值
        bbox_mask = ((anchors_bbox_map >= 0).float().unsqueeze(-1)).repeat(
            1, 4)
        # 将类标签和分配的边界框坐标初始化为零
        class_labels = torch.zeros(num_anchors, dtype=torch.long,
                                   device=device)
        #assigned_bb 是一个形状为 (num_anchors, 4) 的张量,用于存储每个锚框分配到的真实边界框坐标。
        assigned_bb = torch.zeros((num_anchors, 4), dtype=torch.float32,
                                  device=device)
        # 使用真实边界框来标记锚框的类别。
        # 如果一个锚框没有被分配,标记其为背景(值为零)
        # indices_true 储存分配了真实边界框的锚框索引
        indices_true = torch.nonzero(anchors_bbox_map >= 0)
        # 这些锚框分配到的真实边界索引bb_idx
        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 = offset_boxes(anchors, assigned_bb) * bbox_mask #掩码值为1才需要计算偏移
        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)

3.5 NMS

​ 在知道预测偏移量后,一般使用逆偏移变换来返回预测的边界框坐标(就是把 x b x_b xb的坐标解出来)

#@save
def offset_inverse(anchors, offset_preds):
    """根据带有预测偏移量的锚框来预测边界框"""
    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

  # nms函数按降序对置信度先进性排序
#@save
def nms(boxes, scores, iou_threshold):
    """对预测边界框的置信度进行排序"""
    B = torch.argsort(scores, dim=-1, descending=True)
    keep = []  # 保留预测边界框的指标
    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)

def multibox_detection(cls_probs, offset_preds, anchors, nms_threshold=0.5,
                     pos_threshold=0.009999999):
  """使用非极大值抑制来预测边界框"""
  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)

      # 找到所有的non_keep索引,并将类设置为背景
      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]
      # pos_threshold是一个用于非背景预测的阈值
      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)


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值