两种不同风格的lxml标注文件的解析:pet和Lara_UrbanSeq1_Traffic Light

2024-02-12 04:32

本文主要是介绍两种不同风格的lxml标注文件的解析:pet和Lara_UrbanSeq1_Traffic Light,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1. pet数据集标注样式

以Abyssinian_12.xml为例,文件内容如下:

<annotation><folder>OXIIIT</folder><filename>Abyssinian_12.jpg</filename><source><database>OXFORD-IIIT Pet Dataset</database><annotation>OXIIIT</annotation><image>flickr</image></source><size><width>335</width><height>500</height><depth>3</depth></size><segmented>0</segmented><object><name>cat</name><pose>Frontal</pose><truncated>0</truncated><occluded>0</occluded><bndbox><xmin>94</xmin><ymin>83</ymin><xmax>211</xmax><ymax>190</ymax></bndbox><difficult>0</difficult></object>
</annotation>

分析可知,其节点全部为tag:text形式,每个tag不包含attrib。因此,参照Object Detection API官方,采用以下方式来进行递归读取,返回一个包含多层级字典结构的数据。

import numpy as np
import PIL.Image
import tensorflow as tf
from lxml import etreefrom object_detection.dataset_tools import tf_record_creation_util
from object_detection.utils import dataset_util
from object_detection.utils import label_map_utilxml_path = "./Annotations/Abyssinian_12.xml"
# xml_path = "./Annotations/Lara_test.xml"with tf.gfile.GFile(xml_path, 'r') as fid:xml_str = fid.read()xml = etree.fromstring(xml_str)
#     xml = etree.fromstring(xml_str.encode('utf-8'))data = dataset_util.recursive_parse_xml_to_dict(xml)['annotation']
#     data = dataset_util.recursive_parse_xml_to_dict(xml)print(data)
#     for item in data:
#         print(type(item))

其中调用的函数recursive_parse_xml_to_dict(xml)如下:

def recursive_parse_xml_to_dict(xml):"""Recursively parses XML contents to python dict.We assume that `object` tags are the only ones that can appearmultiple times at the same level of a tree.Args:xml: xml tree obtained by parsing XML file contents using lxml.etreeReturns:Python dictionary holding XML contents."""if not xml:return {xml.tag: xml.text}result = {}for child in xml:child_result = recursive_parse_xml_to_dict(child)if child.tag != 'object':result[child.tag] = child_result[child.tag]else:if child.tag not in result:result[child.tag] = []result[child.tag].append(child_result[child.tag])return {xml.tag: result}

2. Lara标注样式

Lara交通标志数据集的标注文件将所有的图片文件信息整合在一个文件中,截取一段如下:

<?xml version="1.0" encoding="UTF-8"?>
<dataset name="Lara_UrbanSeq1" version="0.5" comments="Public database: http://www.lara.prd.fr/benchmarks/trafficlightsrecognition"><frame number="6695" sec="487" ms="829"><objectlist><object id="18"><orientation>90</orientation><box h="39" w="18" xc="294" yc="34"/><appearance>appear</appearance><hypothesislist><hypothesis evaluation="1.0" id="1" prev="1.0"><type evaluation="1.0">Traffic Light</type><subtype evaluation="1.0">go</subtype></hypothesis></hypothesislist></object><object id="19"><orientation>90</orientation><box h="15" w="6" xc="518" yc="123"/><appearance>appear</appearance><hypothesislist><hypothesis evaluation="1.0" id="1" prev="1.0"><type evaluation="1.0">Traffic Light</type><subtype evaluation="1.0">go</subtype></hypothesis></hypothesislist></object><object id="20"><orientation>90</orientation><box h="15" w="6" xc="382" yc="122"/><appearance>appear</appearance><hypothesislist><hypothesis evaluation="1.0" id="1" prev="1.0"><type evaluation="1.0">Traffic Light</type><subtype evaluation="1.0">go</subtype></hypothesis></hypothesislist></object></objectlist><grouplist></grouplist></frame>
</dataset>

可见其主要信息都包含在tag:attrib中,是难以用递归函数来实现解析的。
对该文件进行单独测试如下:

# 测试解析xml文件
# examples_path = os.path.join(annotations_dir, 'trainval.txt')
# examples_list = dataset_util.read_examples_list(examples_path)
# xml_path = "./Annotations/Lara_UrbanSeq1_GroundTruth_cvml.xml"
# tree = ET.parse(xml_path)
# root = tree.getroot()
# print(root.tag)
# print(root.attrib)
# print(root[11178].tag)
# print(root[11178].attrib)
# print(root[11178][0][0].tag)
# print(root[11178][0][0].attrib)
# for frame in root.findall("./frame")
# for obj in root[11178][0][0]:
#     print(obj.attrib)
#     print(obj.tag)

主要实现代码如下:

