目标检测算法中的真实框、预测框和锚框
2021-03-02 本文已影响0人
LabVIEW_Python
目标检测算法中有几种标识物体位置的框,本文依次介绍:
- 边界框,bounding box,用于标识物体的位置,常用格式有左上右下坐标,即xyxy;中心宽高,即xywh。
- 真实框,Ground truth box, 是人工标注的位置,存放在标注文件中
- 预测框,Prediction box, 是由目标检测模型计算输出的框
- 锚框,Anchor box,根据数据集的对象位置类聚出来,用于预测框计算做参考;基于这个参考,算法生成的预测框仅需要在这个锚框的基础上进行“精修或微调fine-tuning”即可,这样算法可以收敛的更快,检测效果更好。
范例程序和运行结果,如下所示:
# 画图展示如何绘制边界框和锚框
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.image import imread
import math
# 定义画矩形框的程序
def draw_rectangle(currentAxis, bbox, edgecolor = 'k', facecolor = 'y', fill=False, linestyle='-'):
# currentAxis,坐标轴,通过plt.gca()获取
# bbox,边界框,包含四个数值的list, [x1, y1, x2, y2]
# edgecolor,边框线条颜色
# facecolor,填充颜色
# fill, 是否填充
# linestype,边框线型
# patches.Rectangle需要传入左上角坐标、矩形区域的宽度、高度等参数
rect=patches.Rectangle((bbox[0], bbox[1]), bbox[2]-bbox[0]+1, bbox[3]-bbox[1]+1, linewidth=1,
edgecolor=edgecolor,facecolor=facecolor,fill=fill, linestyle=linestyle)
currentAxis.add_patch(rect)
plt.figure(figsize=(10, 10))
filename = 'dog.jpg'
im = imread(filename)
plt.imshow(im)
# 使用xyxy格式表示物体真实框
bbox1 = [196, 71, 308, 280]
bbox2 = [190, 66, 300, 275]
bbox3 = [247.2, 131.62, 480.0, 639.32]
currentAxis=plt.gca()
draw_rectangle(currentAxis, bbox1, edgecolor='g')
draw_rectangle(currentAxis, bbox2, edgecolor='r')
# 绘制锚框
def draw_anchor_box(center, length, scales, ratios, img_height, img_width):
"""
以center为中心,产生一系列锚框
其中length指定了一个基准的长度
scales是包含多种尺寸比例的list
ratios是包含多种长宽比的list
img_height和img_width是图片的尺寸,生成的锚框范围不能超出图片尺寸之外
"""
bboxes = []
for scale in scales:
for ratio in ratios:
h = length*scale*math.sqrt(ratio)
w = length*scale/math.sqrt(ratio)
x1 = max(center[0] - w/2., 0.)
y1 = max(center[1] - h/2., 0.)
x2 = min(center[0] + w/2. - 1.0, img_width - 1.0)
y2 = min(center[1] + h/2. - 1.0, img_height - 1.0)
print(center[0], center[1], w, h)
bboxes.append([x1, y1, x2, y2])
for bbox in bboxes:
draw_rectangle(currentAxis, bbox, edgecolor = 'b')
img_height = im.shape[0]
img_width = im.shape[1]
draw_anchor_box([252., 175.5], 100., [2.0], [0.5, 1.0, 2.0], img_height, img_width)
plt.show()
真实框、预测框和锚框