锚框
%matplotlib inline
import torch
from d2l import torch as d2l
torch.set_printoptions(2)#精简输出精度
生成多个锚框
缩放比s,宽高比r。
中心位置给定,已知宽和高的锚框使确定的。
同一像素为中心的锚框数量:n+m-1。一张图一共生成wh(n+m-1)个锚框
multibox_prior:生成以每个像素为中心具有不同形状的锚框
def multibox_prior(data,sizes,ratios):
#data形状:[batch_size,channels,height,width]
#sizes:包含锚框基础尺寸的列表
#ratios:包含锚框高宽比的列表
in_height,in_width=data.shape[-2:]
device,num_sizes,num_ratios=data.device,len(sizes),len(ratios)
boxes_per_pixel=(num_size+num_ratios-1)
size_tensor=torch.tensor(sizes,device=device)
ratio_tensor=torch.tensor(ratios,device=device)
#为了将锚点移动到像素的中心,需要设置偏移量
#一个像素h,w均为1,所以偏移中心0.5
offset_h,offset_w=0.5,0.5
#x,y轴上缩放步长
steps_h=1.0/in_height
step_w=1.0/in_weight
#生成锚框的所有中心点
center_h=(torch.arange(in_height,device=device)+offset_h)*steps_h
center_w=(torch.arange(in_width,device=device)+offset_w)*step_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)
#生成“box_per_pixel”个高和宽
#之后用于创建锚框的四角坐标(xmin,xmax,ymin,ymax)
w=torch.cat((size_tensor*torch.sqrt(ratio_tensor[0]),
sizes[0]*torch.sqrt(ratio_tensor[1:])))\
*in_height/in_weight
h=torch.cat((size_tensor/torch.sqrt(ratio_tensor[0]),
sizes[0]//torch.sqrt(ratio_tensor[1:]))
#除以2获得半高,半宽
anchor_manipulations=torch.stack((-w,-h,w,h)).T.repeat(in_height*in_weight,1)/2
#每个中心点都将有“boxes_per_pixel”个锚框
#所以生成含所有锚框中心的网格,重复了“boxes_per_pixel”次
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
#在第0维插入新维度
return output.unsqueeze(0)
w,h代码的解释
w = torch.cat((size_tensor * torch.sqrt(ratio_tensor[0]),
size_tensor[0] * torch.sqrt(ratio_tensor[1:]))) * in_height / in_width
h = torch.cat((size_tensor / torch.sqrt(ratio_tensor[0]),
size_tensor[0] / torch.sqrt(ratio_tensor[1:])))
1.宽度(w)的计算
-
size_tensor * torch.sqrt(ratio_tensor[0]):size_tensor包含了不同的锚框尺寸。ratio_tensor[0]是比例的第一个值,假设为1(正方形),这部分计算生成了与第一个比例相对应的锚框宽度。
-
size_tensor[0] * torch.sqrt(ratio_tensor[1:]):size_tensor[0]是第一个尺寸的基准值,用于生成与其他比例相关的锚框宽度。ratio_tensor[1:]是剩余的比例,计算基准尺寸和这些比例的宽度。
-
torch.cat(...):- 将以上两部分计算结果拼接,得到所有比例下的锚框宽度。
-
* in_height / in_width:- 锚框的宽度需要在输入特征图的宽度和高度上进行标准化。这个步骤将计算结果从像素尺度映射到网络输入特征图的尺度上。
2.高度(h)的计算
-
size_tensor / torch.sqrt(ratio_tensor[0]):size_tensor除以sqrt(ratio_tensor[0])计算得到与第一个比例相关的锚框高度。
-
size_tensor[0] / torch.sqrt(ratio_tensor[1:]):size_tensor[0]除以剩余比例的平方根,生成其他比例下的锚框高度。
-
torch.cat(...):- 将以上两部分计算结果拼接,得到所有比例下的锚框高度。
show_bboxes函数:显示图像中以某个像素为中心的所有锚框
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))
show_bboxes(axes, bboxes, labels=None, colors=None):
axes: 用于绘制边界框的matplotlib轴对象。bboxes: 边界框的列表,每个边界框可能是一个矩形坐标。labels(可选): 每个边界框的标签,用于显示在边界框中间。colors(可选): 边界框的颜色列表。如果没有提供颜色,函数会使用默认颜色。
内部函数 _make_list
_make_list(obj, default_values=None):
- 功能: 确保传入的
obj是一个列表。如果obj为None,则使用default_values。 - 实现:
- 如果
obj为None,将其设置为default_values。 - 如果
obj不是列表或元组,则将其转换为列表。 - 返回处理后的列表。
- 如果
主体代码
使用 _make_list 确保 labels 和 colors 都是列表。如果 colors 为 None,则使用默认颜色 ['b', 'g', 'r', 'm', 'c']。
-
遍历边界框
bboxes:for i, bbox in enumerate(bboxes): color = colors[i % len(colors)] rect = d2l.bbox_to_rect(bbox.detach().numpy(), color) axes.add_patch(rect)enumerate(bboxes): 遍历bboxes列表,同时获取每个边界框的索引i。color = colors[i % len(colors)]: 使用颜色列表中的颜色。如果colors列表长度小于bboxes的长度,颜色会循环使用。d2l.bbox_to_rect(bbox.detach().numpy(), color): 使用d2l库的bbox_to_rect函数将边界框转换为matplotlib可用的矩形。bbox.detach().numpy()将边界框从张量转换为 NumPy 数组。axes.add_patch(rect): 将矩形添加到axes上进行绘制。
-
添加标签(如果提供):
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))if labels and len(labels) > i: 如果labels存在且标签数量足够。text_color = 'k' if color == 'w' else 'w': 根据边界框的颜色选择文本颜色。白色背景时,文本为黑色,反之亦然。axes.text(...): 在矩形的中心位置添加标签。参数解释:rect.xy[0],rect.xy[1]: 矩形的左下角坐标,作为标签的位置。va='center',ha='center': 垂直和水平对齐方式均为居中。fontsize=9: 设置字体大小为 9。color=text_color: 设置文本颜色。bbox=dict(facecolor=color, lw=0): 设置文本背景为边界框的颜色,边框宽度为 0。
交并比(IoU)


