python批量处理数据脚本——目标检测数据标签的labelme格式转VOC格式

python 复制代码
import os
import json
from xml.etree.ElementTree import Element, SubElement, tostring, ElementTree

def labelme_to_voc(json_path, output_dir):
    with open(json_path, 'r') as f:
        labelme_data = json.load(f)

    img_filename = labelme_data['imagePath']
    img_width = labelme_data['imageWidth']
    img_height = labelme_data['imageHeight']
    shapes = labelme_data['shapes']

    # Create VOC XML structure
    root = Element('annotation')

    folder = SubElement(root, 'folder')
    folder.text = 'VOC'  # Customize folder name as needed

    filename = SubElement(root, 'filename')
    filename.text = os.path.basename(img_filename)

    size = SubElement(root, 'size')
    width = SubElement(size, 'width')
    width.text = str(img_width)
    height = SubElement(size, 'height')
    height.text = str(img_height)
    depth = SubElement(size, 'depth')
    depth.text = '3'  # Assuming RGB images

    for shape in shapes:
        label = shape['label']
        points = shape['points']

        object_elem = SubElement(root, 'object')
        name = SubElement(object_elem, 'name')
        name.text = label

        pose = SubElement(object_elem, 'pose')
        pose.text = 'Unspecified'

        truncated = SubElement(object_elem, 'truncated')
        truncated.text = '0'

        difficult = SubElement(object_elem, 'difficult')
        difficult.text = '0'

        bndbox = SubElement(object_elem, 'bndbox')
        xmin = SubElement(bndbox, 'xmin')
        xmin.text = str(min(points[0][0], points[1][0]))
        ymin = SubElement(bndbox, 'ymin')
        ymin.text = str(min(points[0][1], points[1][1]))
        xmax = SubElement(bndbox, 'xmax')
        xmax.text = str(max(points[0][0], points[1][0]))
        ymax = SubElement(bndbox, 'ymax')
        ymax.text = str(max(points[0][1], points[1][1]))

    # Save the VOC XML file
    xml_path = os.path.join(output_dir, os.path.splitext(os.path.basename(img_filename))[0] + '.xml')
    tree = ElementTree(root)
    tree.write(xml_path)

# Example usage
labelme_json_path = 'path/to/labelme.json'
output_directory = 'path/to/output'
labelme_to_voc(labelme_json_path, output_directory)

这只是一张图片的标签转换,要是一个数据集,则进行listdir遍历目录下的每个json标签即可。

相关推荐
言無咎14 分钟前
从规则引擎到任务规划:AI Agent 重构跨境财税复杂账务处理体系
大数据·人工智能·python·重构
张小凡vip20 分钟前
数据挖掘(十)---python操作Spark常用命令
python·数据挖掘·spark
weixin_3954489121 分钟前
排查流程啊啊啊
人工智能·深度学习·机器学习
U盘失踪了27 分钟前
Reqable 导出响应数据
python
2301_7903009631 分钟前
数据分析与科学计算
jvm·数据库·python
是小蟹呀^44 分钟前
卷积神经网络(CNN):卷积操作
人工智能·神经网络·cnn
程序员小远1 小时前
使用Postman进行一次完整的接口测试
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
Yvonne爱编码1 小时前
JAVA数据结构 DAY1-集合和时空复杂度
java·数据结构·python
DN20201 小时前
AI销售机器人:节日祝福转化率提升30倍
人工智能·python·深度学习·机器学习·机器人·节日
香芋Yu1 小时前
【大模型教程——第二部分:Transformer架构揭秘】第2章:模型家族谱系:从编码器到解码器 (Model Architectures)
深度学习·架构·transformer