• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

.txt(yolo)和.xml(VOC)数据集标签格式互相转换

武飞扬头像
DreamFish212
帮助1

前言:博主在处理目标检测数据集时,经常需要将标签进行不同格式的转换,因此整理了以下代码,以供参考和保存。

一、实现将txt格式转换成xml格式:

  1.  
    # 将txt格式转换成xml格式数据集
  2.  
    from xml.dom.minidom import Document
  3.  
    import os
  4.  
    import cv2
  5.  
     
  6.  
     
  7.  
    def makexml(picPath, txtPath, xmlPath): # txt所在文件夹路径,xml文件保存路径,图片所在文件夹路径
  8.  
    """此函数用于将yolo格式txt标注文件转换为voc格式xml标注文件
  9.  
    在自己的标注图片文件夹下建三个子文件夹,分别命名为picture、txt、xml
  10.  
    """
  11.  
    #创建字典用来对类型进行转换,要与classes.txt文件中的类对应,且顺序要一致
  12.  
    dic = {'0': "person", '1': "car", '2': "bike", '3': "color_cone",
  13.  
    '4': "car_stop", '5': "bump", '6': "hole", '7': "animal"}
  14.  
    files = os.listdir(txtPath)
  15.  
    for i, name in enumerate(files):
  16.  
    xmlBuilder = Document()
  17.  
    annotation = xmlBuilder.createElement("annotation") # 创建annotation标签
  18.  
    xmlBuilder.appendChild(annotation)
  19.  
    txtFile = open(txtPath name)
  20.  
    txtList = txtFile.readlines()
  21.  
    img = cv2.imread(picPath name[0:-4] ".png") # 注意这里的图片后缀,.jpg/.png
  22.  
    Pheight, Pwidth, Pdepth = img.shape
  23.  
     
  24.  
    folder = xmlBuilder.createElement("folder") # folder标签
  25.  
    foldercontent = xmlBuilder.createTextNode("datasetRGB")
  26.  
    folder.appendChild(foldercontent)
  27.  
    annotation.appendChild(folder)
  28.  
     
  29.  
    filename = xmlBuilder.createElement("filename") # filename标签
  30.  
    filenamecontent = xmlBuilder.createTextNode(name[0:-4] ".png")
  31.  
    filename.appendChild(filenamecontent)
  32.  
    annotation.appendChild(filename)
  33.  
     
  34.  
    size = xmlBuilder.createElement("size") # size标签
  35.  
    width = xmlBuilder.createElement("width") # size子标签width
  36.  
    widthcontent = xmlBuilder.createTextNode(str(Pwidth))
  37.  
    width.appendChild(widthcontent)
  38.  
    size.appendChild(width)
  39.  
     
  40.  
    height = xmlBuilder.createElement("height") # size子标签height
  41.  
    heightcontent = xmlBuilder.createTextNode(str(Pheight))
  42.  
    height.appendChild(heightcontent)
  43.  
    size.appendChild(height)
  44.  
     
  45.  
    depth = xmlBuilder.createElement("depth") # size子标签depth
  46.  
    depthcontent = xmlBuilder.createTextNode(str(Pdepth))
  47.  
    depth.appendChild(depthcontent)
  48.  
    size.appendChild(depth)
  49.  
     
  50.  
    annotation.appendChild(size)
  51.  
     
  52.  
    for j in txtList:
  53.  
    oneline = j.strip().split(" ")
  54.  
    object = xmlBuilder.createElement("object") # object 标签
  55.  
    picname = xmlBuilder.createElement("name") # name标签
  56.  
    namecontent = xmlBuilder.createTextNode(dic[oneline[0]])
  57.  
    picname.appendChild(namecontent)
  58.  
    object.appendChild(picname)
  59.  
     
  60.  
    pose = xmlBuilder.createElement("pose") # pose标签
  61.  
    posecontent = xmlBuilder.createTextNode("Unspecified")
  62.  
    pose.appendChild(posecontent)
  63.  
    object.appendChild(pose)
  64.  
     
  65.  
    truncated = xmlBuilder.createElement("truncated") # truncated标签
  66.  
    truncatedContent = xmlBuilder.createTextNode("0")
  67.  
    truncated.appendChild(truncatedContent)
  68.  
    object.appendChild(truncated)
  69.  
     
  70.  
    difficult = xmlBuilder.createElement("difficult") # difficult标签
  71.  
    difficultcontent = xmlBuilder.createTextNode("0")
  72.  
    difficult.appendChild(difficultcontent)
  73.  
    object.appendChild(difficult)
  74.  
     
  75.  
    bndbox = xmlBuilder.createElement("bndbox") # bndbox标签
  76.  
    xmin = xmlBuilder.createElement("xmin") # xmin标签
  77.  
    mathData = int(((float(oneline[1])) * Pwidth 1) - (float(oneline[3])) * 0.5 * Pwidth)
  78.  
    xminContent = xmlBuilder.createTextNode(str(mathData))
  79.  
    xmin.appendChild(xminContent)
  80.  
    bndbox.appendChild(xmin)
  81.  
     
  82.  
    ymin = xmlBuilder.createElement("ymin") # ymin标签
  83.  
    mathData = int(((float(oneline[2])) * Pheight 1) - (float(oneline[4])) * 0.5 * Pheight)
  84.  
    yminContent = xmlBuilder.createTextNode(str(mathData))
  85.  
    ymin.appendChild(yminContent)
  86.  
    bndbox.appendChild(ymin)
  87.  
     
  88.  
    xmax = xmlBuilder.createElement("xmax") # xmax标签
  89.  
    mathData = int(((float(oneline[1])) * Pwidth 1) (float(oneline[3])) * 0.5 * Pwidth)
  90.  
    xmaxContent = xmlBuilder.createTextNode(str(mathData))
  91.  
    xmax.appendChild(xmaxContent)
  92.  
    bndbox.appendChild(xmax)
  93.  
     
  94.  
    ymax = xmlBuilder.createElement("ymax") # ymax标签
  95.  
    mathData = int(((float(oneline[2])) * Pheight 1) (float(oneline[4])) * 0.5 * Pheight)
  96.  
    ymaxContent = xmlBuilder.createTextNode(str(mathData))
  97.  
    ymax.appendChild(ymaxContent)
  98.  
    bndbox.appendChild(ymax)
  99.  
     
  100.  
    object.appendChild(bndbox) # bndbox标签结束
  101.  
     
  102.  
    annotation.appendChild(object)
  103.  
     
  104.  
    f = open(xmlPath name[0:-4] ".xml", 'w')
  105.  
    xmlBuilder.writexml(f, indent='\t', newl='\n', addindent='\t', encoding='utf-8')
  106.  
    f.close()
  107.  
     
  108.  
     
  109.  
    if __name__ == "__main__":
  110.  
    picPath = "C:\\data\\ir_det_dataset\\Images\\fir\\" # 图片所在文件夹路径,后面的\\一定要带上
  111.  
    txtPath = "C:\\data\\ir_det_dataset\\labels\\fir\\" # txt所在文件夹路径,后面的\\一定要带上
  112.  
    xmlPath = "C:\\data\\ir_det_dataset\\xml\\fir\\" # xml文件保存路径,后面的\\一定要带上
  113.  
    makexml(picPath, txtPath, xmlPath)
