python 处理dlib xml文件格式

该博客介绍如何使用Python解析和处理dlib的XML文件。通过`xml.dom.minidom`,`xml.etree.cElementTree`,`lxml.etree`等库,读取XML文件,获取图像信息,并创建新的XML注解。代码示例展示了如何获取图像路径,读取图像,以及生成新的XML对象,包括边界框坐标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#coding=utf-8
import  xml.dom.minidom
import xml.etree.cElementTree as ET
from lxml import etree, objectify
import cv2
import os
def trasnform(old_path,new_path,image_path):
    #image_path_list = os.listdir(image_path)
    dom = xml.dom.minidom.parse(old_path)
    #得到文档元素对象
    root = dom.documentElement
    itemlist = root.getElementsByTagName('image')
    for item in itemlist[:]:
        name=item.getAttribute("file")
        print(image_path+'/'+name[:-4]+'.jpg')
        image = cv2.imread(image_path+'/'+name[:-4]+'.jpg')
        if image is None:
            continue
        gao,kuan,shendu = image.shape
        #print un
        ii = item.getElementsByTagName('box')
        top1 =[]
        left1 =[]
        width1 = []
        height1 =[]
        for i in ii:
            
            top=i.getAttribute("top")
            top1.append(top)
            left=i.getAttribute("left")
            left1.append(left)
            width=i.getAttribute("width")
            width1.append(width)
            height=i.getAttribute("height")
            height1.append(height)
            print top,left,width,height
        E = objectify.ElementMaker(annotate=False)
        anno_tree = E.annotation(
        E.filename(name),
        E.size(
            E.height(gao),
            E.width(kuan),
            E.depth(shendu)))
        
            
        for i in range(len(top1)):
            print(left1[i])
            print(width1[i])
            #print(left1[i]+width1[i])
            anno_tree2 =E.object(
            E.name('car'),
            E.label('1'),
            E.ignore('0'),
            E.bndbox(
            E.xmin(left1[i]),
            E.ymin(top1[i]),
            E.xmax(str(int(left1[i])+int(width1[i]))),
            E.ymax(str(int(top1[i])+int(height1[i])))))
            anno_tree.append(anno_tree2)
    
        file_name = new_path+ '/'  + name[0 : -4] + ".xml"
        print(file_name)
        etree.ElementTree(anno_tree).write(file_name, pretty_print=True)
old_path = r"/home/huran/workspace/shell/dlib_front_and_rear_vehicles_v1/training.xml"
new_path = r"/home/huran/workspace/shell/dlib_front_and_rear_vehicles_v1"
image_path = r"/home/huran/workspace/shell/dlib_front_and_rear_vehicles_v1"
trasnform(old_path,new_path,image_path)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值