找回密码
 立即注册
首页 业界区 安全 锚框 anchor box

锚框 anchor box

姬宜欣 昨天 14:33
博客地址:https://www.cnblogs.com/zylyehuo/
参考 《动手学深度学习》第二版
代码总览
  1. # 锚框
复制代码
  1. %matplotlib inline
  2. import torch
  3. from d2l import torch as d2l
复制代码
  1. torch.set_printoptions(2)  # 精简输出精度
复制代码
1.png
  1. def multibox_prior(data, sizes, ratios):
  2.     """生成以每个像素为中心具有不同形状的锚框"""
  3.     in_height, in_width = data.shape[-2:]
  4.     device, num_sizes, num_ratios = data.device, len(sizes), len(ratios)
  5.     boxes_per_pixel = (num_sizes + num_ratios - 1)
  6.     size_tensor = torch.tensor(sizes, device=device)
  7.     ratio_tensor = torch.tensor(ratios, device=device)
  8.     # 为了将锚点移动到像素的中心,需要设置偏移量。
  9.     # 因为一个像素的高为1且宽为1,我们选择偏移我们的中心0.5
  10.     offset_h, offset_w = 0.5, 0.5
  11.     steps_h = 1.0 / in_height  # 在y轴上缩放步长
  12.     steps_w = 1.0 / in_width  # 在x轴上缩放步长
  13.     # 生成锚框的所有中心点
  14.     center_h = (torch.arange(in_height, device=device) + offset_h) * steps_h
  15.     center_w = (torch.arange(in_width, device=device) + offset_w) * steps_w
  16.     shift_y, shift_x = torch.meshgrid(center_h, center_w, indexing='ij')
  17.     shift_y, shift_x = shift_y.reshape(-1), shift_x.reshape(-1)
  18.     # 生成“boxes_per_pixel”个高和宽,
  19.     # 之后用于创建锚框的四角坐标(xmin,xmax,ymin,ymax)
  20.     w = torch.cat((size_tensor * torch.sqrt(ratio_tensor[0]),
  21.                    sizes[0] * torch.sqrt(ratio_tensor[1:])))\
  22.                    * in_height / in_width  # 处理矩形输入
  23.     h = torch.cat((size_tensor / torch.sqrt(ratio_tensor[0]),
  24.                    sizes[0] / torch.sqrt(ratio_tensor[1:])))
  25.     # 除以2来获得半高和半宽
  26.     anchor_manipulations = torch.stack((-w, -h, w, h)).T.repeat(
  27.                                         in_height * in_width, 1) / 2
  28.     # 每个中心点都将有“boxes_per_pixel”个锚框,
  29.     # 所以生成含所有锚框中心的网格,重复了“boxes_per_pixel”次
  30.     out_grid = torch.stack([shift_x, shift_y, shift_x, shift_y],
  31.                 dim=1).repeat_interleave(boxes_per_pixel, dim=0)
  32.     output = out_grid + anchor_manipulations
  33.     return output.unsqueeze(0)
复制代码
  1. # 返回的锚框变量Y的形状是(批量大小,锚框的数量,4)
复制代码
  1. img = d2l.plt.imread('./assets/catdog.jpg')
  2. h, w = img.shape[:2]
  3. print(h, w)
复制代码
2.png
  1. X = torch.rand(size=(1, 3, h, w))
  2. Y = multibox_prior(X, sizes=[0.75, 0.5, 0.25], ratios=[1, 2, 0.5])
  3. Y.shape
复制代码
3.png
  1. # 访问以(250,250)为中心的第一个锚框
复制代码
  1. boxes = Y.reshape(h, w, 5, 4)
  2. boxes[250, 250, 0, :]
复制代码
4.png
  1. # 显示以图像中以某个像素为中心的所有锚框
复制代码
  1. def show_bboxes(axes, bboxes, labels=None, colors=None):
  2.     """显示所有边界框"""
  3.     def _make_list(obj, default_values=None):
  4.         if obj is None:
  5.             obj = default_values
  6.         elif not isinstance(obj, (list, tuple)):
  7.             obj = [obj]
  8.         return obj
  9.     labels = _make_list(labels)
  10.     colors = _make_list(colors, ['b', 'g', 'r', 'm', 'c'])
  11.     for i, bbox in enumerate(bboxes):
  12.         color = colors[i % len(colors)]
  13.         rect = d2l.bbox_to_rect(bbox.detach().numpy(), color)
  14.         axes.add_patch(rect)
  15.         if labels and len(labels) > i:
  16.             text_color = 'k' if color == 'w' else 'w'
  17.             axes.text(rect.xy[0], rect.xy[1], labels[i],
  18.                       va='center', ha='center', fontsize=9, color=text_color,
  19.                       bbox=dict(facecolor=color, lw=0))
