imwarp matlab,matlab、opencv、pytorch实现仿射变换

matlab、opencv、pytorch实现仿射变换

matlab、opencv、pytorch实现仿射变换

matlab

tform = affine2d(tform');

dst=imwarp(img,tform);

figure;imshow(dst);%会自动移到中心

7f8746877c0aa05897293f83b371de13.png

opencv

需要自己平移

Mat Mt= (Mat_(2, 3) << 1,0,0,0,1,0);

warpAffine(srcimg, img, Mt,Size(N, M));//输出大小N*M

b844999af3f356c1669278ae3a7d2bf2.png

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()

de8840698139c1b7698236ee81ce592b.png

matlab、opencv、pytorch实现仿射变换相关教程

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OpenCV是一个开源的计算机视觉库,提供了丰富的图像处理和计算机视觉算法。它可以用于实现各种图像处理任务,包括仿射变换。 在OpenCV中,可以使用函数cv2.warpAffine()来实现仿射变换。该函数接受输入图像、仿射变换矩阵和输出图像的大小作为参数,并返回经过仿射变换后的图像。 要实现仿射变换的反运算,可以使用cv2.invertAffineTransform()函数。该函数接受仿射变换矩阵作为参数,并返回其逆矩阵。 下面是一个示例代码,展示了如何使用OpenCV实现仿射变换的反运算: ```python import cv2 import numpy as np # 读取输入图像 img = cv2.imread('input.jpg') # 定义仿射变换矩阵 M = np.float32([[1, 0, 100], [0, 1, 50]]) # 进行仿射变换 transformed_img = cv2.warpAffine(img, M, (img.shape[1], img.shape[0])) # 计算仿射变换的逆矩阵 inv_M = cv2.invertAffineTransform(M) # 进行反运算 reversed_img = cv2.warpAffine(transformed_img, inv_M, (transformed_img.shape[1], transformed_img.shape[0])) # 显示结果 cv2.imshow('Input', img) cv2.imshow('Transformed', transformed_img) cv2.imshow('Reversed', reversed_img) cv2.waitKey(0) cv2.destroyAllWindows() ``` 在上述代码中,我们首先读取输入图像,然后定义了一个仿射变换矩阵M。通过调用cv2.warpAffine()函数,我们将输入图像进行了仿射变换,并得到了变换后的图像transformed_img。接着,我们使用cv2.invertAffineTransform()函数计算了仿射变换矩阵的逆矩阵inv_M。最后,我们再次调用cv2.warpAffine()函数,将变换后的图像进行反运算,得到了恢复到原始状态的图像reversed_img。 希望以上内容能够帮助到你!如果有任何问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值