新聞中心
這篇文章主要為大家展示了“python、PyTorch圖像讀取與numpy轉(zhuǎn)換的示例分析”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“python、PyTorch圖像讀取與numpy轉(zhuǎn)換的示例分析”這篇文章吧。
Tensor轉(zhuǎn)為numpy
np.array(Tensor)
numpy轉(zhuǎn)換為Tensor
torch.Tensor(numpy.darray)
PIL.Image.Image轉(zhuǎn)換成numpy
np.array(PIL.Image.Image)
numpy 轉(zhuǎn)換成PIL.Image.Image
Image.fromarray(numpy.ndarray)
首先需要保證numpy.ndarray 轉(zhuǎn)換成np.uint8型
numpy.astype(np.uint8),像素值[0,255]。
同時(shí)灰度圖像保證numpy.shape為(H,W),不能出現(xiàn)channels
這里需要np.squeeze()。彩色圖象保證numpy.shape為(H,W,3)
之后Image.fromarray(numpy.ndarray)
PIL.Image.Image轉(zhuǎn)換成Tensor
torchvision.transfrom
img=Image.open('00381fa010_940422.tif').convert('L') import torchvision.transforms as transforms trans=transforms.Compose([transforms.ToTensor()]) a=trans(img)
Tensor轉(zhuǎn)化成PIL.Image.Image
先轉(zhuǎn)換成numpy,再轉(zhuǎn)換成PIL.Image.Image
灰度圖像
img=Image.open('00381fa010_940422.tif').convert('L') import torchvision.transforms as transforms trans=transforms.Compose([transforms.ToTensor()]) a=trans(img) b=np.array(a) #b.shape (1,64,64) maxi=b.max() b=b*255./maxi b=b.transpose(1,2,0).astype(np.uint8) b=np.squeeze(b,axis=2) xx=Image.fromarray(b) xx
彩色圖象
img2=Image.open('00381fa010_940422.tif').convert('RGB') import torchvision.transforms as transforms trans=transforms.Compose([transforms.ToTensor()]) a=trans(img2) a=np.array(a) maxi=a.max() a=a/maxi*255 a=a.transpose(1,2,0).astype(np.uint8) b=Image.fromarray(a) b
python-opencv
import cv2 a=cv2.imread('00381fa010_940422.tif') #a.shape (64,64,3) cv2.imwrite('asd.jpg',a) Image.fromarray(a) b=cv2.imread('00381fa010_940422.tif',0)#b.shape (64,64) Image.fromarray(b)
cv2.imread()返回numpy.darray, 讀取灰度圖像之后shape為(64,64),RGB圖像的shape為(64,64,3),可直接用Image.fromarray()轉(zhuǎn)換成Image。
cv寫圖像時(shí),灰度圖像shape可以為(H,W)或(H,W,1)。彩色圖像(H,W,3)
要從numpy.ndarray得到PIL.Image.Image,灰度圖的shape必須為(H,W),彩色為(H,W,3)
對(duì)于Variable類型不能直接轉(zhuǎn)換成numpy.ndarray,需要用.data轉(zhuǎn)換
np.array(a.data)
以上是“python、PyTorch圖像讀取與numpy轉(zhuǎn)換的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)成都網(wǎng)站設(shè)計(jì)公司行業(yè)資訊頻道!
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。
網(wǎng)站題目:python、PyTorch圖像讀取與numpy轉(zhuǎn)換的示例分析-創(chuàng)新互聯(lián)
網(wǎng)站地址:http://www.dlmjj.cn/article/spggg.html