锚框的形状计算公式
假设原图的高为H,宽为W
锚框形状详细公式推导
以每个像素为中心生成不同形状的锚框
# s是缩放比,ratio是宽高比
def multibox_prior(data, sizes, ratios):
"""生成以每个像素为中心具有不同形状的锚框"""
in_height,in_width = data.shape[-2:] # 取出最后两个元素,即h和w
device,num_sizes,num_ratios = data.device,len(sizes),len(ratios)
boxes_per_pixel = (num_sizes+num_ratios -1) # 以某个像素坐标为中心的锚框为n+m-1
size_tensor = torch.tensor(sizes,device=device) # 将缩放比例列表sizes转为tensor, 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轴上缩放步⻓
print(f'steps_h,steps_w = {steps_h,steps_w}')
# 生成锚框的所有中心点
center_h = (torch.arange(in_height, device=device) + offset_h) * steps_h
center_w = (torch.arange(in_width, device=device) + offset_w) * steps_w
print(f'center_h,center_w={center_h,center_w}')
#网格化中心点坐标
shift_y,shift_x = torch.meshgrid(center_h,center_w)
#reshape成一维,shift_y和shift_x坐标一一对应
shift_y,shift_x = shift_y.reshape(-1),shift_x.reshape(-1)
print(f'shift_y, shift_x={shift_y, shift_x}') #
#norm=√(H/W),这个就是个标号,方便计算
norm = torch.sqrt(torch.tensor(in_height)/torch.tensor(in_width))
# 生成“boxes_per_pixel”个高和宽,
#只考虑包含s1或r1的组合,因此S*r1 与s1*R合并即为n+m-1个锚框
w = torch.cat((size_tensor * torch.sqrt(ratio_tensor[0]),
size_tensor[0] * torch.sqrt(ratio_tensor[1:]))) * norm
h = torch.cat((size_tensor / torch.sqrt(ratio_tensor[0]),
size_tensor[0] / torch.sqrt(ratio_tensor[1:]))) / norm
# 获得归一化后的锚框的w,h的一半,形成偏移量,为了让归一化后的锚框根据中心点 + 偏移量找到 左上角和右下角坐标
anchor_manipulations = torch.stack((-w, -h, w, h)).T.repeat(in_height * in_width, 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)
# 每个中心点都将有“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)
#(x_min,y_min,x_max,y_max) = 归一化后的锚框中心点 + 往左上角和右下角走的偏移量
output = out_grid + anchor_manipulations
return output.unsqueeze(0)
# 将锚框变量Y的形状更改为(图像高度,图像宽度,以同一像素为中心的锚框的数量,4)
boxes = Y.reshape(h, w, 5, 4)# 此处的5由 缩放的数量n + 宽高比的数量m -1 而得
# 访问以(250,250)为中心的第一个锚框。它有四个元素:锚框左上⻆的(x, y)轴坐标和右下⻆的(x, y)轴坐标
boxes[250, 250, 0, :] # 输出的坐标是归一化后的,即归一化前的锚框 w/in_weight 和 h/in_height
img = d2l.plt.imread('../data/images/cat_and_dog.jpg')
h, w = img.shape[:2]
print(h, w)
X = torch.rand(size=(1, 3, h, w))
# 返回的锚框变量Y的形状是(批量大小,锚框的数量,4 (表示锚框的左上角右下角坐标))。
Y = multibox_prior(X, sizes=[0.75, 0.5, 0.25], ratios=[1, 2, 0.5])
Y.shape
根据真实框来标注生成的锚框
文章来源:https://www.toymoban.com/news/detail-671800.html
# 计算IOU
def box_iou(boxes1,boxes2):
'''
:param boxes1: shape = (boxes1的数量,4)
:param boxes2: shape = (boxes2的数量,4)
:param areas1: boxes1中每个框的面积 ,shape = (boxes1的数量)
:param areas2: boxes2中每个框的面积 ,shape = (boxes2的数量)
:return:
'''
# 定义一个Lambda函数,输入boxes,内容是计算得到框的面积
box_area = lambda boxes:((boxes[:,2] - boxes[:,0]) * (boxes[:,3] - boxes[:,0]))
# 计算面积
areas1 = box_area(boxes1)
areas2 = box_area(boxes2)
# 计算交集 要把所有锚框的左上角坐标 与 真实框的所有左上角坐标 作比较,大的就是交集的左上角 ,加个None 可以让锚框与所有真实框作对比
inter_upperlefts = torch.max(boxes1[:,None,:2],boxes2[:,:2])
# 把所有锚框的右下角坐标 与 真实框的所有右下角坐标 作比较,小的就是交集的右下角坐标 ,加个None 可以让锚框与所有真实框作对比
inter_lowerrights = torch.min(boxes1[:,None,2:],boxes2[:,2:])
# 如果右下角-左上角有元素小于0,那就说明没有交集,clamp(min-0)会将每个元素与0比较,小于0的元素将会被替换成0
inters = (inter_lowerrights - inter_upperlefts).clamp(min=0) # 得到w和h
inter_areas = inters[:,:,0] * inters[:,:,1] # 每个样本的 w*h
# 求锚框与真实框的并集
# 将所有锚框与真实框相加,他们会多出来一个交集的面积,所以要减一个交集的面积
union_areas = areas1[:,None] * areas2 - inter_areas
return inter_areas/union_areas
# 每个真实框都要跟所有锚框计算iou,Iou数量等于,真实框数量 * 锚框的数量
def assign_anchor_to_bbox(ground_truth,anchors,devices,iou_threshold=0.5):
# 得到锚框和真实框的个数
num_anchors,num_gt_boxes = anchors.shape[0],ground_truth.shape[0]
# jaccard是计算 所有锚框anchors和真实框ground_truth的交并比
jaccard = box_iou(anchors,ground_truth)
# torch.full(size,fill_value,dtype,device),如下代码生产成一个一位数组,长度为锚框的个数,值为-1
anchors_bbox_map = torch.full((num_anchors,),-1,dtype=torch.long,device=devices)
# 对行取最大值,得到每个真实框对应的最大IOU的锚框
max_ious,indices = torch.max(jaccard,dim=1)
# 返回张量中非0元素的索引,即Max_iou>设定的阈值,位于第i行和第j列的元素x_ij是锚框i和真实边界框j的IoU
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)
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
# 标注类别和偏移量
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
'''
如果一个锚框没有被分配真实边界框,将锚框的类别标记为背景。背景类别的锚框通常被称为负类锚框,其余的被称为正类锚框。
我们使用真实边界框(labels参数)实现以下multibox_target函数,来标记锚框的类别和偏移量(anchors参数)。
此函数将背景类别的索引设置为零,然后将新类别的整数索引递增一。
'''
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:]
# 使用真实边界框来标记锚框的类别。
# 如果一个锚框没有被分配,标记其为背景(值为零)
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)
# 第一个元素表示类别,0代表狗,1代表猫。其余四个元素是左下角坐标和右上角坐标(归一化后的介于0-1之间),归一化的方法是,x坐标 / 宽,y坐标/高
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]])
bbox_scale = torch.tensor((w, h, w, h))
# img = d2l.plt.imread('../data/images/cat_dog.png')
img = d2l.plt.imread('../data/images/cat_and_dog.jpg')
fig = d2l.plt.imshow(img)
# 画出真实框 :(坐标轴,归一化*bbox_scale得到原图规模的坐标,标签,颜色)
show_bboxes(fig.axes,ground_truth[:,1:] * bbox_scale,['dog','cat'],'k') # k最后画出来是黑色
# 画出设置的锚框,把锚框类别标记为0-4
show_bboxes(fig.axes, anchors * bbox_scale, ['0', '1', '2', '3', '4']);
'''
labels[0]:
labels[1]:掩码,形状为(批量大小,锚框数的4倍),对应每个锚框的4个偏移量(负类掩码为0),通过元素乘法,将负类的偏移量过滤掉
labels[2]:锚框对应的标签
'''
labels = multibox_target(anchors.unsqueeze(dim=0),ground_truth.unsqueeze(dim=0))
非极大值抑制
文章来源地址https://www.toymoban.com/news/detail-671800.html
'''
在预测时,我们先为图像生成多个锚框,再为这些锚框一一预测类别和偏移量。一个预测好的边界框则根据其中某个带有预测偏移量的锚框而生成。下面我们实现了offset_inverse函数,该函数将锚框和偏移量预测作为输入,并应用逆偏移变换来返回预测的边界框坐标。
输入: 锚框 和 偏移量预测
输出:根据锚框的原始坐标和预测的偏移量 计算出的 预测的边界框坐标
'''
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
'''按降序对置信度进行排序并返回其索引'''
#@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)
'''调用offset_inverse'''
predicted_bb = offset_inverse(anchors, offset_pred)
'''调用nms'''
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)
到了这里,关于13.4 目标检测锚框标注 & 非极大值抑制的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!