【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
【pytorch报错解决】expected input to have 3 channels, but got 1 channels instead的更多相关文章
- Anaconda 安装 pytorch报错解决方法
一.安装Pytorch: # -c 指定用pytorch镜像源下载软件conda install pytorch torchvision cpuonly -c pytorch 报错: 二.配置: ch ...
- pytorch报错:ValueError: Expected more than 1 value per channel when training, got input size torch.Size([1,512,1,1])
1.pytorch报错:ValueError: Expected more than 1 value per channel when training, got input size torch.S ...
- org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 3报错解决
报错的原因翻译出来: 预期的一个结果(或null)返回selectOne(),但发现:3 意思就是你想得到一个结果值,但是返回了三个结果值. 一般可能测试的时候我们存了几条一样的数据,在登录时,会把同 ...
- selenium调用Firefox和Chrome需要注意的一些问题,和出现的报错selenium:expected [object undefined] undefined to be a string
在高版本selenium下如:selenium3.4.3 1.高版本的selenium需要浏览器安装一些补丁驱动 Firefox:geckodriver 下载网址:http://download.cs ...
- vue 项目 npm install 报错解决
node-sass 安装报错解决办法 2017年04月15日 14:34:25 阅读数:20189 E:\kibana>npm install node-sass > node-sass@ ...
- Pytorch报错:cuda runtime error (59) : device-side assert triggered at /pytorch/aten/src/THC/generic/THCTensorMath.cu:26
Pytorch报错:cuda runtime error (59) : device-side assert triggered at /pytorch/aten/src/THC/generic/TH ...
- Linux部署Django:报错 nohup: ignoring input and appending output to ‘nohup.out’
一.部署 Django 到远程 Linux 服务器 利用 xshell 通过 ssh 连接到 Linux服务器,常规的启动命令是 python3 manage.py runserver 但是,关闭 x ...
- JavaScript函数报错SyntaxError: expected expression, got ';'
故事背景:编写Javaweb项目,在火狐浏览器下运行时firebug报错SyntaxError: expected expression, got ';'或者SyntaxError: expected ...
- MySQL5.7.26安装及启动报错解决
一.安装依赖包 [root@db01 ~]# yum install -y lrzsz [文件上传/下载] [root@db01 ~]# yum -y install xfsprogs [安装磁盘格式 ...
随机推荐
- Redis常用数据类型及各种数据类型应用和实现方式
Redis常用数据类型: StringHashListSetSorted set 在具体描述这几种数据类型之前,我们先通过一张图了解下Redis内部内存管理中是如何描述这些不同数据类型的: 首先Red ...
- docker容器中解决出现:^H^H^H^H
docker容器中解决出现:^H^H^H^H 环境:docker容器是debain系统 解决: 把stty erase ^H 添加到.bash_profile中 vim /etc/profile st ...
- Linux配置Docker镜像加速器
Docker默认镜像为官方镜像,可以配置成国内加速器提高速度 登录阿里云控制台,搜索容器镜像服务获取到镜像加速服务地址 新建配置文件 /etc/docker/daemon.json 输入以下内容 { ...
- 第八章 跨语言服务治理方案 Service Mesh
8.1 Service Mesh 概述 新兴的下一代微服务架构,被称为下一代微服务,同时也是云原生技术栈的代表技术之一. 8.1.1 Service Mesh的由来 从2016年到2018年,serv ...
- C++标准模板库STL算法与自适应容器(栈和队列)
参考<21天学通C++>第23与第24章节,对STL算法与自适应容器进行介绍. 实际上在前面的STL顺序容器.关联容器进行介绍时或多或少引用到了一些STL算法中的模板函数.而自适应容器是在 ...
- Spring Boot 初学避免犯不必要的错误
创建项目时的目录问题: 新包体(例如controller)必须和启动文件 DemoApplication.java 在同一级目录下,如下 spring boot 初步使用创建新的项目:https:// ...
- 安装本地 jar 文件
Maven 提供了 maven-install-plugin 可将 jar 文件安装至本地 repository.安装命令如下: mvn install:install-file -Dfile= -D ...
- php生成0~1随机小数方法
php生成0~1随机小数方法JavaScript生成0~1随机小数的方法可以调用自带的Math.random(); php生成0~1随机小数方法如下:<pre><?php/** * ...
- pandas对时间列分组求diff遇到的问题
例子: df = pd.DataFrame() df['A'] = [1, 1, 2] df['B'] = [datetime.date(2018, 1, 2), datetime.date(2018 ...
- Python——多态、检查类型
一.多态 Python变量并不需要声明类型,同一个变量可以在不同的时间引用不同的对象,当一个变量在调用同一个方法,可以呈现出多种行为,而具体呈现出哪种行为由该变量引用的对象来决定,这就是多态. 先看一 ...