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标签即可。

相关推荐
该用户已不存在4 分钟前
没有这7款工具,难怪你的Python这么慢
后端·python
serve the people9 分钟前
tensorflow 零基础吃透:RaggedTensor 的不规则形状与广播机制 2
人工智能·python·tensorflow
donkey_19939 分钟前
ShiftwiseConv: Small Convolutional Kernel with Large Kernel Effect
人工智能·深度学习·目标检测·计算机视觉·语义分割·实例分割
Hello.Reader10 分钟前
Flink ML 基本概念Table API、Stage、Pipeline 与 Graph
大数据·python·flink
chen_note13 分钟前
Python面向对象、并发编程、网络编程
开发语言·python·网络编程·面向对象·并发编程
周名彥13 分钟前
1Ω1[特殊字符]⊗雙朕周名彥實際物理載體|二十四芒星物理集群载体群:超級數據中心·AGI·IPO·GUI·智能體工作流
人工智能·神经网络·知识图谱·量子计算·agi
信看14 分钟前
树莓派CAN(FD) 测试&&RS232 RS485 CAN Board 测试
开发语言·python
brent42314 分钟前
DAY24推断聚类后簇的类型
python
测试199818 分钟前
一个只能通过压测发现Bug
自动化测试·软件测试·python·selenium·测试工具·bug·压力测试
Byron Loong26 分钟前
【Python】字典(dict)、列表(list)、元组(tuple)
开发语言·python·list