Ultralytics获取coco指标

1、获取val()结果并保存json文件

import warnings

warnings.filterwarnings('ignore')
from ultralytics import YOLO

# https://docs.ultralytics.com/modes/train/

if __name__ == '__main__':
    model = YOLO('runs/models/v8m/weights/best.pt')
    # model.load('') # loading pretrain weights
    model.val(data='ultralytics/cfg/datasets/VisDrone.yaml',
                cache=False,
                imgsz=640,
                epochs=200,
                batch=4,
                split='test', # 测试,不使用测试集则删除该行
                workers=8,
                device='0',
                resume=True,  # last.pt path
                project='runs/val',
                name='exp',
                # amp=True
                )

2、获取coco指标

import argparse
import json
import os

from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval


def parse_opt():
    parser = argparse.ArgumentParser()
    # 原数据集生成的json文件 
    parser.add_argument('--anno_json', type=str, default='E:/1-Data/DataSet/VisDrone2019/Anno/test.json',
                        help='training model path')
    # val时生成的json文件 
    parser.add_argument('--pred_json', type=str, default='runs/val/exp14/predictions.json', help='data yaml path')

    return parser.parse_known_args()[0]


def cover_pred_json_id(anno_json_path, pred_json_path):
    with open(anno_json_path, "r") as f:
        ann_json = json.load(f)
    with open(pred_json_path, "r") as f:
        pred_json = json.load(f)
    for pred_item in tqdm(pred_json,desc="读取中:",):
        img_id = pred_item["image_id"]
        ann_id = [ann_item["id"] for ann_item in ann_json["images"] if ann_item["file_name"][:-4] == img_id]
        try:
            pred_item["image_id"] = ann_id[0]
        except IndexError:
            print(img_id)

    out_json_path = os.path.join(os.path.dirname(pred_json_path), "newpred.json")
    with open(out_json_path, 'w') as file:
        json.dump(pred_json, file, indent=4)
    return out_json_path

if __name__ == '__main__':
    opt = parse_opt()
    anno_json = opt.anno_json
    pred_json = opt.pred_json
    pred_json = cover_pred_json_id(anno_json, pred_json)  # cover yolo id to coco id
    anno = COCO(anno_json)  # init annotations api
    print(pred_json)
    pred = anno.loadRes(pred_json)  # init predictions api
    eval = COCOeval(anno, pred, 'bbox')
    eval.evaluate()
    eval.accumulate()
    eval.summarize()

3、yolo2coco 格式转化

import os
import json
from PIL import Image

"""
首先满足YOLO格式要求:
        images:
            train
            val
            test
        labels:
            train
            val
            test
"""

# 设置数据集路径
output_dir = r"E:\1-Data\DataSet\UAV-DT"  # 修改为YOLO格式的数据集路径;
dataset_path = r"E:\1-Data\DataSet\UAV-DT\yolo"  # 修改你想输出的coco格式数据集路径
images_path = os.path.join(dataset_path, "images")
labels_path = os.path.join(dataset_path, "labels")

# 类别映射
categories = [
    {"id": 1, "name": "car"},
    {"id": 2, "name": "truck"},
    {"id": 3, "name": "bus"}
    # 添加更多类别
]


# YOLO格式转COCO格式的函数
def convert_yolo_to_coco(x_center, y_center, width, height, img_width, img_height):
    x_min = (x_center - width / 2) * img_width
    y_min = (y_center - height / 2) * img_height
    width = width * img_width
    height = height * img_height
    return [x_min, y_min, width, height]


# 初始化COCO数据结构
def init_coco_format():
    return {
        "images": [],
        "annotations": [],
        "categories": categories
    }


