Pytorch 使用opnecv读入图像由HWC转为BCHW格式

传统使用opencv自带的swapaxes进行转换,然后使用pytorch的from_numpy转为tensor

例如:

img = img.swapaxes(1,2).swapaxes(0,1)

但是有一个常用的图像增广模块albumentations模块中的img_to_tensor进行直接转换

注意:我这里使用unsqueeze是为了验证模型的输出,如果使用pytorch的dataset则不需要使用这个操作

我理解了您的问题。以下是实现全景图像拼接的PytorchOpenCV代码示例: Pytorch代码示例: ```python import torch import cv2 import numpy as np # 加载图像 img1 = cv2.imread('image1.jpg') img2 = cv2.imread('image2.jpg') # 转为pytorch tensor img1_tensor = torch.from_numpy(img1).permute(2, 0, 1).float().unsqueeze(0) img2_tensor = torch.from_numpy(img2).permute(2, 0, 1).float().unsqueeze(0) # 把tensor移到GPU上,如果GPU可用 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") img1_tensor = img1_tensor.to(device) img2_tensor = img2_tensor.to(device) # 计算特征点和特征描述符 sift = cv2.xfeatures2d.SIFT_create() kp1, des1 = sift.detectAndCompute(img1, None) kp2, des2 = sift.detectAndCompute(img2, None) # 匹配特征点 bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True) matches = bf.match(des1, des2) matches = sorted(matches, key=lambda x: x.distance) # 取前几个较好的匹配点 good_matches = matches[:50] # 计算两幅图像的投影变换矩阵 src_pts = np.float32([kp1[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2) dst_pts = np.float32([kp2[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2) M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0) # 将两幅图像拼接起来 result = cv2.warpPerspective(img1, M, (img1.shape[1] + img2.shape[1], img2.shape[0])) result[0:img2.shape[0], 0:img2.shape[1]] = img2 # 显示结果 cv2.imshow("Result", result) cv2.waitKey(0) cv2.destroyAllWindows() ``` OpenCV代码示例: ```python import cv2 import numpy as np # 加载图像 img1 = cv2.imread('image1.jpg') img2 = cv2.imread('image2.jpg') # 计算特征点和特征描述符 sift = cv2.xfeatures2d.SIFT_create() kp1, des1 = sift.detectAndCompute(img1, None) kp2, des2 = sift.detectAndCompute(img2, None) # 匹配特征点 bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True) matches = bf.match(des1, des2) matches = sorted(matches, key=lambda x: x.distance) # 取前几个较好的匹配点 good_matches = matches[:50] # 计算两幅图像的投影变换矩阵 src_pts = np.float32([kp1[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2) dst_pts = np.float32([kp2[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2) M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0) # 将两幅图像拼接起来 result = cv2.warpPerspective(img1, M, (img1.shape[1] + img2.shape[1], img2.shape[0])) result[0:img2.shape[0], 0:img2.shape[1]] = img2 # 显示结果 cv2.imshow("Result", result) cv2.waitKey(0) cv2.destroyAllWindows() ``` 希望这些代码可以帮到您实现全景图像拼接!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值