自己敲了一遍才彻底明白anchor是咋操作的,一直想趁假期的时间把faster复现一下…
import torch
import numpy as np
ratios=[0.5,1,2]#长与宽之比 原图对应16*16 将其缩放的比例 有 11*23,16*16,23*11
scales=[8,16,32]#在原图上生成128*128,256*256,512*512的anchor,如128*128是16*16放大8倍,0.5比例则为88*184
size=16 #特征图上一点代表原图多大的区域
cx=size/2.
cy=size/2.#算出每个anchor的中心坐标
def generate_anchor(size,ratios,scales):#生成anchor
anchor=np.zeros((len(ratios)*len(scales),4),dtype=float)
for i in range(len(ratios)):
for j in range(len(scales)):
h=size*scales[j]*np.sqrt(ratios[i])
w=size*scales[j]*np.sqrt(1./ratios[i])
index=i*len(scales)+j
anchor[index][0]=cy-h/2.
anchor[index][1]=cx-w/2.
anchor[index][2] = cy + h / 2.
anchor[index][3] = cx + w / 2.
return anchor.flatten() #返回的anchor是9*4的数组,存放着不同大小和比例anchor的左上、右下相对于中心点的坐标。
#给定中心点,就可以得到在原图中左上、右下的坐标
#传入上一步得到的anchor坐标,缩放比例size,和特征图长宽weight、height
def enumerate_anchor(anchor,size,f_height,f_weight):
anchor_img_y=np.arange(size/2,f_height*size,size)#在原图上以缩放比例为间隔取点
anchor_img_x = np.arange(size/2, f_weight * size, size)
anchor_img_x,anchor_img_y=np.meshgrid(anchor_img_x,anchor_img_y)
shift = np.stack((anchor_img_y.ravel(), anchor_img_x.ravel(),anchor_img_y.ravel(), anchor_img_x.ravel()), axis=1)
a=np.shape(shift)[0]
shift=np.tile(shift, (1, len(scales)*len(ratios)))
anchor=np.tile(anchor,(a,1))
anchor=anchor+shift
#将原图上抽取的点坐标保存(保存两个,分别对应左上、右下),然后将原图上的坐标加上anchor中传入的坐标,就得到了anchor在原图上的左上、右下坐标
return anchor