Tensor转为numpy
np.array(Tensor)
numpy转换为Tensor
torch.Tensor(numpy.darray)
PIL.Image.Image转换成numpy
np.array(PIL.Image.Image)
numpy 转换成PIL.Image.Image
Image.fromarray(numpy.ndarray)
首先需要保证numpy.ndarray 转换成np.uint8型
numpy.astype(np.uint8),像素值[0,255]。
同时灰度图像保证numpy.shape为(H,W),不能出现channels
这里需要np.squeeze()。彩色图象保证numpy.shape为(H,W,3)
之后Image.fromarray(numpy.ndarray)
PIL.Image.Image转换成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转化成PIL.Image.Image
先转换成numpy,再转换成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()转换成Image。
cv写图像时,灰度图像shape可以为(H,W)或(H,W,1)。彩色图像(H,W,3)
要从numpy.ndarray得到PIL.Image.Image,灰度图的shape必须为(H,W),彩色为(H,W,3)
对于Variable类型不能直接转换成numpy.ndarray,需要用.data转换
np.array(a.data)
以上这篇python、PyTorch图像读取与numpy转换实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
更新日志
- 孙悦.1996-伙伴【正大国际】【WAV+CUE】
- 纪钧瀚《钢琴阅读时光 雨中书店聆听轻音乐》[FLAC/分轨][399.62MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[320K/MP3][87.4MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[FLAC/分轨][184.94MB]
- 陈慧娴.2018-Priscilla-Ism演唱会3CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 郑秀文.1999-我应该得到(国)【华纳】【WAV+CUE】
- 陈家慧.2011-钢琴酒吧2CD【龙吟唱片】【WAV+CUE】
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[320K/MP3][45.01MB]
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[FLAC/分轨][109.13MB]
- 赞多《序章》[320K/MP3][45.54MB]
- 许巍.2004-每一刻都是崭新的【步升大风】【WAV+CUE】
- 群星.2024-四方馆影视原声带【韶愔音乐】【FLAC分轨】
- 陈雷.1997-安锁咧【金圆唱片】【WAV+CUE】
- 关淑怡.2013-MY.FAVORITE.SK.3CD【环球】【WAV+CUE】
- Sweety.2006-花言乔语【丰华】【WAV+CUE】