YOLO格式数据集和VOC格式数据集互转(txt&xml)

前言

一、voc转yolo(xml转txt)

二、yolo转voc(txt转xml)


前言

在使用labelimg进行数据标注时可以将结果保存为yolo格式或者voc格式,但是发现要是想用labelimg打开yolo识别后的txt就不行了,在训练ai的时候我们可以用已经有的结果识别一遍图片,然后再进行查漏补缺,这样子效率会更高,这里出一个YOLO的txt与voc的xml相互转换源代码


一、voc转yolo(xml转txt)

import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
 
 
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)
    for xml_name in xml_files:
        print(xml_name)
        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')
        out_txt_f = open(out_txt_path, 'w')
        tree = ET.parse(xml_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))
            # b=(xmin, xmax, ymin, ymax)
            print(w, h, b)
            bb = convert((w, h), b)
            out_txt_f.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
 
 
if __name__ == "__main__":
    # 把voc的xml标签文件转化为yolo的txt标签文件
    # 1、类别
    classes1 = ['1','4']
    # 2、voc格式的xml标签文件路径
    xml_files1 = r'xml2'
    # 3、转化为yolo格式的txt标签文件存储路径
    save_txt_files1 = r'txt3'
    convert_annotation(xml_files1, save_txt_files1, classes1)

 将以上代码拷贝到一个py文件里,修改xml_files1与save_txt_files1为自己文件所在的相对路径,修改classes为自己标注的类别,cmd切换到当前py文件路径下,python ***.py 即可。

二、yolo转voc(txt转xml)

与上面代码一样,这里需要修改如下四条为自己对应的路径与类别

  1. voc_annotations = r'1010-01xml'
  2. yolo_txt = r'1010-01txt'
  3. img_path = r'1010-01photo'
  4. labels = ['1','4']  # label for datasets
import os
import glob
from PIL import Image

voc_annotations = r'1010-01xml'
yolo_txt = r'1010-01txt'
img_path = r'1010-01photo'
labels = ['1','4']  # label for datasets
# 图像存储位置
src_img_dir = img_path  # 添加你的路径
# 图像的txt文件存放位置


src_txt_dir = yolo_txt
src_xml_dir = voc_annotations

img_Lists = glob.glob(src_img_dir + '/*.jpg')

img_basenames = []
for item in img_Lists:
    img_basenames.append(os.path.basename(item))

img_names = []
for item in img_basenames:
    temp1, temp2 = os.path.splitext(item)
    img_names.append(temp1)

for img in img_names:
    im = Image.open((src_img_dir + '/' + img + '.jpg'))
    width, height = im.size

    # 打开txt文件
    gt = open(src_txt_dir + '/' + img + '.txt').read().splitlines()
    print(gt)
    if gt:
        # 将主干部分写入xml文件中
        xml_file = open((src_xml_dir + '/' + img + '.xml'), 'w')
        xml_file.write('\n')
        xml_file.write('    VOC2007\n')
        xml_file.write('    ' + str(img) + '.jpg' + '\n')
        xml_file.write('    \n')
        xml_file.write('        ' + str(width) + '\n')
        xml_file.write('        ' + str(height) + '\n')
        xml_file.write('        3\n')
        xml_file.write('    \n')

        # write the region of image on xml file
        for img_each_label in gt:
            spt = img_each_label.split(' ')  # 这里如果txt里面是以逗号‘,’隔开的,那么就改为spt = img_each_label.split(',')。
            print(f'spt:{spt}')
            xml_file.write('    \n')
            xml_file.write('        ' + str(labels[int(spt[0])]) + '\n')
            xml_file.write('        Unspecified\n')
            xml_file.write('        0\n')
            xml_file.write('        0\n')
            xml_file.write('        \n')

            center_x = round(float(spt[1].strip()) * width)
            center_y = round(float(spt[2].strip()) * height)
            bbox_width = round(float(spt[3].strip()) * width)
            bbox_height = round(float(spt[4].strip()) * height)
            xmin = str(int(center_x - bbox_width / 2))
            ymin = str(int(center_y - bbox_height / 2))
            xmax = str(int(center_x + bbox_width / 2))
            ymax = str(int(center_y + bbox_height / 2))

            xml_file.write('            ' + xmin + '\n')
            xml_file.write('            ' + ymin + '\n')
            xml_file.write('            ' + xmax + '\n')
            xml_file.write('            ' + ymax + '\n')
            xml_file.write('        \n')
            xml_file.write('    \n')

        xml_file.write('')

 

 

你可能感兴趣的:(xml,深度学习,人工智能,python)