SSD的anchor_box计算
转自:http://www..com/article/129360549/
写的很好很清晰。 防删防遗忘,有问题请联系
看过SSD的tensorflow实现的小伙伴一定对anchor_box的计算很是好奇, 网上也是五花八门的解释,今天我结合源码和原理来解释一下.
default_params = SSDParams(
img_shape=(300, 300),
num_classes=21,
no_annotation_label=21,
feat_layers=['block4', 'block7', 'block8', 'block9', 'block10', 'block11'],
feat_shapes=[(38, 38), (19, 19), (10, 10), (5, 5), (3, 3), (1, 1)],
anchor_size_bounds=[0.15, 0.90],
# anchor_size_bounds=[0.20, 0.90],
anchor_sizes=[(21., 45.),
(45., 99.),
(99., 153.),
(153., 207.),
(207., 261.),
(261., 315.)],
# anchor_sizes=[(30., 60.),
# (60., 111.),
# (111., 162.),
# (162., 213.),
# (213., 264.),
# (264., 315.)],
anchor_ratios=[[2, .5],
[2, .5, 3, 1./3],
[2, .5, 3, 1./3],
[2, .5, 3, 1./3],
[2, .5],
[2, .5]],
anchor_steps=[8, 16, 32, 64, 100, 300],
anchor_offset=0.5,
normalizations=[20, -1, -1, -1, -1, -1],
prior_scaling=[0.1, 0.1, 0.2, 0.2]
)
这个anchor_box的计算与anchor_sizes和anchor_ratios有关.
先解释一下anchor_box的由来. 我们假设当前层是block4, 那么我们的feat_shape就是(38, 38),
你可以将其理解为38*38个cell单元, 每个单元要预测出来几个anchor_box, 不同的层, 这个数理论上讲都是6个, (paper上就是这么写的). 每个box的长宽比是有ratios决定的, paper上是两个 1 , 以及4个其他的值. 但是作者的源码却很调皮的改了一下.
看一下我们的长宽比,这里面没有那两个1, 因为他们是单独设定的:
anchor_ratios=[[2, .5],
[2, .5, 3, 1./3],
[2, .5, 3, 1./3],
[2, .5, 3, 1./3],
[2, .5],
[2, .5]],
我们看到第一层还有最后两层, 只有两种长宽比, 所以这三层就只有4种box.
这个图可以说介绍的相当准确定了, 网上有错的, 以这个为准 . 以block4层为例, 他每个cell单元只有4个box, 包括一大一小两个正方形, 以及两个长方形.
对于小正方形,其边长为min_size, 这个min_size是什么呢?就是前面参数中的anchor_sizes:
anchor_sizes=[(30., 60.),
(60., 111.),
(111., 162.),
(162., 213.),
(213., 264.),
(264., 315.)]
其中每一行为一组, 每一行对应相应的特征层, 第一行对应的就是block4, 依次类推, 对于(30, 60), 30就是min_size, 60就是max_size.
大正方形边长为:
然后是另外两个长方形,这个时候anchor_ratios就出马了,长方形的长宽是有公式可寻的.
这个ratio就是anchor_ratios里的2, 5, 3, 1/3 之类的.
这样,原理上box的大小就介绍完了.但是别忘了这个尺寸是在原图上的尺寸, 我们需要这个尺寸相对于原图的比例.
看下源码的这一部分:
# Add first anchor boxes with ratio=1.
# sizes就是(30, 60), img_shape就是原图尺寸(300, 300)
h[0] = sizes[0] / img_shape[0]
w[0] = sizes[0] / img_shape[1]
di = 1
if len(sizes) > 1:
h[1] = math.sqrt(sizes[0] * sizes[1]) / img_shape[0]
w[1] = math.sqrt(sizes[0] * sizes[1]) / img_shape[1]
di += 1
# r 就是[2, 5, 3, 1/3]
for i, r in enumerate(ratios):
h[i+di] = sizes[0] / img_shape[0] / math.sqrt(r)
w[i+di] = sizes[0] / img_shape[1] * math.sqrt(r)
最后, 既然我们高明白了anchor_size, 这个参数直接决定了当前特征层的box 的大小, 可以看出越靠近输入层, box越小, 越靠近输出层, box越大, 所以 SSD的底层用于检测小目标, 高层用于检测大目标.