关键点检测数据集yolo格式转coco格式
时间: 2025-07-09 14:47:44 浏览: 16
### 将YOLO格式的关键点检测数据集转换为COCO格式
#### 数据结构对比
YOLO格式通常用于目标检测,其标注文件中的每一行表示一个边界框及其类别标签。对于关键点检测任务,在YOLO格式下,除了边界框外还会附加若干个关键点坐标。而COCO格式则更加复杂和灵活,不仅支持多类别的对象定义,还能够描述图像中多个实例的位置、姿态以及其他属性。
#### 转换过程概述
为了实现从YOLO到COCO格式的转换,主要工作集中在解析原始YOLO标注文件并构建符合COCO JSON标准的新文档。这涉及到几个方面的工作:
- **读取YOLO标注**:提取每张图片对应的边界框信息及关联的关键点位置。
- **创建JSON模板**:按照COCO API的要求准备基本框架,包括images, annotations 和 categories三个部分。
- **映射关系建立**:确保YOLO中的分类ID能正确对应至COCO里的category_id字段;同时处理好keypoints数组与image ID之间的绑定。
- **保存结果**:最终生成完整的COCO风格json文件[^1]。
#### 实现方法
下面给出一段Python脚本作为参考,该脚本能帮助完成上述提到的任务之一——即把单个YOLO txt文件的内容转化为适合加入到总的annotations列表当中的字典形式。
```python
import json
from pathlib import Path
def yolo_to_coco(yolo_file_path: str, image_info: dict, category_id_map: dict):
"""
Convert YOLO format keypoints to COCO annotation structure.
Args:
yolo_file_path (str): Path of the .txt file containing YOLO style labels and keypoints.
image_info (dict): Dictionary holding information about current image like id, width, height etc.
category_id_map (dict): Mapping from original class ids used in YOLO files to those expected by COCO dataset.
Returns:
list[dict]: List of dictionaries representing individual object instances with their respective keypoint data formatted according to COCO specifications.
"""
coco_anns = []
img_width = int(image_info['width'])
img_height = int(image_info['height'])
with open(yolo_file_path) as f:
lines = f.readlines()
for line_num, line in enumerate(lines):
parts = line.strip().split()
cls_idx_yolo = int(parts[0])
bbox_x_center_norm = float(parts[1]) * img_width
bbox_y_center_norm = float(parts[2]) * img_height
bbox_w_norm = float(parts[3]) * img_width
bbox_h_norm = float(parts[4]) * img_height
keypoints = [] # Initialize empty list for storing all keypoints per instance
num_keypoints_visible = 0 # Counter for visible keypoints within bounding box
# Assuming there are N pairs after first five elements which represent keypoints' coordinates(x,y,v)
n_kpts = len(parts)-5
if n_kpts % 3 != 0:
raise ValueError(f"Incorrect number of values found on line {line_num}.")
kpt_pairs = zip(*([iter(parts[5:])]*3))
for idx, (kpx_str, kpy_str, visiblity_flag) in enumerate(kpt_pairs):
try:
kp_x = round(float(kpx_str)*img_width)
kp_y = round(float(kpy_str)*img_height)
v = min(int(visiblity_flag), 2) # Visibility flag should be either 0 or 1 or 2
keypoints.extend([kp_x, kp_y, v])
if v > 0:
num_keypoints_visible += 1
except Exception as e:
print(e)
ann_dict = {
"id": line_num,
"image_id": image_info["id"],
"category_id": category_id_map.get(cls_idx_yolo),
"bbox":[round(bbox_x_center_norm-bbox_w_norm/2.),
round(bbox_y_center_norm-bbox_h_norm/2.),
bbox_w_norm,bbox_h_norm],
"area": bbox_w_norm*bbox_h_norm,
"iscrowd": 0,
"num_keypoints": num_keypoints_visible,
"keypoints": keypoints
}
coco_anns.append(ann_dict)
return coco_anns
```
此函数接受一个指向YOLO格式文本文件路径`yolo_file_path`,一张特定图片的信息字典`image_info`(至少包含宽度、高度和唯一标识符),以及原生类别索引到新类别编号间的映射表`category_id_map`。它会返回一系列遵循COCO规范的对象实例记录组成的列表。
需要注意的是,这段代码假设输入的YOLO文件已经包含了必要的关键点信息,并且这些信息是以三元组的形式存在的(x坐标比例、y坐标比例、可见性标志)。如果实际情况有所不同,则可能需要调整相应的逻辑来适应具体需求[^2]。
阅读全文
相关推荐


















