动手学深度学习之锚框

锚框

  • 锚框就是一个框,边缘框就是一个物体的真实的位置的一个框,锚框是对这个边缘框位置的一个猜测。算法先给我们画出一个框,然后看这个框里面有没有物体。如果有的话,算法就基于这个物体进行预测,它到我们真实的边缘框是怎么偏移过去的。简单来说就是,先提出多个框,然后看看框里面有没有这个物体,有的话,就基于这个框来调整位置。这样我们就有两个预测,一个是对框中是否存在该物体的预测,另一个是锚框到真实的边缘框的预测。
    在这里插入图片描述

loU-交并比

  • loU用来计算两个框之间的相似度。它是一个0-1之间的数值,0表示无重叠,1表示重合。也就是这两个框的交集和这两个框的并集的比值
    在这里插入图片描述

赋予锚框标号(几种常见的做法)(训练阶段使用)

  • 在训练的时候每一个锚框是一个样本,将每一个锚框标注成背景。 要么关联上一个真实的边缘框,也就是说,框住物体的标号,以及它到真实边框的偏移。

  • 一般来说会生成大量的锚框,这会导致大量的负类样本。
    在这里插入图片描述

  • 例子:下图有一个矩阵,它的列有四个标注好的边缘框,也就是说真实有四个物体,每个物体对应的有四个框。对于每一个物体我们生成了九个锚框,然后用每个锚框去算他的IoU值,填在里面。然后我们将整个矩阵中的最大值挑出来,然后将边缘框给这个锚框,然后将这个最大值对应的行和列删除。在剩余的值里面我们在找出一个最大值,再将这个锚框给对应的边缘框,删除对应的行和列。直到所有的锚框都删除完。

  • 赋予锚框标号,是每次读取图片进来都要做一次。
    在这里插入图片描述

使用非极大值抑制(NMS)输出(预测阶段使用)

  • 首先选中所有的框中的非背景类的最大预测值,这个值是对这个类的softmax的值,也就是说越接近1就越接近。然后去掉所有和他的IoU的值大于某个值的框,将被保留的值拿出来。重复上述过程,知道所有的预测要么被选中,要么被删除。最后我们会得到一个比较干净的输出。
    在这里插入图片描述

总结

在这里插入图片描述

锚框代码实现

%matplotlib inline
import torch
from d2l import torch as d2l

torch.set_printoptions(2)

锚框的宽度和高度分别是 w s r ws\sqrt{r} wsr h s / r hs/\sqrt{r} hs/r 。我们只考虑组合: ( s 1 , r 1 ) , ( s 1 , r 2 ) , . . . , ( s 1 , r m ) , ( s 2 , r 1 ) , ( s 3 , r 1 ) , . . . , ( s n , r 1 ) (s_1,r_1),(s_1,r_2),...,(s_1,r_m),(s_2,r_1),(s_3,r1),...,(s_n,r_1) (s1,r1),(s1,r2),...,(s1,rm),(s2,r1),(s3,r1),...,(sn,r1)

# 对于每一个像素为中心,生成高宽度不同的锚框
# 这里一个data对应图片,图片有一个高宽。对于每一个像素,以它为中心,生成不同个宽度和高度的上述宽度和高度的东西,w,h表示高宽,s表示锚框的大小,锚框占图片的多少。r是锚框的高宽比
# 这里会给一系列的s,r。这里不会都组合,这样生成的锚框太多。常见的做法是:首先全部用最合适的size,和所有的ratios组合,将ratio过滤一遍。然后再用所有的最合适的ratio,和所有的size组合,将size过滤一遍
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的个数加上ratios的个数-1
    size_tensor = torch.tensor(sizes, device=device)
    ratio_tensor = torch.tensor(ratios, device=device)

    offset_h, offset_w = 0.5, 0.5
    steps_h = 1.0 / in_height
    steps_w = 1.0 / in_width

    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)
    shift_y, shift_x = shift_y.reshape(-1), shift_x.reshape(-1)

    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:])))
    anchor_manipulations = torch.stack(
        (-w, -h, w, h)).T.repeat(in_height * in_width, 1) / 2

    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)

返回的锚框变量Y的形状