复制代码
  1. # 以(250,250)为中心的锚框
复制代码
  1. d2l.set_figsize()
  2. bbox_scale = torch.tensor((w, h, w, h))
  3. fig = d2l.plt.imshow(img)
  4. show_bboxes(fig.axes, boxes[250, 250, :, :] * bbox_scale,
  5.             ['s=0.75, r=1', 's=0.5, r=1', 's=0.25, r=1', 's=0.75, r=2',
  6.              's=0.75, r=0.5'])
复制代码
5.png

  1. # 交并比(IoU)
复制代码
  1. def box_iou(boxes1, boxes2):
  2.     """计算两个锚框或边界框列表中成对的交并比"""
  3.     box_area = lambda boxes: ((boxes[:, 2] - boxes[:, 0]) *
  4.                               (boxes[:, 3] - boxes[:, 1]))
  5.     # boxes1,boxes2,areas1,areas2的形状:
  6.     # boxes1:(boxes1的数量,4),
  7.     # boxes2:(boxes2的数量,4),
  8.     # areas1:(boxes1的数量,),
  9.     # areas2:(boxes2的数量,)
  10.     areas1 = box_area(boxes1)
  11.     areas2 = box_area(boxes2)
  12.     # inter_upperlefts,inter_lowerrights,inters的形状:
  13.     # (boxes1的数量,boxes2的数量,2)
  14.     inter_upperlefts = torch.max(boxes1[:, None, :2], boxes2[:, :2])
  15.     inter_lowerrights = torch.min(boxes1[:, None, 2:], boxes2[:, 2:])
  16.     inters = (inter_lowerrights - inter_upperlefts).clamp(min=0)
  17.     # inter_areasandunion_areas的形状:(boxes1的数量,boxes2的数量)
  18.     inter_areas = inters[:, :, 0] * inters[:, :, 1]
  19.     union_areas = areas1[:, None] + areas2 - inter_areas
  20.     return inter_areas / union_areas
复制代码
  1. # 将真实边界框分配给锚框
复制代码
  1. def assign_anchor_to_bbox(ground_truth, anchors, device, iou_threshold=0.5):
  2.     """将最接近的真实边界框分配给锚框"""
  3.     num_anchors, num_gt_boxes = anchors.shape[0], ground_truth.shape[0]
  4.     # 位于第i行和第j列的元素x_ij是锚框i和真实边界框j的IoU
  5.     jaccard = box_iou(anchors, ground_truth)
  6.     # 对于每个锚框,分配的真实边界框的张量
  7.     anchors_bbox_map = torch.full((num_anchors,), -1, dtype=torch.long,
  8.                                   device=device)
  9.     # 根据阈值,决定是否分配真实边界框
  10.     max_ious, indices = torch.max(jaccard, dim=1)
  11.     anc_i = torch.nonzero(max_ious >= iou_threshold).reshape(-1)
  12.     box_j = indices[max_ious >= iou_threshold]
  13.     anchors_bbox_map[anc_i] = box_j
  14.     col_discard = torch.full((num_anchors,), -1)
  15.     row_discard = torch.full((num_gt_boxes,), -1)
  16.     for _ in range(num_gt_boxes):
  17.         max_idx = torch.argmax(jaccard)
  18.         box_idx = (max_idx % num_gt_boxes).long()
  19.         anc_idx = (max_idx / num_gt_boxes).long()
  20.         anchors_bbox_map[anc_idx] = box_idx
  21.         jaccard[:, box_idx] = col_discard
  22.         jaccard[anc_idx, :] = row_discard
  23.     return anchors_bbox_map
复制代码
  1. # 标记类别和偏移量
复制代码
  1. def offset_boxes(anchors, assigned_bb, eps=1e-6):
  2.     """对锚框偏移量的转换"""
  3.     c_anc = d2l.box_corner_to_center(anchors)
  4.     c_assigned_bb = d2l.box_corner_to_center(assigned_bb)
  5.     offset_xy = 10 * (c_assigned_bb[:, :2] - c_anc[:, :2]) / c_anc[:, 2:]
  6.     offset_wh = 5 * torch.log(eps + c_assigned_bb[:, 2:] / c_anc[:, 2:])
  7.     offset = torch.cat([offset_xy, offset_wh], axis=1)
  8.     return offset
