Pytorch报错解决:The size of tensor a (4) must match the size of tensor b (3) at non-singleton dimensio

报错内容

Pytorch报错解决:The size of tensor a (4) must match the size of tensor b (3) at non-singleton dimensio_第1张图片

报错分析

        在执行 F.normalize(tensor, self.mean, self.std, self.inplace) 时,出现了tensor维度不匹配的问题(在axis=0的轴上,需要3维,得到的tensor为4维),该函数由 img = self.transform(img) 调用,因此可以判断在执行 self.transform(img) 前得到的img维度就不对,即读取的img包含RGBA四个通道。

报错代码定位

 

验证及解决

使用的图像:

Pytorch报错解决:The size of tensor a (4) must match the size of tensor b (3) at non-singleton dimensio_第2张图片

 验证代码:

from PIL import Image
import numpy as np

img_path = r"E:\datasets\plants\ip102_v1_1_old\splited_images\Alfalfa\train\Pieris canidia\40563.jpg"

with open(img_path, 'rb') as f:
    img = Image.open(f)
    img2 = img.convert("RGB")

temp_img = np.array(img).transpose(2, 0, 1)
temp_img2 = np.array(img2).transpose(2, 0, 1)
if(temp_img.shape[0] == 4):
    print("abnormal img")

debug截图:Pytorch报错解决:The size of tensor a (4) must match the size of tensor b (3) at non-singleton dimensio_第3张图片         因此,使用PIL.Image读取图像后,要用 .convert("RGB") 转为RGB三个通道。

错误代码修改:

注意: .convert("RGB")是一个有返回值的函数,并不直接对原来的img进行修改。

你可能感兴趣的:(报错解决,pytorch,python)