记录解决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格式...")

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

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
青葱年少的头像青葱年少普通用户
上一篇 2023年7月5日
下一篇 2023年7月5日

相关推荐