python解析xml文件,提取信息并保存为txt格式

该代码段使用Python的xml.etree.ElementTree库解析XML文件,特别是针对目标检测中的bbox信息。它提取物体标签、bbox坐标,并将这些坐标从xyxy格式转换为xywh格式,适应于机器学习模型的输入需求。示例XML文件包含多个对象的边界框信息。
摘要由CSDN通过智能技术生成

python解析xml文件,以目标检测的bbox为例,提取物体框的label, xmin, ymin (box的左上点); xmax, ymax (box的右上点), 并将其转化为 class center_x center_y box_width box_height

关键

  • xml.etree.ElementTree as ET
  • tree.getroot()
  • root.find()
  • root.find().text
  • root.iter()
import os
from glob import glob
import xml.etree.ElementTree as ET

classes = ['crazing', 'inclusion', 'patches', 'pitted_surface', 'rolled-in_scale', 'scratches']

def xyxytoxywh(x_min, y_min, x_max, y_max, img_w, img_h):
    cx = (x_max + x_min) / 2.
    cy = (y_max + y_min) / 2.
    w = (x_max - x_min)
    h = (y_max - y_min)

    return str(cx / img_w), str(cy / img_h), str(w / img_w), str(h / img_h)

def decode_xml(xml_file, save_dir):
    txt_file = os.path.join(save_dir, os.path.basename(xml_file)[:-3]+"txt")
    with open(txt_file, 'w', encoding='utf-8') as f:
        tree = ET.parse(xml_file)
        root = tree.getroot()
        size = root.find('size')
        img_w = int(size.find('width').text)
        img_h = int(size.find('height').text)

        for obj in root.iter('object'):
            cls = obj.find('name').text
            if cls not in classes:
                print(cls)
                continue

            cls_id = classes.index(cls)
            xmlbox = obj.find('bndbox')
            x_min = (float(xmlbox.find('xmin').text))
            y_min = (float(xmlbox.find('ymin').text))
            x_max = (float(xmlbox.find('xmax').text))
            y_max = (float(xmlbox.find('ymax').text))

            txt = str(cls_id) + ' ' + ' '.join(xyxytoxywh(x_min, y_min, x_max, y_max, img_w, img_h))+'\n'
            f.write(txt)

if __name__ == "__main__":
    dir = "./ANNOTATIONS" # path to load .xml file
    save_dir = "./labels" # path to save .txt file
    os.makedirs(save_dir, exist_ok=True)
    xml_file_list = glob(dir+"/*.xml")
    
    for xml_file in xml_file_list:
        decode_xml(xml_file, save_dir)

一个xml的内容示例

<annotation>
	<folder>cr</folder>
	<filename>crazing_2.jpg</filename>
	<source>
		<database>NEU-DET</database>
	</source>
	<size>
		<width>200</width>
		<height>200</height>
		<depth>1</depth>
	</size>
	<segmented>0</segmented>
	<object>
		<name>crazing</name>
		<pose>Unspecified</pose>
		<truncated>1</truncated>
		<difficult>0</difficult>
		<bndbox>
			<xmin>99</xmin>
			<ymin>120</ymin>
			<xmax>200</xmax>
			<ymax>174</ymax>
		</bndbox>
	</object>
	<object>
		<name>crazing</name>
		<pose>Unspecified</pose>
		<truncated>1</truncated>
		<difficult>0</difficult>
		<bndbox>
			<xmin>8</xmin>
			<ymin>16</ymin>
			<xmax>200</xmax>
			<ymax>111</ymax>
		</bndbox>
	</object>
</annotation>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值