xml转txt,适应各种图片格式,如jpg,png,jpeg,PNG,JPEG等

xml转txt,适应各种图片格式,如jpg,png,jpeg,PNG,JPEG等

bash 复制代码
import xml.etree.ElementTree as ET
import os
import cv2
import numpy as np
import glob

classes = []


def convert(size, box):
    dw = 1. / (size[0])
    dh = 1. / (size[1])
    x = (box[0] + box[1]) / 2.0 - 1
    y = (box[2] + box[3]) / 2.0 - 1
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    return (x, y, w, h)


def get_image_file(imgpath, imgname_without_ext):
    # 匹配多种图像格式
    extensions = ['jpg', 'jpeg', 'png', 'JPG', 'JPEG', 'PNG']
    for ext in extensions:
        imgfile = os.path.join(imgpath, f'{imgname_without_ext}.{ext}')
        if os.path.exists(imgfile):
            return imgfile
    return None


def convert_annotation(xmlpath, xmlname):
    with open(xmlpath, "r", encoding='utf-8') as in_file:
        txtname = xmlname[:-4] + '.txt'
        txtfile = os.path.join(txtpath, txtname)

        tree = ET.parse(in_file)
        root = tree.getroot()
        imgfile = get_image_file(imgpath, xmlname[:-4])
        if imgfile is None:
            print(f'No matching image file for {xmlname}')
            return

        img = cv2.imdecode(np.fromfile(imgfile, np.uint8), cv2.IMREAD_COLOR)
        h, w = img.shape[:2]
        res = []
        for obj in root.iter('object'):
            cls = obj.find('name').text
            if cls not in classes:
                classes.append(cls)
            cls_id = classes.index(cls)
            xmlbox = obj.find('bndbox')
            b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
                 float(xmlbox.find('ymax').text))
            bb = convert((w, h), b)
            res.append(str(cls_id) + " " + " ".join([str(a) for a in bb]))

        # 即使 res 为空也要创建 .txt 文件
        with open(txtfile, 'w+') as f:
            f.write('\n'.join(res))


if __name__ == "__main__":
    imgpath = r"VOCdevkit\JPEGImages"  #图片文件夹路径
    xmlpath = r"Annotations"           #xml格式文件夹
    txtpath = r"VOCdevkit\txt"         #txt格式文件夹

    if not os.path.exists(txtpath):
        os.makedirs(txtpath, exist_ok=True)

    list = os.listdir(xmlpath)
    error_file_list = []
    for i in range(0, len(list)):
        try:
            path = os.path.join(xmlpath, list[i])
            if ('.xml' in path):
                convert_annotation(path, list[i])
                print(f'file {list[i]} convert success.')
            else:
                print(f'file {list[i]} is not xml format.')
        except Exception as e:
            print(f'file {list[i]} convert error.')
            print(f'error message:\n{e}')
            error_file_list.append(list[i])
    print(f'this file convert failure\n{error_file_list}')
    print(f'Dataset Classes:{classes}')

注意需要改的的地方如下:
改为自己相应的路径

bash 复制代码
    imgpath = r"VOCdevkit\JPEGImages"  #图片文件夹路径
    xmlpath = r"Annotations"           #xml格式文件夹
    txtpath = r"VOCdevkit\txt"         #txt格式文件夹
相关推荐
unityのkiven9 分钟前
C++中的虚表和虚表指针的原理和示例
开发语言·c++
炒空心菜菜13 分钟前
MapReduce 实现 WordCount
java·开发语言·ide·后端·spark·eclipse·mapreduce
(・Д・)ノ15 分钟前
python打卡day27
开发语言·python
芯眼39 分钟前
STM32启动文件详解(重点)
java·开发语言·c++·stm32·单片机·mybatis
小oo呆1 小时前
【学习心得】Jupyter 如何在conda的base环境中其他虚拟环境内核
python·jupyter·conda
愚润求学1 小时前
【Linux】动静态库链接原理
linux·运维·服务器·开发语言·笔记
呦呦彬1 小时前
【问题排查】easyexcel日志打印Empty row!
java·开发语言·log4j
Tummer83631 小时前
C#+WPF+prism+materialdesign创建工具主界面框架
开发语言·c#·wpf
九章云极AladdinEdu2 小时前
GPU与NPU异构计算任务划分算法研究:基于强化学习的Transformer负载均衡实践
java·开发语言·人工智能·深度学习·测试工具·负载均衡·transformer
好吃的肘子2 小时前
MongoDB 应用实战
大数据·开发语言·数据库·算法·mongodb·全文检索