pytorch 如何實現HWC轉CHW
看代碼吧~
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()
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。
推薦閱讀:
- pytorch 把圖片數據轉化成tensor的操作
- python計算機視覺OpenCV入門講解
- Python-OpenCV:cv2.imread(),cv2.imshow(),cv2.imwrite()的區別
- opencv-python圖像處理安裝與基本操作方法
- Python OpenCV 針對圖像細節的不同操作技巧