看代码吧~
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 cv import numpy as np img = cv.imread("lenna.png") #BGR HWC -> CHW 12 -> HCW 01 -> CHW transform_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()
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。