接下来部分将使用交并比来衡量锚框和真实边界框之间、以及不同锚框之间的相似度。 给定两个锚框或边界框的列表,以下box_iou函数将在这两个列表中计算它们成对的交并比。
def box_iou(boxes1, boxes2):
"""计算两个锚框或边界框列表中成对的交并比"""
#w*h
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)
#左上坐标
#右下坐标
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_areasandunion_areas的形状:(boxes1的数量,boxes2的数量)
inter_areas = inters[:, :, 0] * inters[:, :, 1]
union_areas = areas1[:, None] + areas2 - inter_areas
return inter_areas / union_areas
def assign_anchor_to_bbox(ground_truth, anchors, device, iou_threshold=0.5):
"""将最接近的真实边界框分配给锚框"""
#num_anchors: 这是一个整数,表示锚框的总数量。每个锚框是预定义的边界框,用于在目标检测中与真实的目标进行匹配。通常,锚框在输入图像的特征图上以网格形式分布。
#num_gt_boxes: 这是一个整数,表示真实边界框的总数量。这些是手动标注在图像中的目标边界框,用于训练模型时作为真实标签进行比较和计算损失
#.shape[0],我们获取了 anchors 和 ground_truth 张量的第一个维度的大小,即锚框和真实边界框的数量。
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 用于记录每个锚框与真实边界框的分配情况。初始化时,所有的值都是 -1,表示这些锚框尚未分配给任何真实边界框。在后续的处理过程中,根据 IoU(交并比)和分配策略,这个张量会被更新为每个锚框实际分配到的真实边界框的索引。如果某个锚框没有合适的真实边界框匹配,它的值将保持为 -1。
anchors_bbox_map = torch.full((num_anchors,), -1, dtype=torch.long,device=device)
# 根据阈值,决定是否分配真实边界框
#max_ious 计算每个锚框与所有真实边界框的IoU最大值,indices存储对应的真实边界框的索引
max_ious, indices = torch.max(jaccard, dim=1)
#找到所有iou值≥iou_throeshold的锚框索引
anc_i = torch.nonzero(max_ious >= iou_threshold).reshape(-1)
#提取对应的目标框索引
box_j = indices[max_ious >= iou_threshold]
#将锚框的目标索引box_j映射到anchors_bbox_map中对应的锚框位置,anchor_bbox_map记录了每个锚框与目标框的最佳匹配
anchors_bbox_map[anc_i] = box_j
#处理为分配的真实边界框
#col_discard,row_cards是大小分别为num_anchors,num_gt_boxes的张量,全部填充为-1.这些张量用于在匹配过程中标记jaccard矩阵中列和行为“丢弃”
col_discard = torch.full((num_anchors,), -1)
row_discard = torch.full((num_gt_boxes,), -1)
#遍历每个真实框,迭代次数等于真实框的数量
for _ in range(num_gt_boxes):
#找到jaccard矩阵的最大值,这个索引是扁平化的(即它在二维矩阵中的一维视图的位置)
max_idx = torch.argmax(jaccard)
#box_idx通过对max——idx取模num_gt_boxes来计算行(真实索引框)
anc_idx通过对max_idx进行整数除法num_gt_boxes来计算列(锚框索引)
box_idx = (max_idx % num_gt_boxes).long()
anc_idx = (max_idx / num_gt_boxes).long()
#更新anchor_bbox_map,将当前的锚框(anc_idx)映射到真实框(box_idx),有效地记录了这个分配
anchors_bbox_map[anc_idx] = box_idx
#丢弃选定的行和列
jaccard[:, box_idx] = col_discard
jaccard[anc_idx, :] = row_discard
return anchors_bbox_map
标记类别和偏移量
锚框A,真实边框B,锚框A的类别被标记为与B相同。
锚框A的偏移量根据B和A的中心坐标的相对位置及这两个框的相对大小进行标记。
对相对位置和大小变化,获得分布更均匀且易于拟合的偏移量。
A的偏移量:
其中常量的默认值为 μ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_assignes_bb=d2l.box_corner_to_center(assigned_bb)
#计算坐标偏移量、
#c_assigned_bb[:,:2]是分配框的中心坐标,c_anc[:,:2]是锚框的中心坐标。他们的差异被除以锚框的宽高比×10,进行缩放
offset_xy=10*(c_assigned_bb[:,:2]-c_anc[:,:2]/c_anc[:,2:])
#计算坐标偏移量
#使用对数函数来平滑地处理宽高比例,eps是一个小常数,避免对数计算中的除0错误,计算结果进行缩放 offset_wh=5*torch.log(eps+c_assigned_bb[:,2:]/c_anc[:,2:])
#合并偏移量
offset=torch.cat([offset_xy,offset_wh],axis=1)
return offset
如果锚框没有被分配真实边界框,只需要将锚框类别标记为background。
背景类别锚框为负类锚框,其余为正类锚框。
使用真实边界框(labels参数)实现以下函数,来标记锚框的类别和偏移量(anchors参数)
为什么使用 squeeze(0)
在处理目标检测任务时,通常输入的锚框张量可能在第一维上包含一个批量维度,但批量大小为 1。例如,模型可能在单张图片上进行训练,这时候批量维度是 1。
为了简化后续操作和计算,有时需要去除这个冗余的维度。使用 squeeze(0) 就是为了去掉这个批量维度,使得张量的形状变为 (num_anchors, 4),即只包含锚框的信息,而不包含批量维度。
总的来说,anchors.squeeze(0) 是将形状为 (1, num_anchors, 4) 的张量变为 (num_anchors, 4) 的操作,这样可以使后续的计算和处理更为简洁和方便。
unsqueeze(dim) 操作
-
unsqueeze(dim)在张量的指定位置dim上添加一个新的维度,维度的大小为 1。 -
dim参数是一个整数,表示新维度的位置。如果dim为负数,它从张量的最后一个维度开始倒数。例如,dim = -1表示在最后一个维度的位置插入一个新维度。
def multibox_target(anchors,labels):
"""使用真实边界框标记锚框"""
#输入锚框和标签(真实边界框),输出额的使锚框的偏移量,掩码,类别标签。
#anchors形状:(num_anchors,4),包含所有锚框的中心坐标和宽高
#labels形状:(batch_size,num_objects,5)每一行表示一个对象的真实边界框及其类别。每行包括class_id,x_center,y_center,width,height
#初始化,batch_size图像数量,anchors:移除第一维,得到形状(num_anchors,4)的张量。初始化用于存储偏移量,掩码和类别标签的列表
batch_size,anchors=labels.shape[0],anchors.squeeze(0)
batch_offset,barch_mask,batch_class_labels=[],[],[]
device,num_anchors=anchors.device,anchors.shape[0]
#遍历每个图像的标签
for i in range(batch_size):
#label:当前图像的标签
label=labels[i,:,:]
#anchors_bbox_map:通过调用assign_anchor_to_bbox函数,将锚框分配到真实边界框上,返回一个映射,表示每个锚框与真实边界框的关系
anchors_bbox_map=assign_anchor_to_bbox(label[:.1:],anchors,device)
#bbox_mask:用于编辑每个锚框是否被分配了真实边界框,1表示分配,0:未分配
bbox_mask=((anchors_bbox_map>=0).float().unsqueeze(-1)).repeat(1,4)
#初始化类别标签和分配的边界框
#class_labels存储每个锚框的类别标签,初始值为0
#assigned_bb存储每个锚框对应的真实辩煎框的坐标,初始值为0
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:找到被分配的边界框的索引
#bb_idx被分配的边界框的索引
indices_true=torch.nonzero(anchors_bbox_map)
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(abtch_offset)
bbox_mask=torch.stack(batch_mask)
class_labels=torch.stack(batch_class_labels)
return (bbox_offset,bbox_mask,class_labels)
使用非极大值抑制预测边界框
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(())
1591

被折叠的 条评论
为什么被折叠?



