目标检测中将txt文件格式转xml,将YOLO格式转换成VOC(互转)

txt2xml:

import os
import cv2
from pathlib import Path

class_name = ["veg", "hot-spot", "crack", "soil"]


def txt2xml(txt_path, xml_path, img_path):
    if not os.path.exists(xml_path):
        os.makedirs(xml_path)
    txt_files = os.listdir(txt_path)
    for txt_file in txt_files:
        name = Path(txt_file).stem
        xml_file = xml_path + name + ".xml"
        img = img_path + name + ".jpg"
        txt = txt_path + txt_file
        print(img_path)
        print(txt_file)
        img = cv2.imread(img)
        H, W, C = img.shape
        txt = open(txt)
        txt_lists = txt.readlines()
        for txt_list in txt_lists:
            infors = txt_list.strip().split(" ")
            xml = open((xml_file), 'w')
            xml.write('<annotation>\n')
            xml.write('    <folder>yolov5_img</folder>\n')
            xml.write('    <filename>' + name + '.jpg' + '</filename>\n')
            xml.write('    <path>' + str(img_path) + '</path>\n')
            xml.write('    <source>\n')
            xml.write('         <database>Peaunt</database>\n')
            xml.write('    </source>\n')
            xml.write('    <size>\n')
            xml.write('        <width>' + str(W) + '</width>\n')
            xml.write('        <height>' + str(H) + '</height>\n')
            xml.write('        <depth>' + str(C) + '</depth>\n')
            xml.write('    </size>\n')
            xml.write('    <segmented>0</segmented>\n')
            xml.write('    <object>\n')
            xml.write('         <name>' + class_name[int(infors[0])] + '</name>\n')
            xml.write('         <pose>Unspecified</pose>\n')
            xml.write('         <truncated>0</truncated>\n')
            xml.write('         <difficult>0</difficult>\n')
            xml.write('         <bndbox>\n')
            xml.write('            <xmin>' + str(
                int(((float(infors[1])) * W) - (float(infors[3])) * 0.5 * W)) + '</xmin>\n')
            xml.write('            <ymin>' + str(
                int(((float(infors[2])) * H) - (float(infors[4])) * 0.5 * H)) + '</ymin>\n')
            xml.write('            <xmax>' + str(
                int(((float(infors[1])) * W) + (float(infors[3])) * 0.5 * W)) + '</xmax>\n')
            xml.write('            <ymax>' + str(
                int(((float(infors[2])) * H) + (float(infors[4])) * 0.5 * H)) + '</ymax>\n')
            xml.write('          </bndbox>\n')
            xml.write('    </object>\n')
            xml.close()
        xml = open((xml_file), 'a')
        xml.write('</annotation>')
        xml.close()


if __name__ == '__main__':
    txt_path = "E:/xy/VOC2007/labels/"
    xml_path = "E:/xy/VOC2007/annotations/"
    img_path = "E:/xy/VOC2007/JPEGImages/"
    txt2xml(txt_path, xml_path, img_path)

xml2txt;

# -*- coding: utf-8 -*-

import xml.etree.ElementTree as ET
import os
from os import getcwd

sets = ['train', 'val', 'test']
classes =["crack"]
abs_path = os.getcwd()


def convert(size, box):
    dw = 1. / (size[0])
    dh = 1. / (size[1])
    x = (box[0] + box[1]) / 2.0 - 1
    y = (box[2] + box[3]) / 2.0 - 1
    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('Annotations/%s.xml' % (image_id),encoding='utf-8')
    out_file = open('labels/%s.txt' % (image_id), 'w',encoding='utf-8')
    tree = ET.parse(in_file)
    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:
            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))
        b1, b2, b3, b4 = b
        # 标注越界修正
        if b2 > w:
            b2 = w
        if b4 > h:
            b4 = h
        b = (b1, b2, b3, b4)
        bb = convert((w, h), b)
        out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')


wd = getcwd()
for image_set in sets:
    if not os.path.exists('labels/'):
        os.makedirs('labels/')
    image_ids = open('hf_txt/%s.txt' % (image_set)).read().strip().split()
    list_file = open('%s.txt' % (image_set), 'w')
    for image_id in image_ids:
        list_file.write(abs_path + '/images/%s.jpg\n' % (image_id))
        convert_annotation(image_id)
    list_file.close()
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 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文件 与上面的过程相反,我们同样需要先把类别名称和类别编号对应起来。由于YOLOtxt标注文件中只保存了图片中的目标的位置及其类别信息,所以在进行换时需要额外对目标进行分类。 具体步骤如下: 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
发出的红包

打赏作者

浪迹天涯@wxy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值