如何将YOLO分割数据集标注转换为COCO格式?
YOLO分割数据集转COCO格式脚本
以下是直接可用的Python脚本,支持将YOLO格式的分割标签(含多边形坐标)完整转换为COCO格式JSON,包含segmentation、bbox、area等核心字段:
import os import json import cv2 import numpy as np # -------------------------- 配置参数 -------------------------- IMAGE_DIR = "path/to/your/images" # 图片文件夹路径 LABEL_DIR = "path/to/your/labels" # YOLO标签文件夹路径 OUTPUT_JSON = "output_coco.json" # 输出COCO格式JSON路径 CATEGORIES = [ # 数据集类别,按YOLO的class_id顺序排列 {"id": 0, "name": "class0", "supercategory": "none"}, {"id": 1, "name": "class1", "supercategory": "none"}, # 按需添加更多类别 ] # ------------------------------------------------------------- def yolo_seg_to_coco(): # 初始化COCO结构 coco_data = { "info": {}, "licenses": [], "categories": CATEGORIES, "images": [], "annotations": [] } image_id = 1 annotation_id = 1 # 遍历所有图片 for img_filename in os.listdir(IMAGE_DIR): if not img_filename.lower().endswith(('.png', '.jpg', '.jpeg')): continue # 获取图片路径和基本信息 img_path = os.path.join(IMAGE_DIR, img_filename) img = cv2.imread(img_path) height, width = img.shape[:2] # 添加图片信息到COCO coco_data["images"].append({ "id": image_id, "file_name": img_filename, "width": width, "height": height, "license": 0, "date_captured": "" }) # 对应标签文件路径 label_filename = os.path.splitext(img_filename)[0] + ".txt" label_path = os.path.join(LABEL_DIR, label_filename) if not os.path.exists(label_path): image_id += 1 continue # 解析YOLO分割标签 with open(label_path, "r") as f: lines = f.readlines() for line in lines: line = line.strip().split() if not line: continue class_id = int(line[0]) # 提取归一化坐标,转换为原始像素坐标 coords = np.array(list(map(float, line[1:]))).reshape(-1, 2) coords[:, 0] *= width coords[:, 1] *= height coords = coords.astype(np.int32).tolist() # 计算bbox(最小外接矩形) x_coords = [p[0] for p in coords] y_coords = [p[1] for p in coords] bbox = [ min(x_coords), min(y_coords), max(x_coords) - min(x_coords), max(y_coords) - min(y_coords) ] # 计算分割区域面积 contour = np.array(coords, dtype=np.int32) area = cv2.contourArea(contour) # 添加标注信息到COCO coco_data["annotations"].append({ "id": annotation_id, "image_id": image_id, "category_id": class_id, "segmentation": [sum(coords, [])], # COCO格式:扁平化坐标列表 "bbox": bbox, "area": area, "iscrowd": 0 }) annotation_id += 1 image_id += 1 # 保存COCO JSON文件 with open(OUTPUT_JSON, "w") as f: json.dump(coco_data, f, indent=4) print(f"转换完成,已保存到 {OUTPUT_JSON}") if __name__ == "__main__": yolo_seg_to_coco()
使用说明
- 修改脚本顶部的
IMAGE_DIR、LABEL_DIR、OUTPUT_JSON为你的实际路径 - 按YOLO标签中的
class_id顺序,完善CATEGORIES列表,确保类别ID和名称对应 - 安装依赖库:
pip install opencv-python numpy - 运行脚本即可生成完整的COCO格式标注文件
注意事项
- YOLO分割标签格式要求:每行格式为
class_id x1 y1 x2 y2 ... xn yn,所有坐标为归一化后的值(相对于图片宽高) - 脚本会自动计算每个分割区域的
bbox和area,无需手动提供 - 支持单多边形分割标注,若你的数据集有多实例或复杂分割(如RLE),可根据需求扩展脚本逻辑
内容的提问来源于stack exchange,提问作者NevMthw
相关产品推荐
相关产品推荐

