是继续在detect.py修改,还是在ploy.py,yolo.py修改


    # Run inference
    model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz))  # warmup
    # model.half().to(device)  # to FP16
    # model.eval()
    seen, windows, dt = 0, [], (Profile(), Profile(), Profile())
    for path, im, im0s, vid_cap, s in dataset:
        with dt[0]:
            im = torch.from_numpy(im).to(model.device) # 将图片转换为tensor,并放到模型的设备上,pytorch模型的输入必须是tensor
            im = im.half() if model.fp16 else im.float()  # uint8 to fp16/32
            im /= 255  # 0 - 255 to 0.0 - 1.0
            if len(im.shape) == 3: # 如果图片的维度为3,则添加batch维度
                im = im[None]  # expand for batch dim
                # 在前面添加batch维度,即将图片的维度从3维转换为4维,即(3,640,640)转换为(1,3,640,640),pytorch模型的输入必须是4维的

        # Inference
        with dt[1]:
            visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
            pred = model(im, augment=augment, visualize=visualize)

        # NMS
        with dt[2]:
            pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)

        # Second-stage classifier (optional)
        # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)

        import math

        # Process predictions
        num_boxes = 0
        max_length_per_class2 = {}  # 用字典记录每个第二类锚框的最长边
        num_class1_boxes_per_class2 = {}  # 用字典记录每个第二类锚框中的第一类锚框数量
        total_distance = 0

        for i, det in enumerate(pred):  # per image
            seen += 1
            if webcam:  # batch_size >= 1
                p, im0, frame = path[i], im0s[i].copy(), dataset.count
                s += f'{i}: '
            else:
                p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)

            p = Path(p)  # to Path
            save_path = str(save_dir / p.name)  # im.jpg
            txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # im.txt
            s += '%gx%g ' % im.shape[2:]  # print string
            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
            imc = im0.copy() if save_crop else im0  # for save_crop
            annotator = Annotator(im0, line_width=line_thickness, example=str(names))
            if len(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()

                # Print results
                for c in det[:, 5].unique():
                    n = (det[:, 5] == c).sum()  # detections per class
                    s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string

                # Write results
                for *xyxy, conf, cls in reversed(det):
                    if save_txt:  # Write to file
                        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh
                        line = (cls, *xywh, conf) if save_conf else (cls, *xywh)  # label format
                        with open(f'{txt_path}.txt', 'a') as f:
                            f.write(('%g ' * len(line)).rstrip() % line + '\n')

                    if save_img or save_crop or view_img:  # Add bbox to image
                        c = int(cls)  # integer class
                        label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
                        annotator.box_label(xyxy, label, color=colors(c, True))
                    if save_crop:
                        save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)

                    # Calculate box statistics
                    if cls == 1:  # Assuming class 1 represents the second category
                        num_boxes += 1
                        length = max(xyxy[2] - xyxy[0], xyxy[3] - xyxy[1])
                        if cls in max_length_per_class2:
                            max_length_per_class2[cls] = max(max_length_per_class2[cls], length)
                        else:
                            max_length_per_class2[cls] = length
                        center_x = (xyxy[0] + xyxy[2]) / 2
                        center_y = (xyxy[1] + xyxy[3]) / 2
                        total_distance += math.sqrt(center_x ** 2 + center_y ** 2)  # Euclidean distance
                    elif cls == 0:  # Assuming class 0 represents the first category
                        if cls in num_class1_boxes_per_class2:
                            num_class1_boxes_per_class2[cls] += 1
                        else:
                            num_class1_boxes_per_class2[cls] = 1

            # Stream results
            im0 = annotator.result()
            if view_img:
                if platform.system() == 'Linux' and p not in windows:
                    windows.append(p)
                    cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux)
                    cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
                cv2.imshow(str(p), im0)
                cv2.waitKey(1)  # 1 millisecond

            # 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)

        # Print time (inference-only)
        LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")

        # Calculate average distance
        if num_boxes > 0:
            average_distance = total_distance / num_boxes
        else:
            average_distance = 0

        # Print results
        t = tuple(x.t / seen * 1E3 for x in dt)  # speeds per image
        LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
        LOGGER.info(f"Number of boxes: {num_boxes}")
        for cls, length in max_length_per_class2.items():
            LOGGER.info(f"Maximum box length for class {int(cls)} {names[int(cls)]}: {length}")
        LOGGER.info(f"Average distance between box centers: {average_distance}")
        for cls, count in num_class1_boxes_per_class2.items():
            LOGGER.info(f"Number of class 1 boxes in class 2 {names[int(cls) + 1]} predictions: {count}")
        if save_txt or save_img:
            s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
            LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
        if update:
            strip_optimizer(weights[0])  # update model (to fix SourceChangeWarning)
#输出结果
image 2/2 E:\yolov5-master\VOC2012\YOLO\images\test\19.jpg: 640x608 5 paddys, 2 caves, 31.9ms
Speed: 1.5ms pre-process, 33.4ms inference, 3.5ms NMS per image at shape (1, 3, 640, 640)
Number of boxes: 2
Maximum box length for class 1 cave: 254.0
Maximum box length for class 1 cave: 530.0
Average distance between box centers: 2019.2025964486338
Number of class 1 boxes in class 2 cave predictions: 1
Number of class 1 boxes in class 2 cave predictions: 1
Number of class 1 boxes in class 2 cave predictions: 1
Number of class 1 boxes in class 2 cave predictions: 1
Number of class 1 boxes in class 2 cave predictions: 1
Results saved to runs\detect\exp248

img


我想要的功能是判断第一类锚框在哪个第二类锚框里,并将每个第二类锚框内的第一类锚框标号分类,并且分别计算各个第二类锚框里边各自有多少第一类锚框数量,计算每个第二类锚框的最长边,计算每一张图中两个第二类锚框之间中心点坐标的距离
将上述代码输出结果换成:
Number of class 1 boxes in class 2 cave predictions1: 2
Number of class 1 boxes in class 2 cave predictions: 3

  • 这篇博客: YoLoV5学习(4)--detect.py程序(预测图片、视频、网络流)逐段讲解~中的 3.1 对source传入的东西进行额外判断 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • source判断
    此处的source对应run函数中的source,代表图片路径;第三行代码判断是否传入为文件地址,IMG_FORMATS表示各种图片类型,VID_FORMATS表示各种视频类型;第四行代码判断是否为网络流传入;第五行代码source.isnumeric判断是否传入为数字,–source 0,数字0表示打开电脑的第一个摄像头;如果是一个网络流且是一个文件,就会进行下载操作。