# 从xml文件解析出数据,以list形式返回。每个list的item都是包含相关信息的一个dict
def get_data_list(xml_path, label_map_dict):"""Function: parse xml to a list of image data, every item contain a dict of image name, size, and a list of objects.Args:xml_path: the path to the xml fileReturns:data_list: a list of data, every data is a dict contain keys.{   'filename': 'frame_006630.jpg', 'size':    {'width': 640, 'height': 480}, 'object':  [ {'bndbox': {'xmin': 368, 'xmax': 378, 'ymin': 94, 'ymax': 116}}, {'bndbox': {'xmin': 563, 'xmax': 571, 'ymin': 103, 'ymax': 123}}]}"""tree = ET.parse(xml_path)root = tree.getroot()data_list = []for frame in root.findall('./frame'):frame_number = int(frame.get("number"))img_name = "frame_{0:06d}.jpg".format(frame_number) # 得到第一个字段,文件名data = dict()data['filename']=img_nameimg_size = dict()img_size['width']=640img_size['height']=480data['size']=img_sizeobject_list=[]data['object']=object_listfor obj in frame.findall('./objectlist/object'): # 得到该帧里的每个objectobject = dict()# 这里待验证。暂时仍用读到的字符串,而没有转换为数字class_name = obj.find('./hypothesislist/hypothesis/subtype').text
#             classes_text.append(class_name.encode('utf-8'))
#             classes.append(label_map_dict[class_name])object['class_text'] = class_nameobject['class_id'] = label_map_dict[class_name]obj_h = int(obj.find('box').get("h"))    obj_w = int(obj.find('box').get("w"))obj_xc = int(obj.find('box').get("xc"))obj_yc = int(obj.find('box').get("yc"))xmin = obj_xc-int(obj_w//2)if xmin<0:xmin=0xmax = obj_xc+int(obj_w//2)ymin = obj_yc-int(obj_h//2)if ymin<0:ymin=0ymax = obj_yc+int(obj_h//2)bndbox = dict()            bndbox['xmin'] = xminbndbox['xmax'] = xmaxbndbox['ymin'] = yminbndbox['ymax'] = ymaxobject['bndbox'] = bndboxobject_list.append(object)data_list.append(data)return data_list

3. 主要对比

前者使用lxml.etree,后者使用xml.etree.ElementTree。解析过程不同。

这篇关于两种不同风格的lxml标注文件的解析:pet和Lara_UrbanSeq1_Traffic Light的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/701668

相关文章

解析 XML 和 INI

XML 1.TinyXML库 TinyXML是一个C++的XML解析库  使用介绍: https://www.cnblogs.com/mythou/archive/2011/11/27/2265169.html    使用的时候,只要把 tinyxml.h、tinystr.h、tinystr.cpp、tinyxml.cpp、tinyxmlerror.cpp、tinyxmlparser.

echarts省份标注加散点效果

这个是安徽的效果图,鼠标移到红色标注或者对应的市区位置都会显示对应的数值。 先直接上代码: import anhuiMapJson from './anhui.json'getCoords: function(city) {var res = [];if (city != null) {for (var c in this.cityMap.features) {if (this.cityMa

tf.split()函数解析

API原型(TensorFlow 1.8.0): tf.split(     value,     num_or_size_splits,     axis=0,     num=None,     name='split' ) 这个函数是用来切割张量的。输入切割的张量和参数,返回切割的结果。  value传入的就是需要切割的张量。  这个函数有两种切割的方式: 以三个维度的张量为例,比如说一

【第十三课】区域经济可视化表达——符号表达与标注

一、前言 地图最直接的表达就是使用符号表达。使用符号可以把简单的点线面要 素渲染成最直观的地理符号,提高地图的可读性。只要掌握了 ArcGIS 符号制 作的技巧,分析符号并总结出规则,就可以制作符合要求的地图+符号。 (一)符号的选择与修改 符号的选择在制图中至关重要,使用符号选择器对话框可从多个可用样式 中选择符号,并且每个符号都有一个标签用来描述其图形特征,如颜色或类型, 利用这些标签可

气象站的种类和应用范围可以根据不同的分类标准进行详细的划分和描述

气象站的种类和应用范围可以根据不同的分类标准进行详细的划分和描述。以下是从不同角度对气象站的种类和应用范围的介绍: 一、气象站的种类 根据用途和安装环境分类: 农业气象站:专为农业生产服务,监测土壤温度、湿度等参数,为农业生产提供科学依据。交通气象站:用于公路、铁路、机场等交通场所的气象监测,提供实时气象数据以支持交通运营和调度。林业气象站:监测林区风速、湿度、温度等气象要素,为林区保护和

陀螺仪LSM6DSV16X与AI集成(8)----MotionFX库解析空间坐标

陀螺仪LSM6DSV16X与AI集成.8--MotionFX库解析空间坐标 概述视频教学样品申请源码下载开启CRC串口设置开启X-CUBE-MEMS1设置加速度和角速度量程速率选择设置FIFO速率设置FIFO时间戳批处理速率配置过滤链初始化定义MotionFX文件卡尔曼滤波算法主程序执行流程lsm6dsv16x_motion_fx_determin欧拉角简介演示 概述 本文将探讨

【文末附gpt升级秘笈】腾讯元宝AI搜索解析能力升级:千万字超长文处理的新里程碑

腾讯元宝AI搜索解析能力升级:千万字超长文处理的新里程碑 一、引言 随着人工智能技术的飞速发展,自然语言处理(NLP)和机器学习(ML)在各行各业的应用日益广泛。其中,AI搜索解析能力作为信息检索和知识抽取的核心技术,受到了广泛的关注和研究。腾讯作为互联网行业的领军企业,其在AI领域的探索和创新一直走在前列。近日,腾讯旗下的AI大模型应用——腾讯元宝,迎来了1.1.7版本的升级,新版本在AI搜

消息认证码解析

1. 什么是消息认证码         消息认证码(Message Authentication Code)是一种确认完整性并进行认证的技术,取三个单词的首字母,简称为MAC。         消息认证码的输入包括任意长度的消息和一个发送者与接收者之间共享的密钥,它可以输出固定长度的数据,这个数据称为MAC值。         根据任意长度的消息输出固定长度的数据,这一点和单向散列函数很类似

问题1,PE文件转到内存中出现解析PE不正确的问题

1,使用fopen(FileName, “r”) r的方式读取文件到内存,此时就可能存在问题了,r以只读方式,有时候不表示字符的有可能就不读了,那么内存中就不会是完整的原始文件。所以此时要采用rb,二进制读取的方式。 bool ReadFileToMem(char* FileName, char**buf) { FILE* f; f = fopen(FileName, “rb”); if