其他分享
首页 > 其他分享> > 批量修改VOC格式xml中box的大小

批量修改VOC格式xml中box的大小

作者:互联网

"""
function of the code: resize_box

author@bjtu_huangyuxiang
"""
from __future__ import division
import os
import xml.dom.minidom as xdm

def resize_box(AnnoPath,OutPath):

    files = os.listdir(AnnoPath)
    i = 0
    for xmlfile in files:
        DomTree = xdm.parse(AnnoPath+xmlfile)
        root = DomTree.documentElement #获得xml文档对象
        objectlist = root.getElementsByTagName('object') #获得xml文档目标名称

        for objects in objectlist:
            bndbox = objects.getElementsByTagName('bndbox')
            for box in bndbox:
                x1_list = box.getElementsByTagName('xmin')
                y1_list = box.getElementsByTagName('ymin')
                x2_list = box.getElementsByTagName('xmax')
                y2_list = box.getElementsByTagName('ymax')
                xmin = int(x1_list[0].childNodes[0].data)
                ymin = int(y1_list[0].childNodes[0].data)
                xmax = int(x2_list[0].childNodes[0].data)
                ymax = int(y2_list[0].childNodes[0].data)
            "下列四行代码是调整后坐标值与未调整前的坐标关系"
            x1min = xmin+0.25*(xmax-xmin)
            y1min = ymin+0.25*(ymax-ymin)
            x1max = xmin+0.7*(xmax-xmin)
            y1max = ymin+0.75*(ymax-ymin)

            x1_list[0].childNodes[0].data = int(x1min)
            y1_list[0].childNodes[0].data = int(y1min)
            x2_list[0].childNodes[0].data = int(x1max)
            y2_list[0].childNodes[0].data = int(y1max)
            if not os.path.exists(OutPath):
                os.makedirs(OutPath)
            save_file = OutPath + xmlfile
            with open(save_file,'w') as newxml:
                DomTree.writexml(newxml)
                print("{}重写入完成".format(xmlfile))
        i += 1
    print("共计修改%s个xml文件" % i)

"-----------------------main function-------------------------"
if __name__ == "__main__":
    AnnoPath = r'D:\desktop\hat_test\xml/'
    OutPath = r'D:\desktop\hat_test\newxml/'
    resize_box(AnnoPath, OutPath)

标签:xml,box,VOC,int,list,__,childNodes,data
来源: https://blog.csdn.net/weixin_46716951/article/details/122380056