import os
import xml.etree.ElementTree as ET
def convert_xml_to_txt(xml_folder, txt_folder):
for root, dirs, files in os.walk(xml_folder):
for file in files:
if file.endswith(".xml"):
xml_path = os.path.join(root, file)
tree = ET.parse(xml_path)
root_elem = tree.getroot()
width = int(root_elem.find("size").find("width").text)
height = int(root_elem.find("size").find("height").text)
txt_file_name = os.path.splitext(file)[0] + ".txt"
txt_path = os.path.join(txt_folder, txt_file_name)
with open(txt_path, "w") as txt_file:
for obj in root_elem.findall("object"):
name = obj.find("name").text
bndbox = obj.find("bndbox")
xmin = int(bndbox.find("xmin").text)
ymin = int(bndbox.find("ymin").text)
xmax = int(bndbox.find("xmax").text)
ymax = int(bndbox.find("ymax").text)
class_id = name
x_center = (xmin + xmax) / (2.0 * width)
y_center = (ymin + ymax) / (2.0 * height)
width_bb = (xmax - xmin) / width
height_bb = (ymax - ymin) / height
txt_file.write(f"{class_id} {x_center} {y_center} {width_bb} {height_bb}\n")
# 定义xml文件夹路径和txt文件夹路径
xml_folder = r"C:\Users\admin\Desktop\TP\TP\helmet\xml"
txt_folder = r"C:\Users\admin\Desktop\TP\TP\helmet\txt"
# 执行转换
convert_xml_to_txt(xml_folder, txt_folder)
xml文件转txt文件
最新推荐文章于 2024-04-24 16:41:08 发布