torchvision 中transform 的使用
torchvision.transforms方法
-
把PIL.Image转换成torch.FloatTensor
-
把shape为(H,W,C)的numpy.ndarry转换成(C,H,W),取值范围是[0,1.0]的torch.FloatTensor
-
(H,W,C)以为(高,宽,通道数)
-
黑白图片的通道数为1,每个像素点的取值为[0,255]
-
彩色图片的通道数为(R,G,B),每个通道的每个像素点的取值为[0,255]
transforms.ToTensor()(img)
- tensor.permute(2,0,1)
-
import torchvision
img_pil=mnist[0][0]
img_torch=torchvision.transforms.ToTensor()(img_pil)
import matplotlib.pyplot as plt
%matplotlib inline
print('img_pil.size = ',img_pil.size)
print('img_torch.shape = ',img_torch.shape)
print(img_torch)
plt.imshow(img_pil)
img_pil.size = (28, 28)
img_torch.shape = torch.Size([1, 28, 28])
41
<matplotlib.image.AxesImage at 0x1fb1fa24d68>
img_pil_1=torchvision.transforms.ToPILImage()(img_torch)
print(img_pil_1.size)
plt.imshow(img_pil_1)
(28, 28)
38
<matplotlib.image.AxesImage at 0x1fb1f9c5358>
#tensor到numpy的转化
import numpy as np
img_np=np.array(img_torch.permute(1,2,0))
print(img_np.shape)
(28, 28, 1)
torchvision.tranforms.Normalize(mean,std)
z
=
x
−
m
e
a
n
s
t
d
z=\frac{x-mean}{std}
z=stdx−mean
给定均值:mean, shape和图片的通道数相同,方差:std,和图片的通道数相同,将会把Tensor规范化处理。
a=transforms.ToTensor()(a)
normal=transforms.Normalize([1,1,1],[1,1,1])
print(normal)
c=normal(a)
print(c)
Normalize(mean=[1, 1, 1], std=[1, 1, 1])
tensor([[[-0.1059, -0.1059, -0.1059, ..., -0.1020, -0.1020, -0.1059],
[-0.1020, -0.1020, -0.1020, ..., -0.0980, -0.0980, -0.1020],
[-0.1020, -0.1020, -0.1020, ..., -0.0980, -0.0980, -0.1020],
...,
[-0.1020, -0.0980, -0.1020, ..., -0.1020, -0.1020, -0.1059],
[-0.1020, -0.0980, -0.1020, ..., -0.1020, -0.1020, -0.1059],
[-0.1020, -0.0980, -0.1020, ..., -0.1020, -0.1020, -0.1059]],
[[-0.1020, -0.1020, -0.1020, ..., -0.0980, -0.0980, -0.1020],
[-0.0980, -0.0980, -0.0980, ..., -0.0941, -0.0941, -0.0980],
[-0.0980, -0.0980, -0.0980, ..., -0.0941, -0.0941, -0.0980],
...,
[-0.0980, -0.0941, -0.0980, ..., -0.0980, -0.0980, -0.1020],
[-0.0980, -0.0941, -0.0980, ..., -0.0980, -0.0980, -0.1020],
[-0.0980, -0.0941, -0.0980, ..., -0.0980, -0.0980, -0.1020]],
[[-0.0941, -0.0941, -0.0941, ..., -0.0902, -0.0902, -0.0941],
[-0.0902, -0.0902, -0.0902, ..., -0.0863, -0.0863, -0.0902],
[-0.0902, -0.0902, -0.0902, ..., -0.0863, -0.0863, -0.0902],
...,
[-0.0902, -0.0863, -0.0902, ..., -0.0902, -0.0902, -0.0941],
[-0.0902, -0.0863, -0.0902, ..., -0.0902, -0.0902, -0.0941],
[-0.0902, -0.0863, -0.0902, ..., -0.0902, -0.0902, -0.0941]]])
torchvision.transforms.Copmose(transforms)
#nice 是Image
com=transforms.Compose([
transforms.ToTensor(),
# transforms.ToPILImage()
])
print(com)
a=com(nice)
print(type(a))
Compose(
ToTensor()
)
<class 'torch.Tensor'>
com=transforms.Compose([
transforms.ToTensor(),
transforms.ToPILImage()
])
print(com)
a=com(nice)
print(type(a))
Compose(
ToTensor()
ToPILImage()
)
<class 'PIL.Image.Image'>