# 处理每个数据集分区
# 可根据你的数据集,是否有test分区,修改代码。有的话修改如下:
# for split in ['train',  'val', 'test']
for split in ['train',  'val']:
    coco_format = init_coco_format()
    annotation_id = 0

    for img_name in os.listdir(os.path.join(images_path, split)):
        if img_name.lower().endswith(('.png', '.jpg', '.jpeg')):
            img_path = os.path.join(images_path, split, img_name)
            label_path = os.path.join(labels_path, split, img_name.replace("jpg", "txt"))

            img = Image.open(img_path)
            img_width, img_height = img.size
            image_info = {
                "file_name": img_name,
                "id": len(coco_format["images"]) + 1,
                "width": img_width,
                "height": img_height
            }
            coco_format["images"].append(image_info)

            if os.path.exists(label_path):
                with open(label_path, "r") as file:
                    for line in tqdm(file,desc="转化中:",):
                        category_id, x_center, y_center, width, height = map(float, line.split())
                        bbox = convert_yolo_to_coco(x_center, y_center, width, height, img_width, img_height)
                        annotation = {
                            "id": annotation_id,
                            "image_id": image_info["id"],
                            # 根据你的数据集修改category_id是否需要减1或者加1
                            "category_id": int(category_id),
                            "bbox": bbox,
                            "area": bbox[2] * bbox[3],
                            "iscrowd": 0
                        }
                        coco_format["annotations"].append(annotation)
                        annotation_id += 1

    # 为每个分区保存JSON文件
    with open(os.path.join(output_dir, f"{split}_coco_format.json"), "w") as json_file:
        json.dump(coco_format, json_file, indent=4)

### 如何使用 Ultralytics 库进行目标检测和 YOLO 模型训练 #### 安装依赖项 为了能够顺利运行 Ultralytics 提供的目标检测工具,需先确保已安装必要的软件包。通常情况下,在 Linux 或 Windows 上可以通过 pip 工具来完成这些操作。 ```bash pip install ultralytics ``` 此命令会自动下载并配置好所有必需的组件[^3]。 #### 准备数据集 对于任何机器学习任务来说,准备合适的数据集都是至关重要的一步。针对目标检测问题,一般需要收集带有标注框的对象图片集合,并按照特定格式整理成文件夹结构以便后续处理程序读取。具体到 YOLO 系列算法,则推荐采用 COCO 数据集标准或是自定义类似的布局方式[^1]。 #### 训练模型 一旦完成了前期准备工作之后就可以着手于实际的训练过程了。借助于 SwanLab 平台的帮助,整个流程变得更加直观易懂——不仅支持在线编辑超参数设定,还能实时监控各项指标变化趋势图,从而帮助使用者更好地理解当前进度以及调整策略方向。 下面是一段简单的 Python 脚本用于启动一次完整的训练周期: ```python from ultralytics import YOLO model = YOLO('yolov8n.yaml') # 创建新的 nano 版本 yolo v8 模型实例 results = model.train(data='path/to/dataset', epochs=100, imgsz=640) ``` 这段代码片段展示了怎样加载预定义好的网络架构描述文件(如 `yolov8n.yaml`),接着指定输入数据源路径以及其他一些基本选项后调用 `.train()` 方法正式开启迭代优化环节[^2]。 #### 进行预测 经过充分的学习积累过后,最终得到的理想化权重参数便可以直接应用于新样本上的推断工作中去。此时只需简单修改几行脚本即可实现高效准确的结果输出功能: ```python predictions = model.predict(source='image.jpg') for pred in predictions: boxes = pred.boxes.cpu().numpy() print(boxes) ``` 这里演示的是从单张静态图像中提取感兴趣区域边界坐标的过程;当然也完全可以扩展至视频流场景下连续帧间的动态监测任务当中[^4]。 #### 验证效果 最后但同样重要的一环就是评估所构建系统的整体表现水平。这往往涉及到多个方面考量因素综合评判,比如精确度(Precision)、召回率(Recall)等统计学概念的应用。幸运的是,Ultralytics 自带了一套完善的评测机制可供开发者随时调用来获取详尽报告分析图表等等有用信息辅助决策制定工作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值