拥有原始照片以及相应的标注XML文件,使用OpenCV库来读取图片和XML文件,然后在图片上绘制标注的边界框,并保存。
格式信息

import cv2
import xml.etree.ElementTree as ET
def draw_boxes_on_image(image_path, annotation_path, output_path):
# 读取图片
image = cv2.imread(image_path)
# 确保图片被成功加载
if image is None:
print(f"Error: Image at {image_path} could not be loaded.")
return
# 解析XML文件
tree = ET.parse(annotation_path)
root = tree.getroot()
# 遍历所有的<object>元素
for obj in root.findall('object'):
# 找到<bndbox>元素
bndbox = obj.find('bndbox')
if bndbox is not None:
# 提取边界框坐标
xmin = int(bndbox.find('xmin').text)
ymin = int(bndbox.find('ymin').text)
xmax = int(bndbox.find('xmax').text)
ymax = int(bndbox.find('ymax').text)
# 提取类别名称
class_name = obj.find('name').text
# 在图片上绘制边界框
cv2.rectangle(image, (xmin, ymin), (xmax, ymax), (0, 255, 0), 2)
# 在边界框旁显示类别名称
cv2.putText(image, class_name, (xmin, ymin - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
# 保存带有边界框的图片
cv2.imwrite(output_path, image)
print(f"Annotated image saved to {output_path}")
# 图片和XML文件的路径
image_path = 'path/to/your/image.jpg'
annotation_path = 'path/to/your/annotation.xml'
# 输出图片的路径
output_path = 'path/to/your/annotated_image.jpg'
# 调用函数绘制边界框并保存图片
draw_boxes_on_image(image_path, annotation_path, output_path)
- 函数draw_boxes_on_image:该函数接收图片路径、XML标注文件路径和输出图片路径作为参数。
- 读取图片:使用cv2.imread从指定路径加载图片。
- 解析XML:使用xml.etree.ElementTree解析XML文件,并获取所有标注对象。
- 绘制边界框和类别名称:遍历每个标注对象,使用cv2.rectangle和cv2.putText在图片上绘制边界框和类别名称。
- 保存图片:使用cv2.imwrite将带有标注的图片保存到指定路径。
确保将image_path、annotation_path和output_path变量替换为实际的文件路径。运行脚本后,将在输出路径生成一张带有边界框和类别名称的图片。
290

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



