python、PyTorch圖像讀取與numpy轉(zhuǎn)換實(shí)例
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)
對于Variable類型不能直接轉(zhuǎn)換成numpy.ndarray,需要用.data轉(zhuǎn)換
np.array(a.data)
以上這篇python、PyTorch圖像讀取與numpy轉(zhuǎn)換實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python 類,對象,數(shù)據(jù)分類,函數(shù)參數(shù)傳遞詳解
這篇文章主要介紹了深入理解Python 類,對象,數(shù)據(jù)分類,函數(shù)參數(shù)傳遞,涉及具體代碼示例,具有一定參考價(jià)值,需要的朋友可以了解下。2021-09-09Django模板標(biāo)簽中url使用詳解(url跳轉(zhuǎn)到指定頁面)
這篇文章主要介紹了Django模板標(biāo)簽中url使用詳解(url跳轉(zhuǎn)到指定頁面),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03Python使用execjs執(zhí)行包含中文參數(shù)的JavaScript
爬蟲的開發(fā)過程中,往往需要對JS進(jìn)行模擬,簡單或者通用的還可以在Python中模擬或者找到對應(yīng)的第三方庫,但是復(fù)雜的就可能不好實(shí)現(xiàn)了,下面這篇文章主要給大家介紹了關(guān)于Python使用execjs執(zhí)行包含中文參數(shù)的JavaScript的相關(guān)資料,需要的朋友可以參考下2022-03-03python字符串驗(yàn)證的幾種實(shí)現(xiàn)方法
字符串的驗(yàn)證是確保數(shù)據(jù)符合特定要求的關(guān)鍵步驟之一,本文主要介紹了python字符串驗(yàn)證的幾種實(shí)現(xiàn)方法,具有一定的參考價(jià)值,感興趣的可以了解一下2024-07-07Python中optionParser模塊的使用方法實(shí)例教程
這篇文章主要介紹了Python中optionParser模塊的使用方法,功能非常強(qiáng)大,需要的朋友可以參考下2014-08-08