The size of tensor a (4) must match the size of tensor b (3) at non-singleton dimension 0 维度不匹配

在导入一个png文件的时候,发现报这个错,源码如下,经过查询找到了两种解决方案。

from PIL import Image
from torchvision import transforms
from torch.utils.tensorboard import SummaryWriter
import torch

writer = SummaryWriter("logs")
img = Image.open("C:/Users/Mxx/PycharmProjects/pythonProject4/images_set/GOGOGOGO.png")
print(img)
#img = img.convert('RGB')
print(img)

trans_totensor = transforms.ToTensor() #首先创建一个对象,来使用ToTensor的方法
img_tensor = trans_totensor(img)
writer.add_image("ToTensor",img_tensor)

#img = img.convert('RGB')
#Normalize
print(img_tensor[0][0][0])
print("---------")
print(img_tensor.shape)
trans_norm = transforms.Normalize([0.5,0.5,0.5],[0.5,0.5,0.5])
img_norm = trans_norm(img_tensor)
print(img_norm[0][0][0])
writer.add_image("Normalize",img_norm)
writer.close()

1.因为png是四个通道,所以需要在Normalize的时候加一个维度。

trans_norm = transforms.Normalize([0.5,0.5,0.5,0.5],[0.5,0.5,0.5,0.5])

2.讲png转成rgb这样只需要做三个维度的标准化。

img = img.convert('RGB')

将png和RGB以及标准化后的png和RGB进行输出,发现原本的png和RGB差不多。

标准化后的相比于标准化前是变的模糊了,但是标准化后的png和RGB是差不多的。 

The size of tensor a (4) must match the size of tensor b (3) at non-singleton dimension 0 维度不匹配_第1张图片

 更改后的test代码如下

from PIL import Image
from torchvision import transforms
from torch.utils.tensorboard import SummaryWriter
import torch

writer = SummaryWriter("logs")
img = Image.open("C:/Users/Mxx/PycharmProjects/pythonProject4/images_set/GOGOGOGO.png")
print(img)
img_RGB = img.convert('RGB')


trans_totensor = transforms.ToTensor() #首先创建一个对象,来使用ToTensor的方法
img_tensor = trans_totensor(img)
#rgb 的 tensor
imgRGB_tensor = trans_totensor(img_RGB)

writer.add_image("ToTensor",img_tensor)

writer.add_image("RGB-ToTensor",imgRGB_tensor)
#img = img.convert('RGB')
#Normalize

trans_norm_png = transforms.Normalize([0.5,0.5,0.5,0.5],[0.5,0.5,0.5,0.5])
img_norm = trans_norm_png(img_tensor)

trans_norm_RGB = transforms.Normalize([0.5,0.5,0.5],[0.5,0.5,0.5])
imgRGB_norm = trans_norm_RGB(imgRGB_tensor)


writer.add_image("PNG Normalize",img_norm)
writer.add_image("RGB Normalize",imgRGB_norm)
writer.close()

你可能感兴趣的:(python,tornado,list,django,virtualenv)