当前位置: 首页 > 工具软件 > img2txt > 使用案例 >

【图像标注篇】格式转换详解,labelimg标注生成的xml文件转成yolov5使用的txt格式,并进行格式划分

端木志诚
2023-12-01

【图像标注篇】格式转换详解,labelimg标注生成的xml文件转成yolov5使用的txt格式,并进行格式划分。

xml转换成txt格式代码如下

import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join

# 数据标签
classes = ['insulator','negative_feeder_shoulder','hat','flat_wrist','support_windbreak_cable','position_windbreak_cable']
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
    if w>=1:
        w=0.99
    if h>=1:
        h=0.99
    return (x,y,w,h)

def convert_annotation(rootpath,xmlname):
    xmlpath = rootpath + '/xml'
    xmlfile = os.path.join(xmlpath,xmlname)
    with open(xmlfile, "r", encoding='UTF-8') as in_file:
      txtname = xmlname[:-4]+'.txt'
      print(txtname)
      txtpath = rootpath + '/worktxt'
      if not os.path.exists(txtpath):
        os.makedirs(txtpath)
      txtfile = os.path.join(txtpath,txtname)
      with open(txtfile, "w+" ,encoding='UTF-8') as out_file:
        tree=ET.parse(in_file)
        root = tree.getroot()
        size = root.find('size')
        w = int(size.find('width').text)
        h = int(size.find('height').text)
        out_file.truncate()
        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))
            bb = convert((w,h), b)
            out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')


if __name__ == "__main__":
    rootpath='C:/Users/Dell/Desktop/merge'
    xmlpath=rootpath+'/xml'
    list=os.listdir(xmlpath)
    for i in range(0,len(list)) :
        path = os.path.join(xmlpath,list[i])
        if ('.xml' in path)or('.XML' in path):
            convert_annotation(rootpath,list[i])
            print('done', i)
        else:
            print('not xml file',i)

只需修改路径即可。

格式划分8:1:1

import os
import shutil

root_path = "C:/Users/Dell/Desktop/merge/dataset/"
img_path = "C:/Users/Dell/Desktop/merge/insulator/images/"
txt_path = "C:/Users/Dell/Desktop/merge/worktxt/"
def train_test_move(txt_path,root_path,img_path):
    files = os.listdir(txt_path)
    l = len(files)
    sets = ['train', 'valid', 'test']
    k = 0
    p = 0.8
    for i in sets:
        if not os.path.exists(root_path+i):
            print(root_path+i)
            os.mkdir(root_path+i)
            os.mkdir(root_path+i+"/images")
            os.mkdir(root_path+i+"/labels")
        for file in files[round(l*k):round(l*p)]:
            shutil.copy(txt_path+file,root_path+i+"/labels")
            shutil.copy(img_path+file[:-3]+"jpg",root_path+i+"/images")
        k = p
        p += 0.1
train_test_move(txt_path,root_path,img_path)

txt格式转成xml格式

import os
import xml.etree.ElementTree as ET
from PIL import Image
import numpy as np

# 图片文件夹,后面的/不能省
img_path = 'C:/Users/Dell/Desktop/merge/insulator/images/'

# txt文件夹,后面的/不能省
labels_path = 'C:/Users/Dell/Desktop/merge/insulator/labels/'

# xml存放的文件夹,后面的/不能省
annotations_path = 'C:/Users/Dell/Desktop/merge/insulator/xml/'

labels = os.listdir(labels_path)

# 类别
classes = ["insulator"]
# 图片的高度、宽度、深度
sh = sw = sd = 0

def write_xml(imgname, sw, sh, filepath, labeldicts):
    '''
    imgname: 没有扩展名的图片名称
    '''

    # 创建Annotation根节点
    root = ET.Element('xml')

    # 创建filename子节点,无扩展名
    ET.SubElement(root, 'filename').text = str(imgname)

    # 创建size子节点
    sizes = ET.SubElement(root,'size')
    ET.SubElement(sizes, 'width').text = str(sw)
    ET.SubElement(sizes, 'height').text = str(sh)
    #ET.SubElement(sizes, 'depth').text = str(sd)

    for labeldict in labeldicts:
        objects = ET.SubElement(root, 'object')
        ET.SubElement(objects, 'name').text = labeldict['name']
        ET.SubElement(objects, 'pose').text = 'Unspecified'
        ET.SubElement(objects, 'truncated').text = '0'
        ET.SubElement(objects, 'Difficult').text = '0'
        bndbox = ET.SubElement(objects,'bndbox')
        ET.SubElement(bndbox, 'xmin').text = str(int(labeldict['xmin']))
        ET.SubElement(bndbox, 'ymin').text = str(int(labeldict['ymin']))
        ET.SubElement(bndbox, 'xmax').text = str(int(labeldict['xmax']))
        ET.SubElement(bndbox, 'ymax').text = str(int(labeldict['ymax']))
    tree = ET.ElementTree(root)
    tree.write(filepath, encoding='utf-8')

for label in labels:
    with open(labels_path + label, 'r') as f:
        img_id = os.path.splitext(label)[0]
        contents = f.readlines()
        labeldicts = []
        for content in contents:
            # 这里要看你的图片格式了,我这里是jpg,注意修改
            img = np.array(Image.open(img_path + label.strip('.txt') + '.jpg'))

            # 图片的高度和宽度
            #sh, sw, sd = img.shape[0], img.shape[1], img.shape[2]
            sh, sw = img.shape[0], img.shape[1]
            content = content.strip('\n').split()
            x = float(content[1])*sw
            y = float(content[2])*sh
            w = float(content[3])*sw
            h = float(content[4])*sh

            # 坐标的转换,x_center y_center width height -> xmin ymin xmax ymax
            new_dict = {'name': classes[int(content[0])],
                        'difficult': '0',
                        'xmin': x+1-w/2,
                        'ymin': y+1-h/2,
                        'xmax': x+1+w/2,
                        'ymax': y+1+h/2
                        }
            labeldicts.append(new_dict)
        #write_xml(img_id, sw, sh, sd, annotations_path + label.strip('.txt') + '.xml', labeldicts)
        write_xml(img_id, sw, sh, annotations_path + label.strip('.txt') + '.xml', labeldicts)
 类似资料: