import os
import xml.etree.ElementTree as ET
def xml_to_txt(xml_path, output_path, class_mapping):
tree = ET.parse(xml_path)
root = tree.getroot()
width = int(root.find('size/width').text)
height = int(root.find('size/height').text)
with open(output_path, 'w') as f:
for obj in root.findall('object'):
class_name = obj.find('name').text
if class_name not in class_mapping:
print(f"Warning: Class '{class_name}' not in class mapping. Skipping...")
continue
class_id = class_mapping[class_name]
xmin = int(obj.find('bndbox/xmin').text)
ymin = int(obj.find('bndbox/ymin').text)
xmax = int(obj.find('bndbox/xmax').text)
ymax = int(obj.find('bndbox/ymax').text)
x_center = (xmin + xmax) / 2.0 / width
y_center = (ymin + ymax) / 2.0 / height
w = (xmax - xmin) / width
h = (ymax - ymin) / height
f.write(f"{class_id} {x_center} {y_center} {w} {h}\n")
# 输入文件夹路径和输出文件夹路径
input_folder = '输入文件夹路径'
output_folder = '输出文件夹路径'
# 类别映射
class_mapping = {'cat': 0, 'dog': 1} # 请根据您的实际情况进行修改,我是猫和狗
# 确保输出文件夹存在
os.makedirs(output_folder, exist_ok=True)
# 遍历所有XML文件并转换为txt格式
for filename in os.listdir(input_folder):
if filename.endswith('.xml'):
xml_path = os.path.join(input_folder, filename)
txt_path = os.path.join(output_folder, os.path.splitext(filename)[0] + '.txt')
xml_to_txt(xml_path, txt_path, class_mapping)
(亲测可行!)将xml文件转换为txt格式(YOLOv5目标检测)
于 2024-02-05 10:24:59 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)