\quad
在使用Pytorch时候,需要导入图片,一般图片的类型都是numpy.ndarray
,需要转换成tensor
类型,
这时候就要使用torchvision.transforms.ToTensor
1.原理
\quad 参考:Pytorch之深入torchvision.transforms.ToTensor与ToPILImage
2.测试&&结果
import cv2 as cv
from torchvision import transforms
image = cv.imread('tttt.jpg')
trans = transforms.ToTensor() # creat object
img_tensor = trans(image) # object call method
print(type(image))
print('image shape:', image.shape)
print('image 第0通道的行数:', image[:, 0, 0].size)
print('image 第0通道的第一个像素值:', image[0, 0, 0])
print('img_tensor shape:', img_tensor.shape)
print('img_tensor 第0维的第一个值:', img_tensor[0, 0, 0])
print('image 第0通道的第一个像素值归1: image[0, 0, 0] / 256 = ', image[0, 0, 0]/256)
<class 'numpy.ndarray'>
image shape: (552, 725, 3)
image 第0通道的行数: 552
image 第0通道的第一个像素值: 227
img_tensor shape: torch.Size([3, 552, 725])
img_tensor 第0维的第一个值: tensor(0.8902)
image 第0通道的第一个像素值归1: image[0, 0, 0] / 256 = 0.88671875
可以看到通过opencv读入了一张图片大小为:(552, 725, 3)
,
通过调用torchvision.transforms.ToTensor
,转化成Tensor
形式,此时的维度为[3, 552, 725]
注意此时Tensor中的每个元素都进行了归一操作,即每个元素都属于[0,1]