学新通

转换之后第一行可能会出现<?xml version="1.0" encoding="utf-8"?>,这行代码声明所用的xml版本是1.0,用xml传输数据时的字符编码是utf-8,如果想去除第一行可以采用以下代码:

  1.  
    import os
  2.  
    def file_name(input_dir,output_dir,spile):
  3.  
    for root, dirs, files in os.walk(input_dir):
  4.  
    for item in files:
  5.  
    f = open(input_dir item, "r", encoding='UTF-8')
  6.  
    content = f.read()
  7.  
    content = content.replace('<?xml version="1.0" encoding="utf-8"?>', spile)
  8.  
    with open(os.path.join(output_dir, item), 'w',encoding='UTF-8') as fval:
  9.  
    fval.write(content)
  10.  
    f.close()
  11.  
    if __name__ == '__main__':
  12.  
    input_dir = "C:\\data\\ir_det_dataset\\xml\\fir\\" #旧文件夹
  13.  
    output_dir = "C:\\data\\ir_det_dataset\\xml\\fir\\xml\\" #新文件夹
  14.  
    file_name(input_dir, output_dir, "")

二、实现将txt格式转换成xml格式:

  1.  
    import xml.etree.ElementTree as ET
  2.  
    import os
  3.  
     
  4.  
    classes = ["person", "car", "bike", "color_cone", "car_stop", "bump", "hole", "animal"]
  5.  
     
  6.  
    # 和自己classes.txt中的类别要一个一个地对应
  7.  
     
  8.  
     
  9.  
    def convert(size, box):
  10.  
    dw = 1. / size[0]
  11.  
    dh = 1. / size[1]
  12.  
    x = (box[0] box[1]) / 2.0
  13.  
    y = (box[2] box[3]) / 2.0
  14.  
    w = box[1] - box[0]
  15.  
    h = box[3] - box[2]
  16.  
    x = x * dw
  17.  
    w = w * dw
  18.  
    y = y * dh
  19.  
    h = h * dh
  20.  
    return (x, y, w, h)
  21.  
     
  22.  
     
  23.  
    def convert_annotation(image_id):
  24.  
     
  25.  
    in_file = open("C:\\data\\ir_det_dataset\\Images\\fir\\xml\\%s.xml" % (image_id), encoding='UTF-8')
  26.  
    # in_file输入要转换的文件路径
  27.  
     
  28.  
    out_file = open("C:\\data\\ir_det_dataset\\Images\\fir\\txt\\%s.txt" % (image_id), 'w')
  29.  
    # out_file输出转换后的文件路径
  30.  
     
  31.  
    tree = ET.parse(in_file)
  32.  
    root = tree.getroot()
  33.  
    size = root.find('size')
  34.  
    w = int(size.find('width').text)
  35.  
    h = int(size.find('height').text)
  36.  
     
  37.  
    for obj in root.iter('object'):
  38.  
    cls = obj.find('name').text
  39.  
    # print(cls)
  40.  
    if cls not in classes:
  41.  
    continue
  42.  
    cls_id = classes.index(cls)
  43.  
    xmlbox = obj.find('bndbox')
  44.  
    b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
  45.  
    float(xmlbox.find('ymax').text))
  46.  
    bb = convert((w, h), b)
  47.  
    out_file.write(str(cls_id) " " " ".join([str(a) for a in bb]) '\n')
  48.  
     
  49.  
     
  50.  
    CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
  51.  
    xml_path = os.path.join(CURRENT_DIR, "C:\\data\\ir_det_dataset\\Images\\fir\\xml\\")
  52.  
    # xml文件路径
  53.  
     
  54.  
    # xml list
  55.  
    img_xmls = os.listdir(xml_path)
  56.  
    for img_xml in img_xmls:
  57.  
    label_name = img_xml.split('.')[0]
  58.  
    print(label_name)
  59.  
    convert_annotation(label_name)
学新通

以上代码同时参考了其他博主,第一次发帖如有侵权请联系删除~

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgcfbbc
系列文章
更多 icon
同类精品
更多 icon
继续加载