img = d2l.plt.imread("/Users/tiger/Desktop/study/机器学习/李沐深度学习/d2l-zh/pytorch/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])
Y.shape
561 728
torch.Size([1, 2042040, 4])

访问以(250,250)为中心的第一个锚框

boxes = Y.reshape(h, w, 5, 4)  # 这里4就是表示这个锚框的左上和右下的坐标
boxes[250, 250, 0, :]  # 这里返回的坐标已经除以高宽了,变为了0-1之间的数了。
tensor([0.06, 0.07, 0.63, 0.82])

显示以图像一个像素为中心的所有锚框

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[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'
])  # 将以250,250为中心的锚框都画出来

在这里插入图片描述

交并比(IoU)

def box_iou(boxes1, boxes2):
    """计算两个锚框或边界框列表中成对的交并比。"""
    box_area = lambda boxes: ((boxes[:, 2] - boxes[:, 0]) *
                              (boxes[:, 3] - boxes[:, 1]))
    areas1 = box_area(boxes1)
    areas2 = box_area(boxes2)
    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)
    inter_areas = inters[:, :, 0] * inters[:, :, 1]
    union_areas = areas1[:, None] + areas2 - inter_areas
    return inter_areas / union_areas

将真实边界框分配给锚框

# ground_truth真实的锚框,anchors给我们的锚框,device进行计算的设备,iou_threshold就是用来对比的,如果一个锚框与真实边框的值小于这个值,就不要了
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]
    jaccard = box_iou(anchors, ground_truth)  # 算出所有的锚框和真实边框的IoU
    anchors_bbox_map = torch.full((num_anchors,), -1, dtype=torch.long,
                                  device=device)
    max_ious, indices = torch.max(jaccard, dim=1)
    anc_i = torch.nonzero(max_ious >= 0.5).reshape(-1)
    box_j = indices[max_ious >= 0.5]
    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)
        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  # 最后得到一个map

给定框 𝐴 和 𝐵,中心坐标分别为 ( x a , y a ) (x_a,y_a) (xa,ya) ( x b , y b ) (x_b, y_b) (xb,yb),宽度分别为 w a w_a wa w b w_b wb,高度分别为 h a h_a ha h b h_b 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 ) \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 ) (σxwaxbxaμx,σyhaybyaμy,σwlogwawbμw,σhloghahbμh)

# 这里的原因就是尽量使得offset使得好预测,也就是说值尽量分的比较开
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:])
    offset = torch.cat([offset_xy, offset_wh], axis=1)
    return offset
#   
def multibox_target(anchors, labels):
    """使用真实边界框标记锚框。"""
    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)
        class_labels = torch.zeros(num_anchors, dtype=torch.long,
                                   device=device)
        assigned_bb = torch.zeros((num_anchors, 4), dtype=torch.float32,
                                  device=device)
        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 = 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)  # 返回一个anchors到标注框的offset,mask=0就不用预测,=1表示对应真实框,锚框对应类编号

在图像中绘制这些地面真相边界框和锚框

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']);

在这里插入图片描述

根据狗和猫的真实边界框,标注这些锚框的分类和偏移量

labels = multibox_target(anchors.unsqueeze(dim=0),
                         ground_truth.unsqueeze(dim=0))  # 这里unsqueeze就是需要我们加上一个维度,就是批量大小

labels[2]
tensor([[0, 1, 2, 0, 2]])
labels[1]  # mask:标记背景类,还是有物体的类
tensor([[0., 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 1., 1.,
         1., 1.]])
labels[0]  # 每个锚框的offset
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]])

应用逆偏移变换来返回预测的边界框坐标

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 函数按降序对置信度进行排序并返回其索引

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)

将非极大值抑制应用于预测边界框

# 意思就是对里面的每一个值拿出来,用一次nms,做一次预测
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)

        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]
        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)
# 将上述算法应用到一个带有四个锚框的具体示例中
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,
                          [0.9, 0.8, 0.7, 0.1],
                          [0.1, 0.2, 0.3, 0.9]])

在图像上绘制这些预测边界框和置信度

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

在这里插入图片描述

返回结果的形状是(批量大小,锚框的数量,6)

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]]])

输出由非极大值抑制保存的最终预测边界框

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)

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值