记录解决RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 27 but got size

问题描述

在做目标检测服务过程中,将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]

完整错误提示如下:
在这里插入图片描述

原因分析:

提示:这里填写问题的分析:

分析了半天最终发现是小图片在pading没有处理好,下面代码中少给了一个参数stride,导致小图片在pading过程中像素错误,导致dimension错误。

img = letterbox(img0, new_shape=self.img_size)[0]

解决方案:

最终通过参考原始utils.datasets代码中图像处理过程,改造代码,参考代码如下
在这里插入图片描述

改造自己的base64_to_image函数代码如下:

    def base64_to_image(self,imagebase64):
        """
        输入base64图片,输出图片
        """
        try:
            imgbase64= base64.b64decode(imagebase64)
            buf_str = BytesIO(imgbase64).getvalue()
            nparr = np.fromstring(buf_str, np.uint8)
            img0 = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
            
#             img = letterbox(img0, new_shape=self.img_size)[0]
            img = letterbox(img0, self.img_size, stride=self.stride)[0]
            img = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x416
            img = np.ascontiguousarray(img)
            
            return img,img0
        except:
            print("输入图片必须是BASE64格式...")

因为第一版代码不是自己写的,花了一下午加晚上逐行代码排查,最终解决了,还是记录一下,防止下次忘了。

  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
引用\[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 ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

后知前觉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值