当前位置: 首页 > news >正文

ultralytics框架计算大中小目标检测精度

先前在跑DETR类目标检测算法时,由于其默认使用的是COCO数据集,所以输出结果中包含不同尺度的检测精度,即大、中、小目标。
而现在博主在使用ultralytics时,发现其并没有这个指标效果,但在先前的实验中,博主发现DETR中计算这些指标使用的是pycocotools这个工具包,那么我们就可以将检测结果和标注数据采用这个工具进行计算。话不多说,我们开整。

YOLO数据集转COCO

首先,我们要做的是将YOLO格式的数据集转换为COCO格式的数据集,代码如下:
这里需要注意的是,COCO的类别是从1开始的,而YOLO的类别则从0开始,那么我们就需要category_id = int(parts[0])+1

import os
import json
from PIL import Imagedef yolo_to_coco(yolo_dir, img_dir, output_file, categories):"""将YOLO格式的标注转换为COCO格式。:param yolo_dir: 包含YOLO标注txt文件的目录路径。:param img_dir: 包含对应图像的目录路径。:param output_file: 输出的COCO格式JSON文件路径。:param categories: 类别列表,如[{"id": 0, "name": "cat"}, {"id": 1, "name": "dog"}]"""images = []annotations = []image_id = 0annotation_id = 0for txt_file in os.listdir(yolo_dir):if not txt_file.endswith('.txt'):continue# 获取对应的图像文件名img_file = os.path.splitext(txt_file)[0] + '.jpg'image_id = os.path.splitext(txt_file)[0]img_path = os.path.join(img_dir, img_file)if not os.path.exists(img_path):print(f"找不到对应的图像文件: {img_file}")continue# 获取图像尺寸with Image.open(img_path) as img:width, height = img.size# 图像信息image_info = {"id": image_id,"file_name": img_file,"width": width,"height": height}images.append(image_info)# 解析YOLO标注with open(os.path.join(yolo_dir, txt_file), 'r') as f:lines = f.readlines()for line in lines:parts = line.strip().split()category_id = int(parts[0])+1x_center = float(parts[1])y_center = float(parts[2])bbox_width = float(parts[3])bbox_height = float(parts[4])# 计算边界框的绝对坐标abs_x = x_center * widthabs_y = y_center * heightabs_w = bbox_width * widthabs_h = bbox_height * heightannotation = {"id": annotation_id,"image_id": image_id,"category_id": category_id,"bbox": [abs_x - abs_w / 2, abs_y - abs_h / 2, abs_w, abs_h],"area": abs_w * abs_h,"iscrowd": 0}annotations.append(annotation)annotation_id += 1coco_format_json = {"images": images,"annotations": annotations,"categories": categories}with open(output_file, 'w') as f:json.dump(coco_format_json, f)
# 示例调用
categories = [{"id": 0, "name": "balloon"}, {"id": 1, "name": "kite"},{"id": 2, "name": "nest"},{"id": 3, "name": "trash"}]  # 根据实际情况修改
yolo_to_coco("D:/project_mine/detection/datasets/others/labels/val", "D:/project_mine/detection/datasets/others/images/val", "coco_annotations.json", categories)

转换出的数据如下:

在这里插入图片描述

推理结果保存为json

第二步,我们需要在推理时,将结果保存为json格式,这个ultralytics框架中已经帮我们实现好了:只需要在参数中加上save_json=True即可

from ultralytics import RTDETR
# 加载模型
model = RTDETR("weights/best.pt")# 开始验证
validation_results = model.val(data="others.yaml",imgsz=640,batch=16,save_json=True,conf=0.25,iou=0.6,device="0"
)
print(validation_results.results_dict)

计算多尺度检测结果

如今,我们将数据均转换为COCO格式了,那么就可以采用pycocotools工具包计算了,代码如下:

from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
# 加载标注和预测
annFile = 'coco_annotations.json'
resFile = 'predictions.json'
cocoGt = COCO(annFile)
cocoDt = cocoGt.loadRes(resFile)# 先评估整体性能 (area='all')
cocoEval = COCOeval(cocoGt, cocoDt, 'bbox')
cocoEval.evaluate()
cocoEval.accumulate()
cocoEval.summarize()

结果如下:

在这里插入图片描述

码字不易,给个赞呗!

相关文章:

  • K8s进阶之一文搞懂PV,PVC及SC
  • 技术文章: PCB基板介电常数的温度系数
  • [Java实战]Spring Boot 整合 Redis(十八)
  • 使用 Watt toolkit 加速 git clone
  • git和gdb
  • PDFMathTranslate:科学 PDF 文件翻译及双语对照工具
  • HDLBIT-更多Verilog功能(More Verilog Features)
  • 【MCP】魔搭社区MCP服务(高德地图、everything文件搜索)
  • C++中类中const知识应用详解
  • 质控脚本来喽
  • 工具篇-如何在Github Copilot中使用MCP服务?
  • Linux 服务器用 SSH 拉取多个 Git 工程
  • python打卡day22
  • 修改网页标签处文字
  • tar -zxvf jdk-8u212-linux-x64.tar.gz -C /opt/module/这个代码的解释
  • MyBatis 中 ${} 与 #{} 的区别与 SQL 注入防范教程
  • 安装Python和配置开发环境
  • PHP 连接和使用 Kafka 的指南
  • Spring AI 与 Hugging Face 深度集成:打造高效文本生成应用
  • 我们来学mysql -- 安装8.4版本
  • 回望乡土:对媒介化社会的反思
  • 重庆三峡学院回应“中标价85万设备网购300元”:已终止采购
  • 人民日报读者点题·共同关注:今天我们为什么还需要图书馆?
  • 国家统计局:4月份居民消费价格同比下降0.1%
  • 三大猪企4月生猪销量同比均增长,销售均价同比小幅下降
  • 中方是否认同俄方关于新纳粹主义观点?外交部:联大曾多次通过相关决议