复制代码
  1. def multibox_target(anchors, labels):
  2.     """使用真实边界框标记锚框"""
  3.     batch_size, anchors = labels.shape[0], anchors.squeeze(0)
  4.     batch_offset, batch_mask, batch_class_labels = [], [], []
  5.     device, num_anchors = anchors.device, anchors.shape[0]
  6.     for i in range(batch_size):
  7.         label = labels[i, :, :]
  8.         anchors_bbox_map = assign_anchor_to_bbox(
  9.             label[:, 1:], anchors, device)
  10.         bbox_mask = ((anchors_bbox_map >= 0).float().unsqueeze(-1)).repeat(
  11.             1, 4)
  12.         # 将类标签和分配的边界框坐标初始化为零
  13.         class_labels = torch.zeros(num_anchors, dtype=torch.long,
  14.                                    device=device)
  15.         assigned_bb = torch.zeros((num_anchors, 4), dtype=torch.float32,
  16.                                   device=device)
  17.         # 使用真实边界框来标记锚框的类别。
  18.         # 如果一个锚框没有被分配,标记其为背景(值为零)
  19.         indices_true = torch.nonzero(anchors_bbox_map >= 0)
  20.         bb_idx = anchors_bbox_map[indices_true]
  21.         class_labels[indices_true] = label[bb_idx, 0].long() + 1
  22.         assigned_bb[indices_true] = label[bb_idx, 1:]
  23.         # 偏移量转换
  24.         offset = offset_boxes(anchors, assigned_bb) * bbox_mask
  25.         batch_offset.append(offset.reshape(-1))
  26.         batch_mask.append(bbox_mask.reshape(-1))
  27.         batch_class_labels.append(class_labels)
  28.     bbox_offset = torch.stack(batch_offset)
  29.     bbox_mask = torch.stack(batch_mask)
  30.     class_labels = torch.stack(batch_class_labels)
  31.     return (bbox_offset, bbox_mask, class_labels)
复制代码
  1. # 一个例子
复制代码
  1. ground_truth = torch.tensor([[0, 0.1, 0.08, 0.52, 0.92],
  2.                          [1, 0.55, 0.2, 0.9, 0.88]])
  3. anchors = torch.tensor([[0, 0.1, 0.2, 0.3], [0.15, 0.2, 0.4, 0.4],
  4.                     [0.63, 0.05, 0.88, 0.98], [0.66, 0.45, 0.8, 0.8],
  5.                     [0.57, 0.3, 0.92, 0.9]])
  6. fig = d2l.plt.imshow(img)
  7. show_bboxes(fig.axes, ground_truth[:, 1:] * bbox_scale, ['dog', 'cat'], 'k')
  8. show_bboxes(fig.axes, anchors * bbox_scale, ['0', '1', '2', '3', '4']);
复制代码
6.png

  1. # 根据狗和猫的真实边界框,标注这些锚框的分类和偏移量
复制代码
  1. labels = multibox_target(anchors.unsqueeze(dim=0),
  2.                          ground_truth.unsqueeze(dim=0))
复制代码
  1. labels[2]
复制代码
7.png
  1. labels[1]
复制代码
8.png
  1. labels[0]
复制代码
9.png
  1. # 应用逆偏移变换来返回预测的边界框坐标
复制代码
  1. def offset_inverse(anchors, offset_preds):
  2.     """根据带有预测偏移量的锚框来预测边界框"""
  3.     anc = d2l.box_corner_to_center(anchors)
  4.     pred_bbox_xy = (offset_preds[:, :2] * anc[:, 2:] / 10) + anc[:, :2]
  5.     pred_bbox_wh = torch.exp(offset_preds[:, 2:] / 5) * anc[:, 2:]
  6.     pred_bbox = torch.cat((pred_bbox_xy, pred_bbox_wh), axis=1)
  7.     predicted_bbox = d2l.box_center_to_corner(pred_bbox)
  8.     return predicted_bbox
复制代码
  1. # 以下nms函数按降序对置信度进行排序并返回其索引
复制代码
[code]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
您需要登录后才可以回帖 登录 | 立即注册