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)
以上这篇python、PyTorch图像读取与numpy转换实例就是小编分享给大家的全部内容了,希望能给大家一个参考
您可能感兴趣的文章:
- Python 将RGB图像转换为Pytho灰度图像的实例
- python实现批量nii文件转换为png图像
- Python生态圈图像格式转换问题(推荐)
- opencv-python 读取图像并转换颜色空间实例
- Python+OpenCV实现将图像转换为二进制格式
- Python 实现判断图片格式并转换,将转换的图像存到生成的文件夹中
- 在Python下利用OpenCV来旋转图像的教程
- Python OpenCV读取png图像转成jpg图像存储的方法
- Python图像处理之图像的缩放、旋转与翻转实现方法示例
- Python3+OpenCV2实现图像的几何变换(平移、镜像、缩放、旋转、仿射)
- Python通过VGG16模型实现图像风格转换操作详解
- opencv-python 读取图像并转换颜色空间实例
- OpenCV与Python之图像的读入与显示以及利用Numpy的图像转换
- Python快速转换numpy数组中Nan和Inf的方法实例说明
- Python 将RGB图像转换为Pytho灰度图像的实例
- Python读取MRI并显示为灰度图像实例代码
- 实例:python图像处理(Pillow+numpy)
- 【Python开发】python PIL读取图像转换为灰度图及另存为其它格式(也可批量改格式)
- 利用Python和PIL库读取(非转换)raw格式图像
- OpenCV与Python之图像的读入与显示以及利用Numpy的图像转换
- Numpy中矩阵matrix读取一列的方法及数组和矩阵的相互转换实例
- python PIL读取图像转换为灰度图及另存为其它格式(也可批量改格式)
- python numpy 显示图像阵列的实例
- python读取csv和txt数据转换成向量的实例
- opencv-python 读取图像并转换颜色空间
- python使用numpy读取、保存txt数据的实例
- 图像处理之PIL.Image与numpy.array之间的相互转换 (Python-OpenCV)
- 对python读取CT医学图像的实例详解
- python图像读取、修改和绘制
- python 从excel中读取数据转换成json字符串
- Python读取指定日期邮件的实例