预测框和锚框之间的偏移量offset之转换
2023-06-16 本文已影响0人
小黄不头秃
我们在训练目标检测的神经网络的时候通常需要计算预测框和锚框之间的偏移量。那么什么是偏移量,为什么要用偏移量呢?
(1)为什么要用偏移量?
偏移量表示的是相对位置,因为CNN卷积核匹配的是一个个特征,也就是匹配某块像素区域的特征向量,匹配到的位置就是该物体所在的位置。这个位置就是相对位置,我们不太关心其绝对位置。偏移量能够很好的描述一个物体在图像中的位置,并且既然物体相对于锚框的位置知道了,其绝对位置也能够反推。
(2)偏移量计算公式
(2)代码实现:
def offset_cpt(anchor_box, pre_box):
# anchor_box:[x1, y1, x2, y2]
# pre_box:[x1, y1, x2, y2]
w = pre_box[2] - pre_box[0]
h = pre_box[3] - pre_box[1]
offset_x1 = (anchor_box[0] - pre_box[0])/w
offset_x2 = (anchor_box[2] - pre_box[2])/w
offset_y1 = (anchor_box[1] - pre_box[1])/h
offset_y2 = (anchor_box[3] - pre_box[3])/h
return [offset_x1, offset_x2, offset_y1, offset_y2]
def offset_back(box, offset):
# 通过偏移量反算框
# box:[x1, y1, x2, y2]
w = box[2] - box[1]
h = box[3] - box[0]
x1 = offset[0]*w + box[0]
y1 = offset[1]*h + box[1]
x2 = offset[2]*w + box[2]
y2 = offset[3]*h + box[3]
return [x1, y1,x2,y2]