从pascalvoc的xml文件生成yolo标记文件和name文件

这是一个Python脚本,用于将PASCALVOC格式的XML注释文件转换为YOLO所需的标记文件和name文件。脚本遍历指定目录下的所有XML文件,读取对象类别和边界框信息,然后转换并写入YOLO格式的txt文件。同时,它还会创建一个包含所有独特类别的name.txt文件。
摘要由CSDN通过智能技术生成

从pascalvoc的xml文件生成yolo标记文件和name文件
使用方法,拷贝入python文件,在xml文件夹上层目录运行

import os
import xml.etree.ElementTree as ET
import sys
'''
1.制作name.txt ok
2.制作train.txt
3.制作test.txt
'''


def convert(size, box):  # 将PascalVoc数据转化为yolo
    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 convert_annotation(image_id):
    # in_file = open(image_id.replace('\\', '/'), 'rb')
    in_file = image_id.replace('\\', '/')
    out_file = open(image_id.split('.')[0] + '.txt', 'w')

    tree = ET.parse(in_file)  # 解析xml树
    root = tree.getroot()
    size = root.find('size')
    w = int(size.find('width').text)
    h = int(size.find('height').text)

    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:
            classes.append(cls)
            # 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_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
    # in_file.close()
    out_file.close()


if __name__ == "__main__":
    classes = []

    wd = os.getcwd()  # 获取当前文件目录
    dir_list = os.listdir(wd)
    dir_xml = []
    for item in dir_list:
        if os.path.isdir(item):
            # dir.append(item)
            dir_path = os.path.join(wd, item)
            dir_list_temp = os.listdir(dir_path)
            for item2 in dir_list_temp:
                if os.path.isfile(dir_path.replace('\\', '/') + '/' + item2):
                    try:
                        if item2.split('.')[1] == 'xml':
                            dir_xml.append(dir_path + '/' + item2)  # 此处搜集完所有xml文件路径名称放在dir中
                    except IndexError:
                        pass

    for item in dir_xml:
        # *****hahaha, 这一小段是整来耍的
        sys.stdout.write('\r' + '/')
        sys.stdout.flush()
        sys.stdout.write('\r' + '|')
        sys.stdout.flush()
        sys.stdout.write('\r' + '\\')
        sys.stdout.flush()
        # print('\r'+'你的输出详情', flush=True)
        try:
            convert_annotation(item)
        except:
            pass

    with open('object.names', 'w') as f:  # 制作name文件
        for item in classes:
            f.write(item)
            f.write('\n')

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 将labelimg标注的voc格式标签xml文件转换为yolo格式标签txt文件,需要进行以下步骤: 1. 读取xml文件中的标注信息,包括目标类别、位置坐标等。 2. 根据yolo格式的要求,将目标位置坐标转换为相对于图像宽度和高度的比例。 3. 将目标类别转换为对应的数字标签,例如将“猫”转换为“”、“狗”转换为“1”。 4. 将转换后的标注信息按照yolo格式的要求,写入txt文件中。 将yolo格式标签txt文件转换为labelimg标注的voc格式标签xml文件,需要进行以下步骤: 1. 读取txt文件中的标注信息,包括目标类别、位置坐标等。 2. 根据voc格式的要求,将目标位置坐标转换为左上角和右下角的坐标值。 3. 将目标类别转换为对应的文字标签,例如将“”转换为“猫”、“1”转换为“狗”。 4. 将转换后的标注信息按照voc格式的要求,写入xml文件中。 以上是将labelimg标注的voc格式标签xml文件yolo格式标签txt文件相互转换的基本步骤,具体实现可以参考相关的代码库和工具。 ### 回答2: LabelImg是一种用于图像标注的常用工具,支持输出多种格式的标注文件,其中包括voc格式标签xml文件yolo格式标签txt文件。这些标签文件可以用于计算机视觉应用程序的训练和测试,因此在进行目标检测和物体识别时非常重要。 在实际应用中,可能需要将标签文件从一种格式转换为另一种格式。下面将介绍如何将LabelImg标注的voc格式标签xml文件yolo格式标签txt文件相互转换: 1. 将voc格式标签文件转换为yolo格式标签文件voc格式标签文件转换为yolo格式标签文件需要执行以下步骤: (1)将标签文件的路径保存到txt文件中。在标签xml文件的所在目录下创建一个txt文件并将标签文件的路径写入文件中。 (2)通过脚本来转换标签文件。执行以下命令来转换标签文件: python voc_label.py ./data/train/labelTxt/ ./data/train/Annotations/ ./data/train/ 在这里,“voc_label.py”是一个Python脚本名,将第一个参数设置为LabelImg生成xml文件所在的目录,将第二个参数设置为标签文件所在的目录,将第三个参数设置为生成yolo格式标签文件的输出目录。执行成功后,将在输出目录中生成与输入目录中的xml文件对应的yolo格式标签文件。 2. 将yolo格式标签文件转换为voc格式标签文件yolo格式标签文件转换为voc格式标签文件需要执行以下步骤: (1)创建一个xml文件并编写模板。在标签文件所在的目录下,创建一个xml文件并编写一个基本模板。在该模板中,应将标签文件的基本信息包括图像名称、标注区域的坐标、类别等一一列举出来。 (2)通过脚本来转换标签文件。执行以下命令来转换标签文件: python yolo_label.py train.txt 在这里,“train.txt”是一个包含所有标签路径的txt文件。执行成功后,将在标签文件所在目录中生成与输入目录中的yolo格式标签文件对应的voc格式标签文件。 总之,无论是将voc格式标签文件转换为yolo格式标签文件,还是将yolo格式标签文件转换为voc格式标签文件,都可以通过执行特定的脚本来完成。这些脚本可以轻松地将标签文件从一种格式转换为另一种格式,这对于计算机视觉应用程序的训练和测试来说是非常有用的。 ### 回答3: LabelImg是一款常用的图像标注软件,VOC格式的标签文件是其默认输出格式之一。而YOLO则是另一种常见的目标检测算法,其标注格式为txt文件。在实际使用中,我们有时需要将LabelImg标注生成VOC格式xml文件转换为YOLO格式的txt文件,或者反过来。下面我们将介绍如何进行这一转换。 1. VOC格式xml文件转换为YOLO格式txt文件 首先,我们需要明确VOC标签文件中的类别名称和类别编号。以VOC格式的xml标签文件为例,打开其中一个文件,我们可以看到类别名称通常被定义为类别列表中的一个节点。而类别编号则是在每个object节点中定义的。可以参考下面的片段: ``` <annotation> <folder>images</folder> <filename>image1.jpg</filename> <source> ... </source> <size> <width>1280</width> <height>720</height> <depth>3</depth> </size> <segmented>0</segmented> <object> <name>cat</name> <pose>Unspecified</pose> <truncated>0</truncated> <difficult>0</difficult> <bndbox> <xmin>438</xmin> <ymin>88</ymin> <xmax>821</xmax> <ymax>510</ymax> </bndbox> </object> ... </annotation> ``` 观察上面片段中的`<name>`标签,我们可以发现该标注文件的类别名称为"cat"。而在`<object>`节点中,出现了一个`<bndbox>`节点,其中包含了四个属性值,分别表示该目标的左上角坐标(xmin, ymin)和右下角坐标(xmax, ymax)。这些坐标值的单位都是像素。 有了这些信息之后,我们就可以将VOC格式xml文件转换为YOLO格式txt文件了。具体步骤如下: 1)读取VOC格式xml文件,并提取出目标的类别、左上角坐标、右下角坐标等信息。 2)按照YOLO格式要求,将坐标值归一化到[0, 1]的范围内,并计算出中心点坐标和目标宽高。 3)将归一化后的坐标值和类别编号写入txt文件。每行文件格式如下: ``` <class_id> <x> <y> <width> <height> ``` 其中class_id为类别编号,x和y是目标中心点坐标的归一化值,width和height是目标宽高的归一化值。 下面是实现该转换过程的Python代码示例: ```python import os import xml.etree.ElementTree as ET def convert_voc_to_yolo(voc_file, classes, out_file): """ Convert a VOC format label file to YOLO format. voc_file: path to the VOC format xml file. classes: a dictionary mapping class names to class indices. out_file: path to save the converted YOLO format txt file. """ tree = ET.parse(voc_file) root = tree.getroot() size = root.find('size') w = int(size.find('width').text) h = int(size.find('height').text) with open(out_file, 'w') as f: for obj in root.iter('object'): cls_name = obj.find('name').text if cls_name not in classes: continue cls_id = classes[cls_name] bbox = obj.find('bndbox') xmin = int(bbox.find('xmin').text) ymin = int(bbox.find('ymin').text) xmax = int(bbox.find('xmax').text) ymax = int(bbox.find('ymax').text) x = (xmin + xmax) / 2 / w y = (ymin + ymax) / 2 / h width = (xmax - xmin) / w height = (ymax - ymin) / h f.write(f'{cls_id} {x:.6f} {y:.6f} {width:.6f} {height:.6f}\n') classes = {'cat': 0, 'dog': 1, ...} voc_file = 'path/to/voc.xml' out_file = 'path/to/yolo.txt' convert_voc_to_yolo(voc_file, classes, out_file) ``` 2. YOLO格式txt文件转换为VOC格式xml文件 与上面的过程相反,我们同样需要先把类别名称和类别编号对应起来。由于YOLO的txt标注文件中只保存了图片中的目标的位置及其类别信息,所以在进行转换时需要额外对目标进行分类。 具体步骤如下: 1)读入YOLO格式txt文件,提取出其中的目标位置信息以及类别编号。 2)将坐标值从归一化范围转换为像素范围。 3)按照VOC格式的要求,将目标的类别、左上角坐标、右下角坐标等信息写入xml文件。 下面是代码示例: ```python import os import xml.etree.cElementTree as ET def convert_yolo_to_voc(yolo_file, classes, img_file, out_dir): """ Convert a YOLO format label file to VOC format yolo_file: path to the YOLO format txt file. classes: a dictionary mapping class names to class indices. img_file: path to the image file. out_dir: the output directory to save the VOC format xml file. """ root = ET.Element('annotation') folder = ET.SubElement(root, 'folder') folder.text = os.path.basename(os.path.dirname(img_file)) filename = ET.SubElement(root, 'filename') filename.text = os.path.basename(img_file) source = ET.SubElement(root, 'source') database = ET.SubElement(source, 'database') database.text = 'Unknown' size = ET.SubElement(root, 'size') img_w, img_h, img_c = cv2.imread(img_file).shape width = ET.SubElement(size, 'width') width.text = str(img_w) height = ET.SubElement(size, 'height') height.text = str(img_h) depth = ET.SubElement(size, 'depth') depth.text = str(img_c) segmented = ET.SubElement(root, 'segmented') segmented.text = '0' with open(yolo_file, 'r') as f: for line in f.readlines(): parts = line.strip().split() cls_id = int(parts[0]) if cls_id not in classes: continue cls_name = classes[cls_id] x, y, width_norm, height_norm = map(float, parts[1:]) x1 = int((x - width_norm/2) * img_w) y1 = int((y - height_norm/2) * img_h) x2 = int(x1 + width_norm * img_w) y2 = int(y1 + height_norm * img_h) object_ = ET.SubElement(root, 'object') name = ET.SubElement(object_, 'name') name.text = cls_name pose = ET.SubElement(object_, 'pose') pose.text = 'Unspecified' truncated = ET.SubElement(object_, 'truncated') truncated.text = '0' difficult = ET.SubElement(object_, 'difficult') difficult.text = '0' bndbox = ET.SubElement(object_, 'bndbox') xmin = ET.SubElement(bndbox, 'xmin') xmin.text = str(x1) ymin = ET.SubElement(bndbox, 'ymin') ymin.text = str(y1) xmax = ET.SubElement(bndbox, 'xmax') xmax.text = str(x2) ymax = ET.SubElement(bndbox, 'ymax') ymax.text = str(y2) out_xml_file = os.path.join(out_dir, os.path.splitext(os.path.basename(yolo_file))[0] + '.xml') tree = ET.ElementTree(root) tree.write(out_xml_file) classes = {0: 'cat', 1: 'dog', ...} yolo_file = 'path/to/yolo.txt' img_file = 'path/to/image.jpg' out_dir = 'path/to/output' convert_yolo_to_voc(yolo_file, classes, img_file, out_dir) ``` 总之,在目标检测任务中,标注数据的格式转换是一个常见的问题。掌握对不同格式数据的相互转换,有利于提高我们的工作效率,也能为实现更加复杂和灵活的目标检测任务提供便利。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值