比赛中学习(2)-voc数据集制作中将.txt文件变为.xml文件

描述

和voc数据集制作有一点不同的是,因为参加的比赛中坐标给了4个,也就是说目标的形状可能是是平行四边形。所以和voc数据集有点不同啊。放出一张.txt文件的形式

比赛中学习(2)-voc数据集制作中将.txt文件变为.xml文件_第1张图片

最后的结果大致是这样的(和上面的图片不是对应的啊)

比赛中学习(2)-voc数据集制作中将.txt文件变为.xml文件_第2张图片

简介

这个代码的功能有两个

(1)将图片重新命名和图片位置更改

(2).txt文件变为.xml文件

代码

import xml.dom
import xml.dom.minidom
import os
import cv2
# xml文件规范定义

#.txt和.jpg文件存放的地址
_TXT_PATH= 'label'
_IMAGE_PATH= 'image'

_INDENT= ''*4
_NEW_LINE= '\n'
_FOLDER_NODE= 'VOC2007'
_ROOT_NODE= 'annotation'
_DATABASE_NAME= 'LOGODection'
_ANNOTATION= 'PASCAL VOC2007'
_AUTHOR= 'zhangyu'
_SEGMENTED= '0'
_DIFFICULT= '0'
_TRUNCATED= '0'
_POSE= 'Unspecified'

#.xml文件和图片重命名文件的存放地址
_IMAGE_COPY_PATH= 'JPEGImages'
_ANNOTATION_SAVE_PATH= 'Annotations'


# 封装创建节点的过�?
def createElementNode(doc,tag, attr):  # 创建一个元素节�?
    element_node = doc.createElement(tag)

    # 创建一个文本节�?
    text_node = doc.createTextNode(attr)

    # 将文本节点作为元素节点的子节�?
    element_node.appendChild(text_node)

    return element_node

    # 封装添加一个子节点的过�?
def createChildNode(doc,tag, attr,parent_node):



    child_node = createElementNode(doc, tag, attr)

    parent_node.appendChild(child_node)

# object节点比较特殊

def createObjectNode(doc,attrs):

    object_node = doc.createElement('object')

    createChildNode(doc, 'name', attrs['classification'],
                    object_node)

    createChildNode(doc, 'pose',
                    _POSE, object_node)

    createChildNode(doc, 'truncated',
                    _TRUNCATED, object_node)

    createChildNode(doc, 'difficult',
                    _DIFFICULT, object_node)

    bndbox_node = doc.createElement('bndbox')

    createChildNode(doc, 'x1', attrs['x1'],
                    bndbox_node)

    createChildNode(doc, 'y1', attrs['y1'],
                    bndbox_node)

    createChildNode(doc, 'x2', attrs['x2'],
                    bndbox_node)

    createChildNode(doc, 'y2', attrs['y2'],
                    bndbox_node)
    createChildNode(doc, 'x3', attrs['x3'],
                    bndbox_node)

    createChildNode(doc, 'y3', attrs['y3'],
                    bndbox_node)

    createChildNode(doc, 'x4', attrs['x4'],
                    bndbox_node)

    createChildNode(doc, 'y4', attrs['y4'],
                    bndbox_node)


    object_node.appendChild(bndbox_node)

    return object_node

# 将documentElement写入XML文件�?
def writeXMLFile(doc,filename):

    tmpfile =open('tmp.xml','w')

    doc.writexml(tmpfile, addindent=''*4,newl = '\n',encoding = 'utf-8')

    tmpfile.close()

    # 删除第一行默认添加的标记

    fin =open('tmp.xml')

    fout =open(filename, 'w')

    lines = fin.readlines()

    for line in lines[1:]:

        if line.split():

         fout.writelines(line)

        # new_lines = ''.join(lines[1:])

        # fout.write(new_lines)

    fin.close()

    fout.close()

def getFileList(path):

    fileList = []
    files = os.listdir(path)
    for f in files:
        if (os.path.isfile(path + '/' + f)):
            fileList.append(f)
    # print len(fileList)
    return fileList


