使用Python的draw_bounding_box_on_image()函数在图像上绘制框
发布时间:2024-01-04 05:58:23
draw_bounding_box_on_image()是TensorFlow Object Detection API中的一个函数,用于在图像上绘制带有边界框的物体。它接受图像、边界框的坐标和类别标签作为输入,并返回带有绘制框的图像。
首先,你需要安装TensorFlow Object Detection API。接下来,我们将演示如何使用draw_bounding_box_on_image()函数在图像上绘制框。
首先,导入所需的库:
import numpy as np import tensorflow as tf from object_detection.utils import visualization_utils as viz_utils from PIL import Image
然后,定义一个函数来加载图像和边界框的坐标:
def load_image_and_bounding_boxes(image_path, boxes):
image_np = np.array(Image.open(image_path))
boxes_np = np.array(boxes)
return image_np, boxes_np
下一步是加载预训练模型和标签映射表:
# 载入训练好的模型
detection_model = tf.saved_model.load('path/to/pretrained/model')
# 加载标签映射表
label_map = {1: 'person', 2: 'car', 3: 'cat', ...}
然后,定义一个函数来绘制边界框:
def draw_bounding_box_on_image(image, boxes, classes):
image_with_boxes = image.copy()
viz_utils.visualize_boxes_and_labels_on_image_array(
image_with_boxes,
boxes,
classes,
np.ones_like(classes, dtype=np.int32),
label_map,
use_normalized_coordinates=True,
max_boxes_to_draw=None,
min_score_thresh=0.4,
agnostic_mode=False)
return image_with_boxes
接下来,加载图像和边界框的坐标:
image_path = 'path/to/image.jpg' boxes = [[0.1, 0.2, 0.4, 0.6], [0.5, 0.3, 0.7, 0.8]] # 边界框坐标,列表中的每个元素对应一个边界框的左上角和右下角坐标 image, boxes = load_image_and_bounding_boxes(image_path, boxes)
最后,使用draw_bounding_box_on_image()函数绘制边界框并显示图像:
image_with_boxes = draw_bounding_box_on_image(image, boxes, classes) Image.fromarray(image_with_boxes).show()
这将显示包含绘制框的图像。可以根据需要调整绘制的边界框的样式和参数,如最小置信度阈值、最大绘制框数量等。
以上是使用Python的draw_bounding_box_on_image()函数在图像上绘制框的简单示例。TensorFlow Object Detection API提供了许多有用的函数和工具,可以帮助我们进行物体检测和图像分析任务。
