numpy是channel放在最后,torch是放在前面(channel first)
举个例子:
import numpy as np
from PIL import Image
import torchvision
#一张彩色图像的路径
path3='/content/drive/MyDrive/Unet/dataset/testing/00001.png'
#Image读后转为numpy格式
print(np.array((Image.open(path3))).shape)
#转为torch
img_or = Image.open(path3)
img = torchvision.transforms.ToTensor()(img_or)
print(img.shape)
output:
(800, 600, 3)
torch.Size([3, 800, 600])
如果想把numpy格式的图像数据转化为torch格式的,需要先利用numpy.transpose()把通道转换一下,再torch.tensor(img),或者torch.from_numpy(),这两者的区别是,from_numpy得到的数据与原数据共用地址,也就是更改一个,另一个也随之更改,torch.tensor不会。