【目标检测】COCO格式数据集转换为YOLO格式

COCO2YOLO, 修改category_mapping:

import json
import os

def coco_to_yolo(coco_annotation_file, output_dir):
    # Load COCO annotations
    with open(coco_annotation_file, 'r') as f:
        coco_data = json.load(f)

    # Create a dictionary to map category_id to class_id
    # Reorder categories to match the desired YOLO indices
    category_mapping = {
        1: 0,  # class 1
        2: 1,  # class 2
        3: 2   # class 3
    }
    
    # Ensure output directory exists
    os.makedirs(output_dir, exist_ok=True)
    
    # Iterate through images
    for img in coco_data['images']:
        img_id = img['id']
        img_width = img['width']
        img_height = img['height']
        annotations = [ann for ann in coco_data['annotations'] if ann['image_id'] == img_id]
        
        # Prepare the YOLO annotation content
        yolo_annotations = []
        for ann in annotations:
            x, y, w, h = ann['bbox']
            x_center = (x + w / 2) / img_width
            y_center = (y + h / 2) / img_height
            w = w / img_width
            h = h / img_height
            category_id = ann['category_id']
            class_id = category_mapping[category_id]
            yolo_annotations.append(f"{class_id} {x_center} {y_center} {w} {h}")
        
        # Save YOLO annotations to a file
        output_file = os.path.join(output_dir, f"{img['file_name'].split('.')[0]}.txt")
        with open(output_file, 'w') as f:
            f.write('\n'.join(yolo_annotations))

# Usage example
coco_annotation_file = '/data/instances_val2017.json'
output_dir = '/data/yolo_annotations'
coco_to_yolo(coco_annotation_file, output_dir)

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值