Python script------Merge and rename xml files of different categories

1. Merge xml files of different categories

import cv2
import numpy as np
import os
import xml.etree.ElementTree as ET
from xml.dom import minidom
import matplotlib.pyplot as plt

CLASSES_NAMES=['C1','W','G1','S1','S2', 'LC1']

def get_class_names(CLASSES_NAMES):
    """
    return a dict, as following,
        {'pottedplant': 0,
         'sheep': 1,
         'bird': 2,
         'dog': 3,
         'bottle': 4,
         'boat': 5,
         ......
        }
    """
    object_category2id = {
   
    
    }
    for i, item in enumerate(CLASSES_NAMES):
        object_category2id[item] = i
    return object_category2id

#获取类别对应标签id,输出为字典,通过类别名称获取id,如:cname2cid[‘bird’]=2
cname2cid=get_class_names(CLASSES_NAMES)

def write_xml():
    annotation = ET.Element("annotation")
    filename = ET.Element("filename")
    filename.text='CRH2A-2309-14-22.jpg'
    size=ET.Element("size")
    width=ET.Element("width")
    width.text=str(2000)
    height=ET.Element("height")
    height.text=str(2048)
    depth = ET.Element("depth")
    depth.text = str(3)
    size.extend([width,height,depth])
    annotation.extend([filename,size])
    #=======object_start=======
    #=====循环这部分代码加入不同目标的标注信息========
    #===需要更改的变量:name xmin ymin xmax ymax
    object=ET.Element("object")
    name=ET.Element("name")
    name.text='class_1'
    pose=ET.Element("pose")
    pose.text='Unspecified'
    truncated=ET.Element("truncated")
    truncated.text=str(0)
    difficult=ET.Element("difficult")
    difficult.text=str(0)
    bndbox=ET.Element("bndbox")
    xmin=ET.Element("xmin")
    xmin.text=str(1147)
    ymin=ET.Element("ymin")
    ymin.text=str(1199)
    xmax=ET.Element("xmax")
    xmax.text=str(1503)
    ymax=ET.Element("ymax")
    ymax.text=str(1617)
    bndbox.extend([xmin,ymin,xmax,ymax])
    object.extend([name, pose, truncated, difficult,bndbox])
    #=======object_end=======
    annotation.append(object)
    # tree = ET.ElementTree(annotation)
    # tree.write("output.xml", encoding="utf-8", xml_declaration=True)  #保存时无缩进,添加缩进需要借用dom


    #借用dom,添加缩进
    rawtext = ET.tostring(annotation)
    dom = minidom.parseString(rawtext)
    with open("output.xml", "w") as f:
        dom.writexml(f, indent="",addindent="  ", newl="\n", encoding="utf-8")

    # tree = ET.ElementTree(annotation)
    # tree.write("output.xml", encoding="utf-8", xml_declaration=True)  #保存时无缩进,添加缩进需要借用dom


    #借用dom,添加缩进
    rawtext = ET.tostring(annotation)
    dom = minidom.parseString(rawtext)
    with open("output.xml", "w") as f:
        dom.writexml(f, indent="",addindent="  ", newl="\n", encoding="utf-8")

def WriteObjectsToXml(ObjDict, save_path):


    annotation = ET.Element("annotation")
    filename = ET.Element("filename")
    filename.text = ObjDict

Guess you like

Origin blog.csdn.net/m0_47405013/article/details/129384209