当前位置:   article > 正文

【目标检测】将xml标注文件转换为txt格式,voc标注格式转为yolo的txt格式_caltech数据集xml转换成txt

caltech数据集xml转换成txt

导入模块

import os
import xml.etree.ElementTree as ET
  • 1
  • 2

若提示没有xml模块,则需在终端输入命令 pip lxml 进行安装

坐标转换

size: (w, h)
box: [xmin, ymin, xmax, ymax]
return: [xcenter, ycenter, box_w, box_h]
voc格式中的目标标注为左上角坐标与右下角坐标,而yolo格式中的坐标为目标中点坐标与目标相对图片的高宽比

def convert(size, box):
    dw = 1. / size[0]
    dh = 1. / size[1]
    x = (box[0] + box[1]) / 2.0
    y = (box[2] + box[3]) / 2.0
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    return (x, y, w, h)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

voc转换为yolo

xml_file: 待转换xml文件的路径
txt_file: 转换完成后的保存路径
classes:list, xml文件中需要转换的类别

def xml2txt(xml_file, txt_file, classes:
    with open(txt_file, 'a') as f:
    	# 解析 xml 文件
        tree = ET.parse(xml_file)
        root = tree.getroot()
        # 读取高宽等信息
        size = root.find('size')
        w = int(size.find('width').text)
        h = int(size.find('height').text)
        # 遍历 xml 中的目标
        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)				# 转换为对应索引 从 0 开始
            xmlbox = obj.find('bndbox')				# 读取标注信息 [xmin, ymin, xmax, ymax]
            b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
                float(xmlbox.find('ymax').text))	# 字符型转换为float
            bb = convert((w, h), b)					# 转换为yolo格式 [xcenter, ycenter, box_w, box_h]
            f.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')	# 写入 txt 文件
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

主函数

文件结构:

|--- xml_dir
	|--- sample1.xml
	|--- sample12.xml
	...
  • 1
  • 2
  • 3
  • 4
if __name__ == '__main__':
    xml_dir = ''	# 指定 xml 文件所在目录
    out_dir = ''	# 指定转换完成的 txt 保存目录
    # 保存路径不存在则创建
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    # 遍历 xml 文件
    for xml in os.listdir(xml_dir):
        if xml.endswith('.xml'):
            xml_path = os.path.join(xml_dir, xml)
            out_path = os.path.join(out_dir, xml.replace('.xml','.txt'))
            xml2txt(xml_path, out_path)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

执行完代码后文件结构

|--- out_dir
	|--- sample11.txt
	|--- sample12.txt
	...
  • 1
  • 2
  • 3
  • 4

完整代码:

指定xml_dir,out_dir路径运行即可

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

def xml2txt(xml_file, txt_file, classes:
    with open(txt_file, 'a') as f:
    	# 解析 xml 文件
        tree = ET.parse(xml_file)
        root = tree.getroot()
        # 读取高宽等信息
        size = root.find('size')
        w = int(size.find('width').text)
        h = int(size.find('height').text)
        # 遍历 xml 中的目标
        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)				# 转换为对应索引 从 0 开始
            xmlbox = obj.find('bndbox')				# 读取标注信息 [xmin, ymin, xmax, ymax]
            b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
                float(xmlbox.find('ymax').text))	# 字符型转换为float
            bb = convert((w, h), b)					# 转换为yolo格式 [xcenter, ycenter, box_w, box_h]
            f.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')	# 写入 txt 文件

if __name__ == '__main__':
    xml_dir = ''	# 指定 xml 文件所在目录
    out_dir = ''	# 指定转换完成的 txt 保存目录
    classes = ['class1', 'class2', '...', 'classn']
    # 保存路径不存在则创建
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    # 遍历 xml 文件
    for xml in os.listdir(xml_dir):
        if xml.endswith('.xml'):
            xml_path = os.path.join(xml_dir, xml)
            out_path = os.path.join(out_dir, xml.replace('.xml','.txt'))
            xml2txt(xml_path, out_path, classes)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/433339
推荐阅读
相关标签
  

闽ICP备14008679号