Python实现遍历文件夹下xml文件转化为yolo格式的txt文件

本文介绍如何使用Python编程将一个文件夹中的所有XML文件转换为Yolo格式的TXT文件,适用于计算机视觉领域的目标检测数据预处理。
摘要由CSDN通过智能技术生成
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join

classes = ['person', 'forklift'] 


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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个可以实现上述功能的 Python 脚本。需要注意的是,该脚本假设 XML 文件格式和上一个问题中提供的例子一致。 ```python import os import xml.etree.ElementTree as ET # 根据 XML 文件解析图像信息 def parse_xml(xml_file): tree = ET.parse(xml_file) root = tree.getroot() # 获取图像的尺寸 size = root.find('size') width = int(size.find('width').text) height = int(size.find('height').text) # 获取每个物体的位置信息 boxes = [] for obj in root.findall('object'): name = obj.find('name').text 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) boxes.append((xmin, ymin, xmax, ymax, name)) return width, height, boxes # 将图像信息转换为 YOLO 格式的字符串 def convert_to_yolo(width, height, box): x_center = (box[0] + box[2]) / 2.0 / width y_center = (box[1] + box[3]) / 2.0 / height box_width = (box[2] - box[0]) / width box_height = (box[3] - box[1]) / height return f"{box[4]} {x_center:.6f} {y_center:.6f} {box_width:.6f} {box_height:.6f}" # 遍当前文件夹中的所有 XML 文件 for xml_file in os.listdir(): if xml_file.endswith('.xml'): # 解析 XML 文件 width, height, boxes = parse_xml(xml_file) # 将图像信息转换为 YOLO 格式 yolo_boxes = [convert_to_yolo(width, height, box) for box in boxes] # 将 YOLO 格式的图像信息保存到 TXT 文件中 with open(os.path.splitext(xml_file)[0] + '.txt', 'w') as f: f.write('\n'.join(yolo_boxes)) ``` 该脚本首先遍当前文件夹中的所有 XML 文件,并解析其中的图像信息和物体位置信息。然后,将解析得到的图像信息转换为 YOLO 格式的字符串,并将其保存到同名的 TXT 文件中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值