欢迎访问宙启技术站
智能推送

使用Python的draw_bounding_box_on_image()函数在图像上绘制边界线

发布时间:2024-01-04 06:00:10

draw_bounding_box_on_image()函数是TensorFlow Object Detection API中的一个函数,用于在图像上绘制边界框。它可以接受一张图像、边界框的坐标和标签,并将边界框绘制在图像上。

以下是一个使用draw_bounding_box_on_image()函数的示例:

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

# 载入图像
image_path = 'image.jpg'
image = tf.io.read_file(image_path)
image = tf.image.decode_jpeg(image)

# 定义边界框坐标和标签
boxes = [[0.1, 0.1, 0.4, 0.4], [0.5, 0.5, 0.7, 0.7]]  # 边界框坐标,每个边界框为[x_min, y_min, x_max, y_max]
labels = ['car', 'person']  # 边界框标签
colors = ['r', 'b']  # 边界框颜色

# 在图像上绘制边界框
def draw_bounding_boxes_on_image(image, boxes, labels, colors):
    for box, label, color in zip(boxes, labels, colors):
        ymin, xmin, ymax, xmax = box
        im_height, im_width, _ = image.shape
        (left, right, top, bottom) = (xmin * im_width, xmax * im_width,
                                      ymin * im_height, ymax * im_height)
        image = cv2.rectangle(image, (int(left), int(top)), (int(right), int(bottom)), color, 2)
        image = cv2.putText(image, label, (int(left), int(top - 10)), cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, 2)

    return image

# 绘制边界框
output_image = draw_bounding_boxes_on_image(image.numpy(), boxes, labels, colors)

# 显示图像
plt.figure(figsize=(10, 10))
plt.imshow(output_image)
plt.axis('off')
plt.show()

在这个示例中,首先需要载入一张图像,然后定义边界框的坐标和标签。接下来,通过调用draw_bounding_boxes_on_image()函数,在图像上绘制边界框。最后,使用Matplotlib库显示绘制好边界框的图像。

绘制边界框的过程主要涉及到计算边界框在图像中的具体位置,并使用OpenCV库的函数进行绘制操作。首先,需要将边界框的坐标值转换为图像中对应的像素值,然后使用OpenCV的rectangle()函数绘制矩形边界框,并使用putText()函数添加边界框的标签。

以上是使用Python的draw_bounding_box_on_image()函数在图像上绘制边界线的一个示例。你可以根据自己的需求调整边界框的坐标、标签和颜色,并使用该函数在图像上绘制出你想要的边界框。