【目标检测】将COCO数据集标注转换为VOC格式

该博客介绍了一个Python脚本,用于将COCO格式的图像注解转换为PASCALVOC XML格式。脚本使用了`pycocotools`和`pascal_voc_writer`库,通过解析COCO注解文件,创建PASCALVOC的XML文件,便于在PASCALVOC工具中使用这些标注。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装库:

pip install pascal_voc_writer

运行指令:

python coco2voc.py --ann_file <path to annotations file> --output_dir <path to output directory>

代码:

from pycocotools.coco import COCO
from pascal_voc_writer import Writer
import argparse
import os

def coco2voc(ann_file, output_dir):
    coco = COCO(ann_file)
    cats = coco.loadCats(coco.getCatIds())
    cat_idx = {}
    for c in cats:
        cat_idx[c['id']] = c['name']
    for img in coco.imgs:
        catIds = coco.getCatIds()
        annIds = coco.getAnnIds(imgIds=[img], catIds=catIds)
        if len(annIds) > 0:
            img_fname = coco.imgs[img]['file_name']
            image_fname_ls = img_fname.split('.')
            image_fname_ls[-1] = 'xml'
            label_fname = '.'.join(image_fname_ls)
            writer = Writer(img_fname, coco.imgs[img]['width'], coco.imgs[img]['height'])
            anns = coco.loadAnns(annIds)
            for a in anns:
                bbox = a['bbox']
                bbox = [bbox[0], bbox[1], bbox[2] + bbox[0], bbox[3] + bbox[1]]
                bbox = [str(b) for b in bbox]
                catname = cat_idx[a['category_id']]
                writer.addObject(catname, bbox[0], bbox[1], bbox[2], bbox[3])
                writer.save(output_dir+'/'+label_fname)


parser = argparse.ArgumentParser(description='Convert COCO annotations to PASCAL VOC XML annotations')
parser.add_argument('--ann_file',help='Path to annotations file')
parser.add_argument('--output_dir',help='Path to output directory where annotations are to be stored')
args = parser.parse_args()
try:
    os.mkdir(args.output_dir)
except FileExistsError:
    pass

coco2voc(ann_file=args.ann_file, output_dir=args.output_dir)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值