在Python中使用draw_bounding_box_on_image()绘制图像中的边界样式
发布时间:2024-01-04 06:02:48
在Python中,我们可以使用TensorFlow提供的draw_bounding_box_on_image()函数来绘制图像中的边界框样式。这个函数可以帮助我们在图像中绘制边界框,以便更好地展示目标的位置。
以下是一个示例代码,演示了如何使用draw_bounding_box_on_image()函数绘制边界框:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
def draw_bounding_box_on_image(image, ymin, xmin, ymax, xmax, color='red', thickness=2, display_str_list=()):
"""Draws a bounding box on an image.
Args:
image: Image numpy array.
ymin: ymin of bounding box.
xmin: xmin of bounding box.
ymax: ymax of bounding box.
xmax: xmax of bounding box.
color: Color of bounding box. Default is red.
thickness: Thickness of bounding box lines. Default is 2.
display_str_list: List of strings to display on or next to the bounding box.
"""
img_height, img_width, _ = image.shape
ymin = int(ymin * img_height)
ymax = int(ymax * img_height)
xmin = int(xmin * img_width)
xmax = int(xmax * img_width)
cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, thickness)
cv2.putText(
image,
' '.join(display_str_list),
(xmin, ymin),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
color,
thickness=1,
lineType=cv2.LINE_AA
)
return image
# 读取图像
image = plt.imread('path_to_image.jpg')
# 随机生成一个边界框
ymin = np.random.random()
xmin = np.random.random()
ymax = ymin + np.random.random() * (1-ymin)
xmax = xmin + np.random.random() * (1-xmin)
# 绘制边界框
image_with_bbox = draw_bounding_box_on_image(image, ymin, xmin, ymax, xmax, thickness=1, display_str_list=['object'])
# 显示图像和边界框
plt.imshow(image_with_bbox)
plt.axis('off')
plt.show()
这个例子做了以下几件事情:
1. 步是导入所需的库,包括tensorflow、numpy和matplotlib。
2. 然后定义了一个draw_bounding_box_on_image()函数,它接受一个图像和一个边界框的坐标以及其他一些参数,然后在图像上绘制边界框。
3. 接下来,使用plt.imread()函数读取一个图像,这里需要将'path_to_image.jpg'替换为实际图像的路径。
4. 然后,我们随机生成一个边界框的坐标,这里使用numpy的random()函数来随机生成0和1之间的随机数,并根据图像的高度和宽度来计算边界框的坐标。
5. 最后,我们调用draw_bounding_box_on_image()函数来绘制边界框,并传入绘制的颜色、边界框的线条宽度和显示字符串列表等参数。
6. 最后,使用plt.imshow()和plt.show()函数来显示带有边界框的图像。
这是一个简单的使用draw_bounding_box_on_image()函数绘制图像中边界框的例子。你可以根据需要修改函数的参数和图像的路径来绘制不同的边界框样式。
