1.tensor你可以理解成就是numpy中的数组(只不过tensor可以使用GPU来加快计算,而array不行)
所以你需要掌握怎么创建tensor,怎么将numpy中的数组转化为tensor,怎么将图片转化为tensor(如果是图片,可以使用OpenCV包将图片转化为numpy数组,然后再将numpy数组转化为tensor)
图片转化为tensor的全过程:
#给定一张图片的路径地址
img_path="/home/ouyang/milu_Unet/data/test/images/1.jpg""
img=Image.open(img_path)
#Image.open()函数传入的是图片地址,返回的是:
#<PIL.Image.Image image mode=L size=512x512 at 0x7FDEB1F2B240>
#将Image类对象转化为一个numpy数组
img_array=np.array(img)
#将numpy数组转化为pytorch里面的tensor
img_tensor=torch.from_numpy(img_array)
2.得到tensor之后,如果想得到tensor的大小可以调用张量的size属性或者shape属性
print(x.size)
print(x.shape)
一个实际的例子:
TypeError: flatten(): argument 'input' (position 1) must be Tensor, not numpy.ndarray
这里flatten()函数要求的参数类型是Tensor,而不是传入的numpy里的array数组