torchvision.transforms中定义了一系列数据转换形式,有PILImage,numpy,Tensor间相互转换,还能对数据进行处理。
torchvision.transforms.ToTensor()
把一个取值范围是[0,255]的PIL.Image
转换成Tensor
shape 为(H,W,C)
的numpy.ndarray,转换成形状为[C,H,W]
,取值范围是[0,1]的Tensor
把一个取值范围是[0,255]的PIL.Image转换成Tensor
import numpy as np
from PIL import Image
from torchvision.transforms import transforms
image=Image.open(r"./image/test1.jpg")
c=transforms.ToTensor()(image)
print(c.shape)
shape为(H,W,C)的numpy.ndarray,转换成形状为[C,H,W],取值范围是[0,1.0]的Tensor
n_out = np.random.rand(100,100,3)
print(n_out.dtype)
t_out = transforms.ToTensor()(n_out)
print(t_out.type())
import numpy as np
import torch
from PIL import Image
from torchvision.transforms import transforms
image = Image.open(r"./image/test1.jpg")
a = torch.FloatTensor(np.array(image).transpose(2, 0, 1) / 255.0)
b = transforms.Compose([
transforms.ToTensor()
])(image)
print(a == b)
将ndarray转换成PILImage
将Tensor转换成PILImage
将ndarray转化成PILImage
#初始化随机数种子
np.random.seed(0)
data = np.random.randint(0, 255, 300)
print(data.dtype)
n_out = data.reshape(10,10,3)
#强制类型转换
n_out = n_out.astype(np.uint8)
print(n_out.dtype)
img2 = transforms.ToPILImage()(n_out)
img2.show()
将Tensor转化成PILImage
t_out = torch.randn(3,10,10)
img1 = transforms.ToPILImage()(t_out)
img1.show()