pytorch tensor 实现 cv2.warpAffine( ) -- 未果

13 篇文章 0 订阅
6 篇文章 0 订阅

因为处理数据需求,要对tensor实现 cv2.warpAffine( )的功能

原图: size = 360 × 480
在这里插入图片描述

首先cv2.warpAffine( ),

import cv2
import numpy as np

img_path = r'C:\Users\CSDN\Desktop\00000001.jpg'
image = cv2.imread(img_path)
mapping2 = np.array([[ 1.23704604,  0.,         -256],
 [ 0.,          1.23704604, 256]] ).astype(np.float)
padding =  [ 66.31880208, 111.23558449, 105.38220486]
# mapping 大小2x3, 变换矩阵,一般反映平移或旋转的关系;(512,512)输出大小;boardValue 补值;
cv2.warpAffine(image, mapping2, (512, 512), borderMode=cv2.BORDER_CONSTANT,  borderValue=padding) 
cv2.imshow('cv2warpAffine', crop)
cv2.waitKey(0)

处理之后:size = 512 × 512
在这里插入图片描述

再看再pytorch中实现, 主要是结合使用F.affine_grid() F.grid_sample()

# 注意theta (in pytorch) 和 mapping (in python cv2)的区别: 前面2×2矩阵互为倒数;
#后面1×2平移矩阵,mapping2使用的是绝对像素,theta使用的倍数关系,且上下左右符号是相反的。
theta = torch.tensor([
      [   1/1.23704604,  0.,         0.5],
 [  0.,          1/1.23704604, -0.5]
], dtype=torch.float)

img_torch = torch.from_numpy(image.transpose(2,0,1)) 
img_torch = img_torch.type('torch.FloatTensor')
       
grid = F.affine_grid(theta.unsqueeze(0), img_torch.unsqueeze(0).size())
output = F.grid_sample(img_torch.unsqueeze(0), grid)
new_img_torch = output.squeeze(0).numpy().transpose(1,2,0)
cv2.imshow('', new_img_torch)
cv2.waitKey(0)

处理之后:size = 360 × 480
在这里插入图片描述

两种方式出来的图片部分不一致,猜测输出尺寸的大小不知道,导致具体计算的方式不一样。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值