记录解决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]

完整错误提示如下:
记录解决RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 27 but got size_第1张图片

原因分析:

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

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

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

解决方案:

最终通过参考原始utils.datasets代码中图像处理过程,改造代码,参考代码如下
记录解决RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 27 but got size_第2张图片

改造自己的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格式...")

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

你可能感兴趣的:(深度学习,python,计算机视觉,深度学习)