在笔记本电脑上使用python调用yolov5模型做图像识别测试过程中,本地摄像头没有异常,但是在调用外接摄像头进行识别时出现摄像头图像张量的尺寸不匹配
在这之前先了解一些变量和函数:
- self.yolov5_cap = cv2.VideoCapture(0) # yolov5识别使用的摄像头
-
- def yolov5_settings(self, # yolov5参数设置及调用
- max_det=1000, # maximum detections per image
- # device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
- classes=None, # filter by class: --class 0, or --class 0 2 3
- agnostic_nms=False, # class-agnostic NMS
- line_thickness=1, # bounding box thickness (pixels)
- half=False, # use FP16 half-precision inference
- ): # 打开摄像头
- self.max_det = max_det
- self.device = self.ui.device.text()
- self.classes = classes
- self.agnostic_nms = agnostic_nms
- self.line_thickness = line_thickness
- self.half = half
- # Initialize
- set_logging()
- self.device = select_device(self.device)
- print(self.device)
- half &= self.device.type != 'cpu' # half precision only supported on CUDA
-
- self.model = attempt_load(self.ui.model.text(), map_location=self.device) # load FP32 model
- self.names = self.model.module.names if hasattr(self.model,
- 'module') else self.model.names # get class names
- ascii = is_ascii(self.names) # names are ascii (use PIL for UTF-8)
以下是项目代码中调用yolov5处理图像的函数:
- def yolov5_operation_recognize(self): # yolov5处理每一帧图像
- # 获取一帧
- ret, frame = self.yolov5_cap.read()
- # self.decodeDisplay(frame)
- img = torch.from_numpy(frame).to(select_device(self.device))
- img = img.half() if self.half else img.float() # uint8 to fp16/32
- img = img / 255.0 # 0 - 255 to 0.0 - 1.0
- if len(img.shape) == 3:
- img = img[None] # expand for batch dim
- img = img.transpose(2, 3)
- img = img.transpose(1, 2)
- print(img)
- # Inference
- pred = self.model(img, augment=False, visualize=False)[0]
-
- # NMS
- pred = non_max_suppression(pred, self.conf_thres, self.iou_thres, self.classes, self.agnostic_nms, max_det=self.max_det)
-
- # Process predictions
- for i, det in enumerate(pred): # detections per image
- s = ''
- arr = {'person':0, '组织钳':0, '弯止血钳':0, '插值针':0, '直头剪刀':0, '翘头剪刀':0}
- annotator = Annotator(frame, line_width=self.line_thickness, pil=not ascii)
- if len(det):
- # Rescale boxes from img_size to im0 size
- det[:, :4] = scale_coords(img.shape[2:], det[:, :4], frame.shape).round()
- # Print results
- for c in det[:, -1].unique():
- n = (det[:, -1] == c).sum() # detections per class
- arr[str(self.names[int(c)])] = n.item()
- s += str(n.item()) + ' ' + str(self.names[int(c)]) + ' ' # add to string
- # Write results
- for *xyxy, conf, cls in reversed(det):
- c = int(cls) # integer class
- label = f'{self.names[c]} {conf:.2f}'
- annotator.box_label(xyxy, label, color=colors(c, True))
- print(xyxy)
- print('result:' + s)
- self.add_tableWidget(arr)
- show = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # 视频色彩转换回RGB,这样才是现实的颜色
- show_image = QImage(show.data, show.shape[1], show.shape[0],
- QImage.Format_RGB888) # 把读取到的视频数据变成QImage形式
- self.ui.DispLb_3.setPixmap(QPixmap.fromImage(
- show_image.scaled(self.ui.DispLb_3.width(), self.ui.DispLb_3.height()))) # 往显示视频的Label里 显示QImage
控制台报错内容为“RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 76 but got size 75 for tensor number 1 in the list. YOLOv5 a93734c torch 1.12.0 CUDA:0 (NVIDIA GeForce GTX 1060, 6144MiB)”
报错信息中提到的问题是张量的尺寸不匹配。具体来说,在第一次调用self.model的时候,传递给它的图像张量的尺寸不正确,导致出现维度不匹配的错误。
在代码中,有一行将图像转换为张量的代码:
img = torch.from_numpy(frame).to(select_device(self.device))
根据报错信息,我们可以推测到问题出现在这里。为了解决这个问题,我们直接开始排错:
-
检查输入图像的维度和形状是否正确。确保
frame是一个正确的图像数组,并且具有正确的尺寸和通道顺序(通常是RGB顺序)。 -
检查
self.model期望的输入图像尺寸。在YOLOv5模型中,通常会定义一个固定的输入图像尺寸,例如416x416或608x608。确保将输入图像调整为正确的尺寸。 -
在转换图像为张量之前,对图像进行预处理,例如缩放、裁剪或填充,以使其符合模型的输入要求。
-
确保
self.device指定的设备是可用的,并且与YOLOv5模型兼容。如果你使用的是GPU加速,确保你的GPU驱动和CUDA版本与模型要求的兼容。
根据报错信息,模型期望的张量尺寸是76,但实际上得到的尺寸是75。这意味着模型期望每个张量的第一个维度大小为76,但你的输入图像尺寸与此不匹配。因为不同摄像头录制的图像尺寸不一定相同,所以需要在将图像转换成张量之前先固定好图像尺寸。问题锁定在图像尺寸大小上。
一般情况下使用的YOLOv5的默认输入尺寸为416x416或者608x608。这些尺寸是YOLOv5常用的输入大小。
这里我使用OpenCV的resize函数将图像调整为608x608:
frame = cv2.resize(frame, (608, 608))
修改之后的完整函数代码为
- def yolov5_operation_recognize(self): # yolov5处理每一帧图像
- # 获取一帧
- ret, frame = self.yolov5_cap.read()
- frame = cv2.resize(frame, (608, 608)) # 控制图像尺寸大小
- # self.decodeDisplay(frame)
- img = torch.from_numpy(frame).to(select_device(self.device))
- img = img.half() if self.half else img.float() # uint8 to fp16/32
- img = img / 255.0 # 0 - 255 to 0.0 - 1.0
- if len(img.shape) == 3:
- img = img[None] # expand for batch dim
- img = img.transpose(2, 3)
- img = img.transpose(1, 2)
- # Inference
- pred = self.model(img, augment=False, visualize=False)[0]
-
- # NMS
- pred = non_max_suppression(pred, self.conf_thres, self.iou_thres, self.classes, self.agnostic_nms, max_det=self.max_det)
-
- # Process predictions
- for i, det in enumerate(pred): # detections per image
- s = ''
- arr = {'person':0, '组织钳':0, '弯止血钳':0, '插值针':0, '直头剪刀':0, '翘头剪刀':0}
- annotator = Annotator(frame, line_width=self.line_thickness, pil=not ascii)
- if len(det):
- # Rescale boxes from img_size to im0 size
- det[:, :4] = scale_coords(img.shape[2:], det[:, :4], frame.shape).round()
- # Print results
- for c in det[:, -1].unique():
- n = (det[:, -1] == c).sum() # detections per class
- arr[str(self.names[int(c)])] = n.item()
- s += str(n.item()) + ' ' + str(self.names[int(c)]) + ' ' # add to string
- # Write results
- for *xyxy, conf, cls in reversed(det):
- c = int(cls) # integer class
- label = f'{self.names[c]} {conf:.2f}'
- annotator.box_label(xyxy, label, color=colors(c, True))
- print(xyxy)
- print('result:' + s)
- self.add_tableWidget(arr)
- show = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # 视频色彩转换回RGB,这样才是现实的颜色
- show_image = QImage(show.data, show.shape[1], show.shape[0],
- QImage.Format_RGB888) # 把读取到的视频数据变成QImage形式
- self.ui.DispLb_3.setPixmap(QPixmap.fromImage(
- show_image.scaled(self.ui.DispLb_3.width(), self.ui.DispLb_3.height()))) # 往显示视频的Label里 显示QImage
运行后问题得到了解决。根据排错过程再做一些知识的延伸
YOLOv5中默认的输入尺寸为416x416或608x608是因为这些尺寸在性能和准确性之间提供了一种平衡。
YOLOv5是一种基于单阶段检测器的目标检测算法,其主要特点是速度快且具有较高的准确性。为了实现高效的目标检测,YOLOv5采用了一系列的网络结构和技术。
输入图像的尺寸在YOLOv5中影响着算法的速度和检测精度。较小的输入尺寸(如416x416)可以加快模型的推理速度,但可能会降低检测的准确性,特别是对于小目标。较大的输入尺寸(如608x608)可以提高检测的准确性,尤其是对于小目标的检测,但会增加计算量和推理时间。
因此,416x416和608x608被视为一种平衡,提供了较好的速度和准确性之间的折衷方案。这些尺寸通常在YOLOv5的默认配置中,可以根据特定任务的需求进行调整。
需要注意的是,YOLOv5支持任意大小的输入尺寸,并且可以通过调整配置文件或代码中的相关参数来设置所需的输入尺寸。但要注意,更大的输入尺寸可能需要更高的计算资源和更长的推理时间。在选择输入尺寸时,需要考虑到应用场景、硬件资源和实时性等因素。