if __name__ == "__main__":

    fileList = getFileList(_TXT_PATH)
    if fileList == 0:
        os._exit(-1)

    current_dirpath = os.path.dirname(os.path.abspath('__file__'))

    if not os.path.exists(_ANNOTATION_SAVE_PATH):
        os.mkdir(_ANNOTATION_SAVE_PATH)

    if not os.path.exists(_IMAGE_COPY_PATH):
        os.mkdir(_IMAGE_COPY_PATH)

    for xText in range(len(fileList)):

        saveName= "%05d" %(xText+1)
        pos = fileList[xText].rfind(".")
        textName = fileList[xText][:pos]

        ouput_file = open(_TXT_PATH + '/' + fileList[xText])
        # ouput_file =open(_TXT_PATH)

        lines = ouput_file.readlines()

        xml_file_name = os.path.join(_ANNOTATION_SAVE_PATH, (saveName + '.xml'))

        img=cv2.imread(os.path.join(_IMAGE_PATH,(textName+'.jpg')))
        #因为数据集中有的图片不显示,因为数据集中有的图片不显示,没有image.shape
        try:
            height,width,channel=img.shape
        except AttributeError:
            continue
        
        
        print(os.path.join(_IMAGE_COPY_PATH,(textName+'.jpg')))
        cv2.imwrite(os.path.join(_IMAGE_COPY_PATH,(saveName+'.jpg')),img)
        my_dom = xml.dom.getDOMImplementation()

        doc = my_dom.createDocument(None,_ROOT_NODE,None)

        # 获得根节�?
        root_node = doc.documentElement

        # folder节点

        createChildNode(doc, 'folder',_FOLDER_NODE, root_node)

        # filename节点

        createChildNode(doc, 'filename', saveName+'.jpg',root_node)

        # source节点

        source_node = doc.createElement('source')

        # source的子节点

        createChildNode(doc, 'database',_DATABASE_NAME, source_node)

        createChildNode(doc, 'annotation',_ANNOTATION, source_node)

        createChildNode(doc, 'image','flickr', source_node)

        createChildNode(doc, 'flickrid','NULL', source_node)

        root_node.appendChild(source_node)

        # owner节点

        owner_node = doc.createElement('owner')

        # owner的子节点

        createChildNode(doc, 'flickrid','NULL', owner_node)

        createChildNode(doc, 'name',_AUTHOR, owner_node)

        root_node.appendChild(owner_node)

        # size节点

        size_node = doc.createElement('size')

        createChildNode(doc, 'width',str(width), size_node)

        createChildNode(doc, 'height',str(height), size_node)

        createChildNode(doc, 'depth',str(channel), size_node)

        root_node.appendChild(size_node)

        # segmented节点

        createChildNode(doc, 'segmented',_SEGMENTED, root_node)


        for line in lines:

            s = line.rstrip('\n')

            array = s.split(',')

            print(array)

            attrs = dict()

            attrs['x1']= array[0]

            attrs['y1']= array[1]

            attrs['x2']= array[2]

            attrs['y2']= array[3]
            
            attrs['x3']= array[4]

            attrs['y3']= array[5]

            attrs['x4']= array[6]

            attrs['y4']= array[7]

            attrs['classification'] = array[8]
            # 构建XML文件名称

            print(xml_file_name)

            # 创建XML文件

            # createXMLFile(attrs, width, height, xml_file_name)
            # object节点

            object_node = createObjectNode(doc, attrs)

            root_node.appendChild(object_node)

            # 写入文件

            writeXMLFile(doc, xml_file_name)

提示

(1)因为.txt文件分开的形式是逗号(,),所以代码是这样的

array = s.split(',')

(2)因为部分图片不显示,会出现问题,然后使用try accept解决了

 #因为数据集中有的图片不显示,因为数据集中有的图片不显示,没有image.shape
        try:
            height,width,channel=img.shape
        except AttributeError:
            continue
        

(3)做了一些小测试,理解这些代码

#测试这段代码    saveName= "%05d" %(xText+1)
xText = 0
savename =  "%05d" %(xText+1)
print(savename)
#测试这段代码  pos = fileList[xText].rfind(".")
str = 'sdasdjaklda.jpg'
#pos = str.rfind('.')
pos = str.find('.')
textName = str[:pos]
print(textName)

参考的博客,但是代码写的是真的好啊。只改了一点点

https://blog.csdn.net/yjl9122/article/details/56842098



你可能感兴趣的:(比赛)