【pytorch报错解决】expected input to have 3 channels, but got 1 channels instead
遇到的问题
数据是png图像的时候,如果用PIL读取图像,获得的是单通道的,不是多通道的。虽然使用opencv读取图片可以获得三通道图像数据,如下:
def __getitem__(self, idx):
image_root = self.train_image_file_paths[idx]
image_name = image_root.split(os.path.sep)[-1]
image = cv.imread(image_root)
if self.transform is not None:
image = self.transform(image)
label = ohe.encode(image_name.split('_')[0])
return image, label
但是会出现报错:
TypeError: img should be PIL Image. Got <class 'numpy.ndarray'>
File "c:/Users/pprp/Desktop/pytorch-captcha-recognition-master/captcha_train.py", line 77, in <module>
main(args)
File "c:/Users/pprp/Desktop/pytorch-captcha-recognition-master/captcha_train.py", line 47, in main
predict_labels = cnn(images)
File "E:\ProgramData\Miniconda3\envs\pytorch\lib\site-packages\torch\nn\modules\module.py", line 493, in __call__
result = self.forward(*input, **kwargs)
File "E:\ProgramData\Miniconda3\envs\pytorch\lib\site-packages\torchvision\models\resnet.py", line 192, in forward
x = self.conv1(x)
File "E:\ProgramData\Miniconda3\envs\pytorch\lib\site-packages\torch\nn\modules\module.py", line 493, in __call__
result = self.forward(*input, **kwargs)
File "E:\ProgramData\Miniconda3\envs\pytorch\lib\site-packages\torch\nn\modules\conv.py", line 338, in forward
self.padding, self.dilation, self.groups)
RuntimeError: Given groups=1, weight of size 64 3 7 7, expected input[64, 60, 160, 3] to have 3 channels, but got 60 channels instead
最终解决方案:
class mydataset(Dataset):
def __init__(self, folder, transform=None):
self.train_image_file_paths = [os.path.join(folder, image_file) for image_file in os.listdir(folder)]
self.transform = transforms.Compose([
transforms.ToTensor(), # 转化为pytorch中的tensor
transforms.Lambda(lambda x: x.repeat(1,1,1)), # 由于图片是单通道的,所以重叠三张图像,获得一个三通道的数据
# transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))
]) # 主要改这个地方
def __len__(self):
return len(self.train_image_file_paths)
def __getitem__(self, idx):
image_root = self.train_image_file_paths[idx]
image_name = image_root.split(os.path.sep)[-1]
image = Image.open(image_root)
if self.transform is not None:
image = self.transform(image)
label = ohe.encode(image_name.split('_')[0])
return image, label
pytorch transform 知识点:https://blog.csdn.net/u011995719/article/details/85107009
PIL PNG格式通道问题的解决方法 : https://www.cnblogs.com/wzjbg/p/8516531.html
代码改变世界
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程