pytorch 如何实现HWC转CHW
作者:高颜值的杀生丸 时间:2023-06-05 21:58:23
看代码吧~
import torch
import numpy as np
from torchvision.transforms import ToTensor
t = torch.tensor(np.arange(24).reshape(2,4,3))
print(t)
#HWC 转CHW
print(t.transpose(0,2).transpose(1,2))
print(t.permute(2,0,1))
print(ToTensor()(t.numpy()))
D:\anaconda\python.exe C:/Users/liuxinyu/Desktop/pytorch_test/day3/hwc转chw.py
tensor([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]],[[12, 13, 14],
[15, 16, 17],
[18, 19, 20],
[21, 22, 23]]], dtype=torch.int32)
tensor([[[ 0, 3, 6, 9],
[12, 15, 18, 21]],[[ 1, 4, 7, 10],
[13, 16, 19, 22]],[[ 2, 5, 8, 11],
[14, 17, 20, 23]]], dtype=torch.int32)
tensor([[[ 0, 3, 6, 9],
[12, 15, 18, 21]],[[ 1, 4, 7, 10],
[13, 16, 19, 22]],[[ 2, 5, 8, 11],
[14, 17, 20, 23]]], dtype=torch.int32)
tensor([[[ 0, 3, 6, 9],
[12, 15, 18, 21]],[[ 1, 4, 7, 10],
[13, 16, 19, 22]],[[ 2, 5, 8, 11],
[14, 17, 20, 23]]], dtype=torch.int32)Process finished with exit code 0
补充:opencv python 把图(cv2下)BGR转RGB,且HWC转CHW
如下所示:
img = cv2.imread("001.jpg")img_ = img[:,:,::-1].transpose((2,0,1))
① 在opencv里,图格式HWC,其余都是CHW,故transpose((2,0,1))
② img[:,:,::-1]对应H、W、C,彩图是3通道,即C是3层。opencv里对应BGR,故通过C通道的 ::-1 就是把BGR转为RGB
注: [::-1] 代表顺序相反操作
③ 若不涉及C通道的BGR转RGB,如Img[:,:,0]代表B通道,也就是蓝色分量图像;Img[:,:,1]代表G通道,也就是绿色分量图像;
Img[:,:,2]代表R通道,也就是红色分量图像。
补充:python opencv 中将图像由BGR转换为CHW用于后期的深度训练
BGR HWC -> CHW 12 -> HCW 01 -> CHW
import cv2 as cvimport numpy as npimg = cv.imread("lenna.png")#BGR HWC -> CHW 12 -> HCW 01 -> CHWtransform_img = img.swapaxes(1,2).swapaxes(0,1)print(img.shape)print(transform_img.shape)cv.imshow("image0 ",transform_img[0])cv.imshow("image1",transform_img[1])cv.imshow("image2",transform_img[2])cv.waitKey(0)cv.destroyAllWindows()
来源:https://blog.csdn.net/u010970956/article/details/104338072
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Django路由层如何获取正确的url
CI框架整合smarty步骤详解
http通过StreamingHttpResponse完成连续的数据传输长链接方式
python自制简易mysql连接池的实现示例
python中函数默认值使用注意点详解
防止别人iframe的js
使用Python为中秋节绘制一块美味的月饼
![](https://img.aspxhome.com/file/2023/2/96452_0s.jpg)
Python初识二叉树续之实战binarytree
![](https://img.aspxhome.com/file/2023/2/123852_0s.png)
Python3 SSH远程连接服务器的方法示例
![](https://img.aspxhome.com/file/2023/8/124918_0s.png)
Python中异常处理用法
![](https://img.aspxhome.com/file/2023/8/105378_0s.jpg)
sql中的常用的字符串处理函数大全
PyTorch中Torch.arange函数详解
![](https://img.aspxhome.com/file/2023/4/134424_0s.png)
CTF中的PHP特性函数解析之中篇
![](https://img.aspxhome.com/file/2023/7/55517_0s.jpg)
Python文件名的匹配之clob库
![](https://img.aspxhome.com/file/2023/5/125005_0s.png)
Python venv虚拟环境跨设备迁移的实现
![](https://img.aspxhome.com/file/2023/6/104836_0s.jpg)
Dreamweaver快捷键大全
MySQL下高可用故障转移方案MHA的超级部署教程
利用python和ffmpeg 批量将其他图片转换为.yuv格式的方法
pandas读取excel,txt,csv,pkl文件等命令的操作
![](https://img.aspxhome.com/file/2023/8/80448_0s.jpg)