python代码转换为pytorch_python、PyTorch图像读取与numpy转换

python、PyTorch图像读取与numpy转换

发布时间:2018-06-15 16:27,

浏览次数:1147

, 标签:

python

PyTorch

numpy

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值