import six
from six import __init__ # 兼容python2和python3模块
def generate_anchor_base(base_size=16, ratios=[0.5, 1, 2],
anchor_scales=[8, 16, 32]):
"""Generate base anchors by enumerating aspect ratio and scales.
Args:
base_size (number): The width and the height of the reference window.
ratios (list of floats): anchor 的宽高比
anchor_scales (list of numbers): anchor 的尺度
Returns: Base anchors in a single-level feature maps.`(R, 4)`.
bounding box is `(x_{min}, y_{min}, x_{max}, y_{max})`
"""
import numpy as np
py = base_size / 2.
px = base_size / 2.
anchor_base = np.zeros((len(ratios) * len(anchor_scales), 4),
dtype=np.float32)
for i in six.moves.range(len(ratios)):
for j in six.moves.range(len(anchor_scales)):
// 乘以感受野值,得到缩放后的 anchor 大小
h = base_size * anchor_scales[j] * np.sqrt(ratios[i])
w = base_size * anchor_scales[j] * np.sqrt(1. / ratios[i])
index = i * len(anchor_scales) + j
anchor_base[index, 0] = px - w / 2.
anchor_base[index, 1] = py - h / 2.
anchor_base[index, 2] = px + h / 2.
anchor_base[index, 3] = py + w / 2.
return anchor_base
# test
if __name__ == "__main__":
bbox_list = generate_anchor_base()
print(bbox_list)
这段代码实现了生成一组基础的 anchor box(锚框)。
在目标检测中,anchor box 是预设的一些矩形框框,它们是用来覆盖图像中可能存在物体的区域。在网络训练过程中,锚框会和 ground truth boxes(真实标签框)进行匹配并计算损失,从而学习到更好的目标检测模型。
该函数的输入有三个参数:
base_size:原始的 anchor 框大小,其宽和高都等于 base_size。
ratios:存储 anchor 的宽高比例,分别为 0.5、1 和 2。
anchor_scales:缩放比例,共 3 个,分别为 8、16、32。可以认为是对锚框做卷积的尺度步长,即每次缩小的倍数。
函数返回值是一个 (9, 4) 的 numpy 数组,表示共生成了九个不同尺寸的 anchor box,每个 box 包含四个坐标值 (x_min, y_min, x_max, y_max),这四个值分别代表框的左上角和右下角两个点的坐标。
具体实现过程如下:
创建一个 numpy 数组,大小为 (9, 4)。
遍历所有的 ratios 和 anchor_scales 组合,得到缩放后的 anchor box 尺寸。
计算 anchor box 左上和右下角坐标,并保存到 anchor_base 数组中。
最后打印出生成的所有 anchor box。
运行结果:
[[ -82.50967 -37.254833 53.254833 98.50967 ]
[-173.01933 -82.50967 98.50967 189.01933 ]
[-354.03867 -173.01933 189.01933 370.03867 ]
[ -56. -56. 72. 72. ]
[-120. -120. 136. 136. ]
[-248. -248. 264. 264. ]
[ -37.254833 -82.50967 98.50967 53.254833]
[ -82.50967 -173.01933 189.01933 98.50967 ]
[-173.01933 -354.03867 370.03867 189.01933 ]]