批量将xml文件转txt文件

import os
import xml.etree.ElementTree as ET

import os
import xml.etree.ElementTree as ET

def convert_xml_to_yolov5_label(xml_file, txt_file):
  tree = ET.parse(xml_file)
  root = tree.getroot()

  with open(txt_file, 'w') as f:
    for obj in root.findall('outputs/object/item'):
      class_name = obj.find('name').text
      bbox = obj.find('bndbox')
      x_min = float(bbox.find('xmin').text)
      y_min = float(bbox.find('ymin').text)
      x_max = float(bbox.find('xmax').text)
      y_max = float(bbox.find('ymax').text)

      width = x_max - x_min
      height = y_max - y_min
      x_center = x_min + width / 2
      y_center = y_min + height / 2

      # 将坐标归一化到0-1之间
      width /= float(root.find('size/width').text)
      height /= float(root.find('size/height').text)
      x_center /= float(root.find('size/width').text)
      y_center /= float(root.find('size/height').text)

      f.write(f"{class_name} {x_center} {y_center} {width} {height}\n")

def batch_convert_xml_to_yolov5_label(xml_folder, txt_folder):
  if not os.path.exists(txt_folder):
    os.makedirs(txt_folder)

  for file in os.listdir(xml_folder):
    if file.endswith('.xml'):
      xml_file = os.path.join(xml_folder, file)
      txt_file = os.path.join(txt_folder, file.replace('.xml', '.txt'))
      convert_xml_to_yolov5_label(xml_file, txt_file)

# 示例用法
xml_folder = r'C:\Users\1\Desktop\images\labelsxml'
txt_folder = r'C:\Users\1\Desktop\images\labels'
batch_convert_xml_to_yolov5_label(xml_folder, txt_folder)

猜你喜欢

转载自blog.csdn.net/qq_62238325/article/details/134533186
今日推荐