XML(Extensible Markup Language,可扩展标记语言)是一种用于存储和传输数据的标记语言。它与HTML类似,但更加通用和灵活,可用于描述各种类型的数据结构。XML通过使用标签(tag)来表示数据的结构和含义,并使用属性(attribute)来提供关于数据的额外信息。
在计算机视觉领域通常用来存储的图像的标准信息,在PASCAL VOC格式的XML文件包括图像基本信息、对象类别、位置和属性等。在VOC2007中000001.xml信息如下:

其中包括图像各类标签:<source>包括图像的来源信息(数据库名称、注释类型及图像来源类型标识),<owner>所有者信息,<size>图片的尺寸信息,<object>图像的物体信息,也就是VOC2007的类以及<bndbox>类的边界框坐标信息。
如果要读取'000001.jpg'图片的‘000001.xml’文件,并显示图像和边界框。
from PIL import Image
import matplotlib.pyplot as plt
# 读取图像
image_path = '000001.jpg'
image = Image.open(image_path)
# 绘制图像
plt.imshow(image)
# plt.axis('off') # 关闭坐标轴
# 绘制边界框
# 这里假设边界框的坐标已经在XML文件中提供了
xmin, ymin, xmax, ymax = 48, 240, 195, 371
width = xmax - xmin
height = ymax - ymin
rect = plt.Rectangle((xmin, ymin), width, height, edgecolor='r', facecolor='none')
plt.gca().add_patch(rect)
xmin, ymin, xmax, ymax = 8, 12, 352, 498
width = xmax - xmin
height = ymax - ymin
rect = plt.Rectangle((xmin, ymin), width, height, edgecolor='b', facecolor='none')
plt.gca().add_patch(rect)
# 显示图像和边界框
plt.show()
显示如下

图中bound出两个类别:dog和person,并且分别显示边界框。
如果在图像中显示类别和边界框信息,对代码进行适当修改。
import xml.etree.ElementTree as ET
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# 解析XML文件
xml_file = '000001.xml'
tree = ET.parse(xml_file)
root = tree.getroot()
# 获取图像文件名
filename = root.find('filename').text
# 获取图像尺寸
size = root.find('size')
width = int(size.find('width').text)
height = int(size.find('height').text)
# 读取图像
image_path = filename
image = Image.open(image_path)
# 绘制图像
plt.imshow(image)
plt.axis('off') # 关闭坐标轴
# 获取并绘制边界框
for obj in root.findall('object'):
# 获取类别和边界框信息
obj_name = obj.find('name').text
bbox = obj.find('bndbox')
xmin = int(bbox.find('xmin').text)
ymin = int(bbox.find('ymin').text)
xmax = int(bbox.find('xmax').text)
ymax = int(bbox.find('ymax').text)
width = xmax - xmin
height = ymax - ymin
# 绘制边界框
rect = patches.Rectangle((xmin, ymin), width, height, linewidth=1, edgecolor='r', facecolor='none')
plt.gca().add_patch(rect)
plt.text(xmin, ymin - 5, obj_name, color='r', fontsize=8, ha='left', va='top')
# 显示图像和边界框
plt.show()
显示如下

若是想生成自己的xml文件,可以选择Labellmg、LabelMe、CVAT等工具。

标定后保存便能够生成自己的xml文件存储图像的相关信息。
184

被折叠的 条评论
为什么被折叠?



