matlab、opencv、pytorch实现仿射变换

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值