voc转YOLO格式

发布于:2024-08-11 ⋅ 阅读:(162) ⋅ 点赞:(0)

voc转YOLO格式

import xml.etree.ElementTree as ET
import os


def convert(size, box):
    x_center = (box[0] + box[1]) / 2.0
    y_center = (box[2] + box[3]) / 2.0
    x = x_center / size[0]
    y = y_center / size[1]
    w = (box[1] - box[0]) / size[0]
    h = (box[3] - box[2]) / size[1]
    return x, y, w, h


def convert_annotation(xml_files_path, save_txt_files_path, classes):
    xml_files = os.listdir(xml_files_path)
    print("XML files found:", xml_files)

    for xml_name in xml_files:
        xml_file = os.path.join(xml_files_path, xml_name)
        out_txt_path = os.path.join(save_txt_files_path, xml_name.split('.')[0] + '.txt')

        # 确保输出目录存在
        os.makedirs(os.path.dirname(out_txt_path), exist_ok=True)

        try:
            tree = ET.parse(xml_file)
            root = tree.getroot()
            size = root.find('size')
            w = int(size.find('width').text)
            h = int(size.find('height').text)

            with open(out_txt_path, 'w') as out_txt_f:
                for obj in root.iter('object'):
                    difficult = obj.find('difficult').text
                    cls = obj.find('name').text
                    if cls not in classes or int(difficult) == 1:
                        continue
                    cls_id = classes.index(cls)
                    xmlbox = obj.find('bndbox')
                    b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text),
                         float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))
                    bb = convert((w, h), b)
                    out_txt_f.write(f"{cls_id} " + " ".join([str(a) for a in bb]) + '\n')

            print(f"Converted {xml_name} to {out_txt_path}")

        except ET.ParseError as e:
            print(f"Could not parse {xml_name}: {e}")
        except Exception as e:
            print(f"Error processing {xml_name}: {e}")


if __name__ == "__main__":
    # 需要转换的类别,需要一一对应
    classes1 = ['crazing', 'inclusion', 'patches', 'pitted_surface', 'rolled-in_scale', 'scratches']
    # VOC格式的XML标签文件路径
    xml_files1 = r'D:\Academic\Deep Learning\yolov10-main\data\NEU\NEU-DET (1)\ANNOTATIONS'
    # 转化为YOLO格式的TXT标签文件存储路径
    save_txt_files1 = r'D:\Academic\Deep Learning\yolov10-main\data\NEU\NEU-DET (1)\labels'

    # 创建保存目录(如果不存在)
    if not os.path.exists(save_txt_files1):
        os.makedirs(save_txt_files1)

    convert_annotation(xml_files1, save_txt_files1, classes1)