您好,登錄后才能下訂單哦!
這篇文章給大家介紹怎么在pytorch中將HWC轉(zhuǎn)換為CHW,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
import torch import numpy as np from torchvision.transforms import ToTensor t = torch.tensor(np.arange(24).reshape(2,4,3)) print(t) #HWC 轉(zhuǎn)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轉(zhuǎn)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
補(bǔ)充:opencv python 把圖(cv2下)BGR轉(zhuǎn)RGB,且HWC轉(zhuǎn)CHW
img = cv2.imread("001.jpg") img_ = img[:,:,::-1].transpose((2,0,1))
① 在opencv里,圖格式HWC,其余都是CHW,故transpose((2,0,1))
② img[:,:,::-1]對(duì)應(yīng)H、W、C,彩圖是3通道,即C是3層。opencv里對(duì)應(yīng)BGR,故通過(guò)C通道的 ::-1 就是把BGR轉(zhuǎn)為RGB
注: [::-1] 代表順序相反操作
③ 若不涉及C通道的BGR轉(zhuǎn)RGB,如Img[:,:,0]代表B通道,也就是藍(lán)色分量圖像;Img[:,:,1]代表G通道,也就是綠色分量圖像;
Img[:,:,2]代表R通道,也就是紅色分量圖像。
補(bǔ)充:python opencv 中將圖像由BGR轉(zhuǎn)換為CHW用于后期的深度訓(xùn)練
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()
關(guān)于怎么在pytorch中將HWC轉(zhuǎn)換為CHW就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。