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

相关推荐
小玮看世界6 小时前
从“画图”到“Mermaid”:AI语义理解与架构绘制的演进之路
人工智能·深度学习·计算机视觉
安_6 小时前
如何构建和使用向量索引?HNSW 和 IVF 有什么区别?
python·ai
向哆哆6 小时前
无人机灾害场景人体目标检测数据集分享(适用于YOLO系列深度学习分类检测任务)
yolo·目标检测·无人机
counting money7 小时前
Java IO流详解:从InputStream到文件操作实战
java·开发语言·python
坚持学习前端日记7 小时前
Python SQLAlchemy ORM 从0到1精通实战手册(基础到复杂高阶)
数据库·python·oracle
北斗落凡尘8 小时前
LangGraph 入门实战(11)--输出模式
后端·python·langchain
雪碧聊技术8 小时前
安装Python(保姆级教程)
python·版本更新·python下载
++==8 小时前
JSON和Python的 四种核心容器
python·json
问天_观心9 小时前
零基础在windows环境下的WSL使用llamafactory(二)
人工智能·神经网络·语言模型·github·模型蒸馏
Eric.4610 小时前
AI漫剧量产Prompt参数实操手册:Stable Diffusion+ComfyUI+OpenClaw通用复制即用配置
人工智能·深度学习·stable diffusion·prompt·ai漫剧