Python 生成VOC格式的标签

常用目标检测模型基本都是读取的PASCAL VOC格式的标签,下面代码用于生成VOC格式的代码,根据需要修改即可:

from lxml import etree, objectify

def gen_txt(filename, h, w, c):
    E = objectify.ElementMaker(annotate=False)
    anno_tree = E.annotation(
        E.folder('VOC_OPEN_IMAGE'),
        E.filename(filename),
        E.source(
            E.database('The VOC2007 Database'),
            E.annotation('PASCAL VOC2007'),
            E.image('flickr'),
            E.flickrid("341012865")
        ),
        E.size(
            E.width(w),
            E.height(h),
            E.depth(c)
        ),
        E.segmented(0),
        E.object(
            E.name('1'),
            E.pose('left'),
            E.truncated('1'),
            E.difficult('0'),
            E.bndbox(
                E.xmin('0'),
                E.ymin('0'),
                E.xmax('0'),
                E.ymax('0')
            )
        ),
    )
    etree.ElementTree(anno_tree).write('ann/'+filename[:-4]+".xml", pretty_print=True)
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个将COCO标签转化为VOC标签Python代码例: ```python import json from xml.etree.ElementTree import Element, SubElement, tostring from xml.dom.minidom import parseString def coco2voc(coco_path, voc_path): with open(coco_path, 'r') as f: coco_data = json.load(f) voc_root = Element('annotation') # 添加文件名 filename = SubElement(voc_root, 'filename') filename.text = coco_data['image']['file_name'] # 添加图像尺寸 size = SubElement(voc_root, 'size') width = SubElement(size, 'width') width.text = str(coco_data['image']['width']) height = SubElement(size, 'height') height.text = str(coco_data['image']['height']) depth = SubElement(size, 'depth') depth.text = '3' # 假设是RGB图像 # 添加目标边界框 for ann in coco_data['annotations']: obj = SubElement(voc_root, 'object') name = SubElement(obj, 'name') name.text = coco_data['categories'][ann['category_id'] - 1]['name'] bbox = ann['bbox'] xmin = SubElement(obj, 'xmin') xmin.text = str(bbox[0]) ymin = SubElement(obj, 'ymin') ymin.text = str(bbox[1]) xmax = SubElement(obj, 'xmax') xmax.text = str(bbox[0] + bbox[2]) ymax = SubElement(obj, 'ymax') ymax.text = str(bbox[1] + bbox[3]) # 将XML转换为字符串并保存到文件 xml_str = parseString(tostring(voc_root)).toprettyxml(indent=' ') with open(voc_path, 'w') as f: f.write(xml_str) # 示例用法 coco_path = 'path/to/coco.json' voc_path = 'path/to/voc.xml' coco2voc(coco_path, voc_path) ``` 请将`coco_path`修改为你的COCO标签文件的路径,将`voc_path`修改为你想要保存VOC标签的路径。运行代码后,将生成一个符合VOC标签格式的XML文件

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值