# Save results (image with detections) if save_img: if dataset.mode == 'image': cv2.imwrite(save_path, im0) else: # 'video' or 'stream' if vid_path[i] != save_path: # new video vid_path[i] = save_path if isinstance(vid_writer[i], cv2.VideoWriter): vid_writer[i].release() # release previous video writer if vid_cap: # video fps = vid_cap.get(cv2.CAP_PROP_FPS) w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) else: # stream fps, w, h = 30, im0.shape[1], im0.shape[0] save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h)) vid_writer[i].write(im0)
时间: 2024-01-28 20:03:14 浏览: 112
这段代码是YOLOv5中的一部分,用于保存预测结果(带有边界框的图像)。具体来说,如果需要保存图像,则会将带有边界框的图像保存到指定的文件夹中。如果数据集模式为'image',则直接保存图像;否则,如果数据集模式为'video'或'stream',则将带有边界框的图像添加到视频中。如果保存路径与当前视频不同,则会创建新的视频文件(如果之前有一个视频写入器,则会释放它)。如果当前的数据集模式为视频,则会获取视频的FPS、宽度和高度。如果当前的数据集模式为流,则将FPS设置为30,宽度和高度设置为当前图像的宽度和高度。最终,会将带有边界框的图像添加到视频中,并将视频保存到指定的文件夹中。
相关问题
代码解释# Process detections for i, det in enumerate(pred): # detections per image if webcam: # batch_size >= 1 p, s, im0 = path[i], '%g: ' % i, im0s[i].copy() else: p, s, im0 = path, '', im0s save_path = str(Path(out) / Path(p).name) s += '%gx%g ' % img.shape[2:] # print string gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh if det is not None and len(det): # Rescale boxes from img_size to im0 size det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() # Print results for c in det[:, -1].unique(): n = (det[:, -1] == c).sum() # detections per class s += '%g %ss, ' % (n, names[int(c)]) # add to string # Write results for *xyxy, conf, cls in det: if save_txt: # Write to file xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh with open(save_path[:save_path.rfind('.')] + '.txt', 'a') as file: file.write(('%g ' * 5 + '\n') % (cls, *xywh)) # label format if save_img or view_img: # Add bbox to image label = '%s %.2f' % (names[int(cls)], conf) if label is not None: if (label.split())[0] == 'person': people_coords.append(xyxy) # plot_one_box(xyxy, im0, line_thickness=3) plot_dots_on_people(xyxy, im0) # Plot lines connecting people distancing(people_coords, im0, dist_thres_lim=(100, 150)) # Print time (inference + NMS) print('%sDone. (%.3fs)' % (s, t2 - t1)) # Stream results if 1: ui.showimg(im0) if cv2.waitKey(1) == ord('q'): # q to quit raise StopIteration # Save results (image with detections) if save_img: if dataset.mode == 'images': cv2.imwrite(save_path, im0) else: if vid_path != save_path: # new video vid_path = save_path if isinstance(vid_writer, cv2.VideoWriter): vid_writer.release() # release previous video writer fps = vid_cap.get(cv2.CAP_PROP_FPS) w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*opt.fourcc), fps, (w, h)) vid_writer.write(im0)
这段代码是目标检测算法的输出结果处理部分。主要包括以下几个步骤:
1. 对每张图片的检测结果进行处理,包括将检测框从输入图像的尺寸缩放到输出图像的尺寸,并将结果写入文本文件中。
2. 对每个类别的检测结果统计数量,并将数量和类别名称添加到输出字符串中。
3. 对每个检测到的目标绘制边界框,并在边界框上标注类别和置信度。
4. 如果检测到的目标是人,则将其坐标保存在列表中,并在图像上绘制点和连线进行社交距离监测。
5. 将处理后的图像展示出来,并将图像保存到文件中。
解析代码:img = cv2.imread(img_name) print(img_name) showimg = img with torch.no_grad(): img = letterbox(img, new_shape=self.opt.img_size)[0] # Convert # BGR to RGB, to 3x416x416 img = img[:, :, ::-1].transpose(2, 0, 1) img = np.ascontiguousarray(img) img = torch.from_numpy(img).to(self.device) img = img.half() if self.half else img.float() # uint8 to fp16/32 img /= 255.0 # 0 - 255 to 0.0 - 1.0 if img.ndimension() == 3: img = img.unsqueeze(0) # Inference pred = self.model(img, augment=self.opt.augment)[0] # Apply NMS pred = non_max_suppression(pred, self.opt.conf_thres, self.opt.iou_thres, classes=self.opt.classes, agnostic=self.opt.agnostic_nms) print(pred) # Process detections for i, det in enumerate(pred): if det is not None and len(det): # Rescale boxes from img_size to im0 size det[:, :4] = scale_coords( img.shape[2:], det[:, :4], showimg.shape).round() for *xyxy, conf, cls in reversed(det): label = '%s %.2f' % (self.names[int(cls)], conf) name_list.append(self.names[int(cls)]) plot_one_box(xyxy, showimg, label=label, color=self.colors[int(cls)], line_thickness=10) cv2.imwrite('prediction.jpg', showimg) self.result = cv2.cvtColor(showimg, cv2.COLOR_BGR2BGRA) self.result = cv2.resize( self.result, (640, 480), interpolation=cv2.INTER_AREA) self.QtImg = QtGui.QImage( self.result.data, self.result.shape[1], self.result.shape[0], QtGui.QImage.Format_RGB32) self.label.setPixmap(QtGui.QPixmap.fromImage(self.QtImg))
这段代码主要是进行目标检测的推理过程,并将检测结果展示在界面上。
首先,使用OpenCV读取图片,然后对图片进行预处理,包括缩放、转换颜色空间、转换数据类型等。然后,将处理后的图片输入模型进行推理,得到检测结果,再对结果进行非极大值抑制,去除重复的检测框。最后,将检测结果绘制在原图上,保存展示图片,并将展示图片转换为Qt中可以显示的QImage格式,并在界面上展示。
阅读全文