python將FLIR數據集中json標籤轉換成xml文件--僅限目標檢測

1.新建一個json文件,從已有的json文件中提取需要用到的類別,比如在下文代碼中,提取了四個類別包括person、car、bus、truck等,代碼如下所示

#-*- coding:utf-8-*-
import json
className = {
    1:'person',
    3:'car',
    6:'bus',
    8:'truck'
}
classNum = [1, 3,6,8]
cocojson="C:\\Users\\Administrator\\Desktop\\FLIR_ADAS_1_3\\train\\thermal_annotations.json" 
def writeNum(Num):
    f=open("C:\\Users\\Administrator\\Desktop\\FLIR_ADAS_1_3\\train\\annptations.json", "a+")
    f.write(str(Num))
inputfile = []
inner = {}
with open(cocojson, "r+") as f:
    allData = json.load(f)
    data =allData["annotations"]
    print(data[1])
    print("read ready")
for i in data:
    if (i['category_id'] in classNum):
        inner = {
            "filename":str(i["image_id"]).zfill(5),
            "name":className[i["category_id"]],
            "bndbox":i["bbox"]
        }
        inputfile.append(inner)
inputfile = json.dumps(inputfile)
writeNum(inputfile)

2.將訓練圖片中包含了四種類別的圖片提取出來,存放在新的文件夾

import json
import os
import cv2

nameStr = []
with open("C:\\Users\\Administrator\\Desktop\\FLIR_ADAS_1_3\\train\\annptations.json", "r+") as f:
    data = json.load(f)
    print("read ready")
for i in data:
    imgName = "FLIR_" + str(i["filename"]) + ".jpeg"
    nameStr.append(imgName)
nameStr = set(nameStr)
print(nameStr)
print(len(nameStr))

path = 'C:\\Users\\Administrator\\Desktop\\FLIR_ADAS_1_3\\train\\thermal_8_bit\\'
savePath = "C:\\Users\\Administrator\\Desktop\\FLIR_ADAS_1_3\\train\\traindata\\"
count = 0
for file in nameStr:
    img = cv2.imread(path + file)
    cv2.imwrite(savePath + file, img)
    count = count + 1
    print('num: ' + count.__str__() + '     ' + file + '\n')

3.將圖片和json文件一一對應生成xml文件

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

import xml.dom
import xml.dom.minidom
import os
# from PIL import Image
import cv2
import json

# xml文件規範定義


_IMAGE_PATH = 'C:\\Users\\Administrator\\Desktop\\FLIR_ADAS_1_3\\train'

_INDENT = '' * 4
_NEW_LINE = '\n'
_FOLDER_NODE = 'traindata'
_ROOT_NODE = 'annotation'
_DATABASE_NAME = 'traindata'
_ANNOTATION = 'traindata'
# = 'SyGoing_CSDN'
_SEGMENTED = '0'
_DIFFICULT = '0'
_TRUNCATED = '0'
_POSE = 'Unspecified'

# _IMAGE_COPY_PATH= 'JPEGImages'
_ANNOTATION_SAVE_PATH = 'C:\\Users\\Administrator\\Desktop\\FLIR_ADAS_1_3\\train\Annotations\\'


# _IMAGE_CHANNEL= 3

# 封裝創建節點的過程
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')

    midname = attrs['name']

    if midname != 'person':
        midname = 'car'

    createChildNode(doc, 'name', midname,
                    object_node)

    # createChildNode(doc, 'name',attrs['name'],
    #                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, 'xmin', str(int(attrs['bndbox'][0])),
                    bndbox_node)

    createChildNode(doc, 'ymin', str(int(attrs['bndbox'][1])),
                    bndbox_node)

    createChildNode(doc, 'xmax', str(int(attrs['bndbox'][0] + attrs['bndbox'][2])),
                    bndbox_node)

    createChildNode(doc, 'ymax', str(int(attrs['bndbox'][1] + attrs['bndbox'][3])),
                    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')
    # print(filename)
    fout = open(filename, 'w')
    # print(os.path.dirname(fout))

    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()


if __name__ == "__main__":
    ##讀取圖片列表
    img_path = "C:\\Users\\Administrator\\Desktop\\FLIR_ADAS_1_3\\train\\traindata\\"
    fileList = os.listdir(img_path)
    if fileList == 0:
        os._exit(-1)

    f=open("C:\\Users\\Administrator\\Desktop\\FLIR_ADAS_1_3\\train\\annptations.json", "r")
    ann_data = json.load(f)

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

    #if notos.path.exists(_ANNOTATION_SAVE_PATH):
     #   os.mkdir(_ANNOTATION_SAVE_PATH)

        # if notos.path.exists(_IMAGE_COPY_PATH):
    #    os.mkdir(_IMAGE_COPY_PATH)

    for imageName in fileList:
        print(imageName)
        saveName = imageName.strip(".jpeg")
        print(saveName)

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

        img = cv2.imread(os.path.join(img_path, imageName))
        print(os.path.join(img_path, imageName))
        # cv2.imshow(img)
        height, width, channel = img.shape
        print(height, width, channel)



        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 ann in ann_data:
            imgName = "FLIR_" + str(ann["filename"])
            cname = saveName;
            if (saveName == imgName):
                # object節點
                object_node = createObjectNode(doc, ann)
                root_node.appendChild(object_node)
            else:
                continue

            # 構建XML文件名稱

        print(xml_file_name)
        writeXMLFile(doc, xml_file_name)

# 創建XML文件

# createXMLFile(attrs, width,height, xml_file_name)

# # 寫入文件
#

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章