import timeit
# import chainer.functions as F
# from roi_align_2d import roi_align_2d
import chainer
import numpy as np
class ROIAlign2D():
"""RoI align over a set of 2d planes."""
def __init__(self, outh, outw, spatial_scale):
self.outh, self.outw = outh, outw
self.spatial_scale = spatial_scale
def forward_cpu(self, inputs):
bottom_data, bottom_rois = inputs
channels, height, width = bottom_data.shape[1:]
n_rois = bottom_rois.shape[0]
print(n_rois)
# `np.zeros` needs to be used because the arrays can be
# returned without having some of its values updated.
top_data = np.zeros(
(n_rois, channels, self.outh, self.outw), dtype=np.float32)
for i_roi in range(n_rois):
idx, xmin, ymin, xmax, ymax = bottom_rois[i_roi]
xmin = xmin * self.spatial_scale
xmax = xmax * self.spatial_scale
ymin = ymin * self.spatial_scale
ymax = ymax * self.spatial_scale
roi_width = max(xmax - xmin, 1.)
roi_height = max(ymax - ymin, 1.)
strideh = 1. * roi_height / self.outh
stridew = 1. * roi_width / self.outw
print(strideh,stridew)
for outh in range(self.outh):
for outw in range(self.outw):
cy = (outh + 0.5) * strideh + ymin
cx = (outw + 0.5) * stridew + xmin
x00 = np.array((cy, cx), dtype=np.float32)
p, q = x00 - np.floor(x00)
bound = (height - 1, width - 1)
x0 = np.maximum(np.floor(x00 - 0.0), (0, 0)).astype( #floor向下取整数
np.int32)
x1 = np.minimum(x0 + (1, 1), bound).astype(np.int32)
print(x00,p, q,x0,x1)
roi_data = bottom_data[int(idx), :, x0[0], x0[1]] * (1 - p) * (1 - q) \
+ bottom_data[int(idx), :, x1[0], x0[1]] * p * (1 - q) \
+ bottom_data[int(idx), :, x0[0], x1[1]] * (1 - p) * q \
+ bottom_data[int(idx), :,
x1[0], x1[1]] * p * q
print(bottom_data[int(idx), :, x0[0], x0[1]],bottom_data[int(idx), :, x1[0], x0[1]],bottom_data[int(idx), :, x0[0], x1[1]],
bottom_data[int(idx), :,x1[0], x1[1]])
top_data[i_roi, :, outh, outw] = roi_data
return top_data
def pooling_forward(x, roi, outh, outw, spatial_scale):
y = F.roi_pooling_2d(x, roi, outh, outw, spatial_scale)
return y
def align_forward(x, roi, outh, outw, spatial_scale):
y = roi_align_2d(x, roi, outh, outw, spatial_scale)
return y
if __name__ == '__main__':
# xp = chainer.cuda.cupy
# x = np.zeros((1, 512, 224, 224), dtype=np.float32)
x=[i*1.0 for i in range(1*5*5)]+[i*1.0 for i in range(1*5*5)]
x=np.array(x).reshape(2, 1, 5, 5)
print(x)
# roi = np.array((0, 0, 0, 200, 200), dtype=np.float32).reshape(1, 5)
# roi = np.concatenate([roi, roi, roi])
bbox=[[0,0 ,0., 1., 1.]]
roi=np.array(bbox).reshape(1, 5)
outh = 2
outw = 2
spatial_scale = 1.
a=ROIAlign2D(outh, outw, spatial_scale)
# (x, roi, outh, outw, spatial_scale)
print(a.forward_cpu([x, roi]))
ROIAlign python实现
最新推荐文章于 2023-07-14 15:09:26 发布