在YOLOv8训练时,使用的训练标注格式是txt,但是我却得到了xml格式的图片标注,下面是将xml转换成txt格式的python代码
只需要更改下面的class_id和输入xml目录和输出txt目录就行了
import os
import xml.etree.ElementTree as ET
#这里的class_id改成类别前标,如0 1 2 3...
def convert_to_yolo_format(xml_file, output_txt_file, class_id=3):
tree = ET.parse(xml_file)
root = tree.getroot()
# 获取图像的宽度和高度
width = int(root.find('size/width').text)
height = int(root.find('size/height').text)
# 打开输出的TXT文件
with open(output_txt_file, 'w', encoding='utf-8') as txt_file:
for obj in root.findall('object'):
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
bbox_width = (xmax - xmin) / width
bbox_height = (ymax - ymin) / height
# 写入TXT文件
txt_file.write(f"{class_id} {x_center:.6f} {y_center:.6f} {bbox_width:.6f} {bbox_height:.6f}\n")
#XML文件所在的文件夹目录
input_dir = r'E:/git-project/YOLOV8/ultralytics-main/标记/Rust_xml'
#输出TXT文件的文件夹目录
output_dir = r'E:/git-project/YOLOV8/ultralytics-main/标记/Rust_txt'
# 创建输出目录(如果不存在)
os.makedirs(output_dir, exist_ok=True)
# 遍历目录中的所有XML文件
for filename in os.listdir(input_dir):
if filename.endswith('.xml'):
file_path = os.path.join(input_dir, filename)
# 创建输出TXT文件路径
output_txt = os.path.join(output_dir, filename.replace('.xml', '.txt'))
# 转换为YOLO格式并写入TXT文件
convert_to_yolo_format(file_path, output_txt)
if os.path.exists(output_txt):
print(f"文件已生成: {output_txt}")
else:
print(f"文件生成失败: {output_txt}")