Faster-RCNN原始碼分析——AnchorGenerator
阿新 • • 發佈:2021-01-24
技術標籤:faster-RCNNpython深度學習機器學習資料結構演算法
一、原理解析:
① 面積保持不變,長、寬比分別為[0.5, 1, 2]是產生的Anchors box
② 如果經過scales變化,即長、寬分別均為 (168=128)、(1616=256)、(16*32=512),對應anchor box如圖
③ 綜合以上兩種變換,最後生成9個Anchor box
二、程式碼實現:
# --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick and Sean Bell
# --------------------------------------------------------
import numpy as np
def generate_anchors(base_size=16, ratios=[0.5, 1, 2],
scales=2**np.arange(3, 6)):
"""通過列舉縱橫比X縮放參考(0、0、15、15)視窗來生成錨定(參考)視窗。"""
base_anchor = np.array([1, 1, base_size, base_size]) - 1
ratio_anchors = _ratio_enum(base_anchor, ratios)
anchors = np.vstack([_scale_enum(ratio_anchors[i, :], scales)
for i in xrange(ratio_anchors.shape[0])])
return anchors
def _whctrs(anchor):
"""
返回錨點(視窗)的寬度,高度,x中心和y中心。
"""
w = anchor[2] - anchor[0] + 1
h = anchor[3] - anchor[1] + 1
x_ctr = anchor[0] + 0.5 * (w - 1)
y_ctr = anchor[1] + 0.5 * (h - 1)
return w, h, x_ctr, y_ctr
def _mkanchors(ws, hs, x_ctr, y_ctr):
"""
給定一個圍繞中心(x_ctr,y_ctr)的寬度(ws)和高度(hs)的向量,輸出一組錨點(windows)。
"""
ws = ws[:, np.newaxis]
hs = hs[:, np.newaxis]
anchors = np.hstack((x_ctr - 0.5 * (ws - 1),
y_ctr - 0.5 * (hs - 1),
x_ctr + 0.5 * (ws - 1),
y_ctr + 0.5 * (hs - 1)))
return anchors
def _ratio_enum(anchor, ratios):
"""
為錨的每個縱橫比列舉一組錨。
"""
w, h, x_ctr, y_ctr = _whctrs(anchor)
size = w * h
size_ratios = size / ratios
ws = np.round(np.sqrt(size_ratios))
hs = np.round(ws * ratios)
anchors = _mkanchors(ws, hs, x_ctr, y_ctr)
return anchors
def _scale_enum(anchor, scales):
"""
為錨定的每個刻度列舉一組錨定。
"""
w, h, x_ctr, y_ctr = _whctrs(anchor)
ws = w * scales
hs = h * scales
anchors = _mkanchors(ws, hs, x_ctr, y_ctr)
return anchors
if __name__ == '__main__':
import time
t = time.time()
a = generate_anchors()
print time.time() - t
print a
from IPython import embed; embed()
參考文獻:
Faster RCNN 學習筆記