matlab
会自动修改画布大小适应图像
tform = affine2d(tform');
dst=imwarp(img,tform);
figure;imshow(dst);
opencv
需要自己平移
Mat Mt= (Mat_<float>(2, 3) << 1,0,0,0,1,0);
warpAffine(srcimg, img, Mt,Size(N, M));//输出大小N*M
pytorch
和直觉相反,仿射变换矩阵应为A的逆。需要缩放平移才能显示完全。以图像中心缩放。
class AffineGridGen(Module):
def __init__(self, out_h=240, out_w=240, out_ch=3):
super(AffineGridGen, self).__init__()
self.out_h = out_h
self.out_w = out_w
self.out_ch = out_ch
def forward(self, theta):
theta = theta.contiguous()
batch_size = theta.size()[0]
out_size = torch.Size((batch_size, self.out_ch, self.out_h, self.out_w))
return F.affine_grid(theta, out_size)#仿射变换
img=cv2.imread('img.jpg')
img=transforms.ToTensor()(img).unsqueeze(0)
theta_batch=torch.Tensor(np.expand_dims(np.array([[1, 0, 0], [0, 1, 0]]), 0).astype(np.float32))
theta_batch = theta_batch.expand(1, 2, 3)
gridGen=AffineGridGen(500, 500)#输出大小 resize
sampling_grid=gridGen(theta_batch)
sampling_grid.data = sampling_grid.data *padding_factor * crop_factor
warped_image_batch = F.grid_sample(img,sampling_grid)
transforms.ToPILImage()(warped_image_batch[0]).show()
参考affine_grid.