YOLO-x代码修改,输出检测框坐标和物体类别及其中心坐标

yolo-x的demo能够直接输出可视化的结果,但我还想得到物体类别和坐标等信息,直接在demo上更改就行了。

修改def image_demo:

def image_demo(predictor, vis_folder, path, current_time, save_result):
    if os.path.isdir(path):
        files = get_image_list(path)
    else:
        files = [path]
    files.sort()
    for image_name in files:
        outputs, img_info = predictor.inference(image_name)
        result_image = predictor.visual(outputs[0], img_info, predictor.confthre)
       #以下为修改内容
        for bbox in outputs[0]:
            label = int(bbox[6])  # 类别索引
            confidence = bbox[4] * bbox[5]  # 置信度
            class_name = predictor.cls_names[label]  # 类别名称

            # 计算中心坐标
            center_x = (bbox[0] + bbox[2]) / 2.0
            center_y = (bbox[1] + bbox[3]) / 2.0

            # 输出四个角的坐标
            x1, y1, x2, y2 = bbox[0], bbox[1], bbox[2], bbox[3]

            print(f"Detected object: {class_name}, Confidence: {confidence:.2f}")
            print(f"  Center coordinates: ({center_x:.2f}, {center_y:.2f})")
            print(f"  Top-left corner: ({x1:.2f}, {y1:.2f})")
            print(f"  Top-right corner: ({x2:.2f}, {y1:.2f})")
            print(f"  Bottom-lef corner: ({x1:.2f}, {y2:.2f})")
            print(f"  Bottom-right corner: ({x2:.2f}, {y2:.2f})")
#修改到此结束

        if save_result:
            save_folder = os.path.join(
                vis_folder, time.strftime("%Y_%m_%d_%H_%M_%S", current_time)
            )
            os.makedirs(save_folder, exist_ok=True)
            save_file_name = os.path.join(save_folder, os.path.basename(image_name))
            logger.info("Saving detection result in {}".format(save_file_name))
            cv2.imwrite(save_file_name, result_image)
        ch = cv2.waitKey(0)
        if ch == 27 or ch == ord("q") or ch == ord("Q"):
            break

看看运行结果:

2023-09-17 13:28:08.605 | INFO     | __main__:main:278 - Args: Namespace(camid=0, ckpt='preModels/yolox_l.pth', conf=0.25, demo='image', device='gpu', exp_file='exps/default/yolox_l.py', experiment_name='yolox_l', fp16=False, fuse=False, legacy=False, name=None, nms=0.45, path='assets/7.jpg', save_result=True, trt=False, tsize=640)
2023-09-17 13:28:09.057 | INFO     | __main__:main:288 - Model Summary: Params: 54.21M, Gflops: 155.65
2023-09-17 13:28:09.925 | INFO     | __main__:main:301 - loading checkpoint
2023-09-17 13:28:11.197 | INFO     | __main__:main:305 - loaded checkpoint done.
2023-09-17 13:28:16.930 | INFO     | __main__:inference:165 - Infer time: 5.7199s
Detected object: bus, Confidence: 0.66
  Center coordinates: (335.09, 276.93)
  Top-left corner: (269.66, 222.62)
  Top-right corner: (400.52, 222.62)
  Bottom-lef corner: (269.66, 331.24)
  Bottom-right corner: (400.52, 331.24)
2023-09-17 13:28:16.934 | INFO     | __main__:image_demo:221 - Saving detection result in ./YOLOX_outputs/yolox_l/vis_res/2023_09_17_13_28_11/7.jpg

成功!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是使用YOLOv7检测图像中的物体输出检测中心坐标和宽高的Python代码示例: ``` import torch import cv2 import numpy as np from yolov7.utils.datasets import letterbox from yolov7.models.experimental import attempt_load from yolov7.utils.general import non_max_suppression, scale_coords, xyxy2xywh # 加载YOLOv7模型 weights = 'yolov7s.pt' device = 'cuda:0' if torch.cuda.is_available() else 'cpu' model = attempt_load(weights, map_location=device) # 加载物体类别标签 classes = [] with open("coco.names", "r") as f: classes = [line.strip() for line in f.readlines()] # 设置输入图像尺寸和缩放因子 input_size = 640 scale_factor = 1/255.0 # 读取图像并进行预处理 image = cv2.imread("image.jpg") height, width = image.shape[:2] image = letterbox(image, new_shape=input_size)[0] image = image[:, :, ::-1].transpose(2, 0, 1).copy() image = torch.from_numpy(image).float().div(255.0).unsqueeze(0) # 将预处理后的图像输入到网络中进行推理 model.eval() with torch.no_grad(): output = model(image.to(device))[0] output = non_max_suppression(output, conf_thres=0.5, iou_thres=0.5) # 解析输出层并筛选出置信度较高的物体 boxes = [] confidences = [] class_ids = [] if output[0] is not None: for detection in output[0]: x1y1 = (detection[:2] * input_size).int() x2y2 = (detection[2:4] * input_size).int() box = torch.cat([x1y1, x2y2], dim=-1).float() box = scale_coords(image.shape[2:], box, image.shape[2:]).tolist() x, y, w, h = xyxy2xywh(torch.tensor(box))[0].tolist() center_x = x + w/2 center_y = y + h/2 boxes.append([x, y, w, h]) confidences.append(float(detection[4])) class_ids.append(int(detection[5])) # 应用非最大抑制(NMS)算法筛选出重叠度较小的物体 indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4) # 绘制筛选后的物体输出中心坐标和宽高 for i in indices: i = i[0] x, y, w, h = boxes[i] center_x = x + w/2 center_y = y + h/2 print(classes[class_ids[i]], center_x, center_y, w, h) cv2.rectangle(image, (int(x), int(y)), (int(x + w), int(y + h)), (0, 255, 0), 2) cv2.putText(image, classes[class_ids[i]], (int(x), int(y)-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) # 显示输出图像 cv2.imshow("YOLOv7 Object Detection", image) cv2.waitKey(0) cv2.destroyAllWindows() ``` 其中,`yolov7s.pt`是YOLOv7模型的权重文件,`coco.names`是物体类别标签文件,`image.jpg`是待检测图像。可以根据实际需求修改这些文件的路径和名称。在运行代码前需要确保已安装PyTorch库、OpenCV库和Numpy库,并将yolov7目录添加到Python路径中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值