微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

批量修改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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。