PIL 读取图片格式及数据转换操作
PIL 库读取的图片格式是 H x W x C 格式的。比如一张图是 128x128x3,图片格式 PIL.PngImagePlugin.PngImageFile。 通过 numpy.array(img) 或者 numpy.asarray(img),转化为 uint8 的数值数组形式,数值范围在 0-255 之间。两个函数的区别在于 array 函数会 copy 一个新的副本,占用新的空间,asarray 不会。
import numpy as np
from PIL import Image
img = Image.open(path)
img = np.array(img) # img 是数值范围在 0-255 之间的 uint8 格式数组
# 注意 img 的形状是 H x W x C
# 如果想改变数组形状,可以使用 transpose(idx1, idx2, idx3)
转换为 Tensor 形式
在 PyTorch 中,图片张量形式是 C x H x W,所以要把数组转置,用到 transpose
import torch
from torchvision import transforms
# 1.
img = np.array(img).transpose(2, 0, 1) # 表示 C x H x W
img1 = torch.tensor(img / 255) # 神经网络里的张量数值一般在 0-1 之间归一化处理,所以除以 255
# 此时获得的数组就是形状为 C x H x W 的张量,数值 0-1
# dtype=torch.float64
# 2.
# 或者经过 transforms 处理
trans = transforms.Compose([
transforms.ToTensor()
])
img2 = trans(img) # 自动转化为形状 CxHxW 的张量形式
由 Tensor 转换为图片
经过 tensor 的处理过程之后,要将 tensor 形式转换为图片。 用到 numpy() 函数,fromarray() 函数。uint8 函数
# 这里将 tensor 形式用 numpy() 函数转为数组形式,
# 并且用 transpose 将数组转置为 PIL 能够处理的 WxHxC 形式。
nimg = img.numpy().transpose(1,2,0)
img = nimg * 255 # 将原来 tensor 里 0-1 的数值乘以 255,以便转为 uint8 数据形式,uint8 是图片的数值形式。
# 那么此时 img 就是原料,通过两种方式将 img 化为图片
Image.fromarray(np.uint8(img))
Image.fromarray(img.astype(np.uint8))

