DataLoader加载图像时Sizes of tensors must match except in dimension 0. Got 1and 3 in dimension 1的问题解决方法

RuntimeError: invalid argument 0: Sizes of tensors must match except
in dimension 0. Got 1 and 3 in dimension 1 at
/opt/conda/conda-bld/pytorch_1579040055865/work/aten/src/TH/generic/THTensor.cpp:612

通常在pytorch环境中,DataLoader加载图像时,用的是 Image库读取图像,代码如下:

from PIL import Image
Image.open(image_path)

有时候会遇到上述错误,遇到这种情况时,需要统一限制数据通道为3或者1,在我这次情况是,需要1,于是用convert(‘L’)将读入的图像统一转成1通道,代码如下

from PIL import Image
Image.open(image_path).convert('L')

如果是需要通道为3,则转换代码如下:

Image.open(image_path).convert('RGB')

记录下这个小问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用\[1\]:在目标检测服务中,使用yolov7模型通过flask打包成预测服务API。训练,输入的图像大小为1280。如果输入的预测图片大小大于1280,则预测成功;如果小于1280,则会报错RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 27 but got size。根据错误提示,推测问题出在图像处理过程中的resize操作上,具体是在以下代码行出错:pred = self.model(img, augment=self.augment)\[0\]。完整的错误提示如下: RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 48 but got size 47 for tensor number 1 in the list. 引用\[2\]中给出了改造base64_to_image函数的代码,该函数用于将base64格式的图片转换为图片对象。在这个函数中,使用了cv2库对图片进行解码和处理。引用\[3\]分析了问题的原因,发现是在pading过程中少给了一个参数stride,导致小图片在pading过程中像素错误,从而导致了dimension错误。 解决方案是在图像处理过程中正确设置stride参数,确保图片的像素处理正确。 #### 引用[.reference_title] - *1* *2* *3* [记录解决RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 27 but got ...](https://blog.csdn.net/h363924219/article/details/127778425)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值