import xml.etree.ElementTree as ET
import xml.etree.ElementTree as ET
def convert_xml_to_yolov5_label(xml_file, txt_file):
tree = ET.parse(xml_file)
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)
x_center = x_min + width / 2
y_center = y_min + height / 2
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):
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)