voc转YOLO格式

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将VOC格式换为YOLO格式,可以参考以下步骤: 1. 首先,需要解析VOC格式的XML文件,获取图像的宽度、高度和目标的位置信息。可以使用Python中的ElementTree库来实现XML文件的解析。 2. 接下来,需要根据VOC格式的目标位置信息计算出目标的中心坐标、宽度和高度。YOLO格式要求目标的位置信息是相对于图像宽度和高度的百分比。 3. 根据计算出的目标位置信息,将其换为YOLO格式的标注。YOLO格式的标注通常是一个文本文件,每一行代表一个目标,包括目标的类别和位置信息。 4. 最后,将换后的YOLO格式的标注文件与对应的图像一起用于训练深度学习网络。 以上是将VOC格式换为YOLO格式的一般步骤。具体实现的代码可以参考引用中提供的代码。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [YOLO格式换成VOC格式](https://download.csdn.net/download/weixin_38342596/10605709)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [将VOC格式标注文件换为Yolo格式](https://blog.csdn.net/qq_40641713/article/details/127078704)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值