python实现xml文件中提取图片属性并保存为txt文件
·
在cv领域中对图片进行标注,保存的文件格式有可能是xml文件,可能还不能被模型直接使用,要经过代码处理提取特定属性值。
xml文件示例:
表示其中一张图片的名字和相关的属性值。
希望得到的文件格式:

前面是图片的路径或者名字,后面是图片带有的多属性。
上代码:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2022/8/12 17:00
# @Author : bess
# @File : popy_xml_txt.py
from xml.dom.minidom import parse
import os
# 将xml格式的文件转换为txt格式
#得到的图片是图片名字加其属性
# (可以一个xml文件里面包含所有的图片标注信息,也可以一个xml对应1张图片的标签信息)
def convert_annotation(xmlfilepath, train_path, test_path):
in_file = open(xmlfilepath, encoding='utf-8')
tree = parse(in_file)
root = tree.documentElement
out_file1 = open(train_path, 'w', encoding='utf-8') # 生成txt格式文件
out_file2 = open(test_path, 'w', encoding='utf-8') # 生成txt格式文件
# 获取所有images
images = root.getElementsByTagName("image")
i = 0
for image in images:
print(image)
# print('image',image.getAttribute("name").split("."))
#属性名字
# imagename = image.getAttribute("image").split(".")[0]
# print(name)
'''
<image id="0" name="034BC8BE773A031E982684AFF7C190A2_transcode_output_dashinit20210520 19h00m50s_120_upper.jpg" width="682" height="1000">
<tag label="color" source="manual">
<attribute name="color">multicolor</attribute>
</tag>
<tag label="silhouette" source="manual">
<attribute name="silhouette">loose silhouette</attribute>
</tag>
<tag label="texture" source="manual">
<attribute name="texture">pleats</attribute>
</tag>
<tag label="pattern" source="manual">
<attribute name="pattern">check</attribute>
</tag>
</image>
'''
#获得图片的名字
image_name = image.attributes['name'].value
# print('image_name',image_name)
#获得多个attribute列表
#这个方法返回一个节点的集合,这个集合可以当做一个数组来处理。这个集合的length属性等于当前文档里有着给定标签名的所有元素的总个数。
# 这个数组里面的每个元素都是一个对象,他们都有着nodeName、nodeType、parentNode、childNodes等属性。
attributes = image.getElementsByTagName("attribute")
# print('---attributes---',attributes)
attr_value = []
if i % 10 ==0:
#划分数据集为 验证集和数据集
for attribute in attributes:
#获得color的值
attr_text = attribute.firstChild.nodeValue
attr_value.append(attr_text)
out_file2.write(image_name + '\t' + ','.join(attr_value) + '\n')
else:
for attribute in attributes:
attr_text = attribute.firstChild.nodeValue
attr_value.append(attr_text)
out_file1.write(image_name + '\t' + ','.join(attr_value) + '\n')
i = i + 1
out_file1.close()
out_file2.close()
if __name__ == '__main__':
# xml文件夹
xmlpath = 'xml'
# txt文件
trian_path = 'popy_list/popy_train_list.txt'
test_path = 'popy_list/popy_test_list.txt'
# 读取xml文件夹下的所有xml文件
filelist = os.listdir(xmlpath)
for files in filelist:
# 获取每一个xml文件名
xmlfilepath = xmlpath + "/" + files
# 将每一个xml文件转换为txt
convert_annotation(xmlfilepath, trian_path, test_path)
这样就可以提取到xml中的图片属性。
豁达不是成全别人,豁达是放过自己,不争就是智慧。
——董宇辉

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)