在Python中利用draw_bounding_box_on_image()函数绘制图像的边界线
发布时间:2024-01-04 06:00:29
在Python中,可以使用draw_bounding_box_on_image()函数来绘制图像的边界线。这个函数通常用于目标检测和边界框可视化任务中。以下是一个使用例子,展示如何在Python中使用draw_bounding_box_on_image()函数绘制图像的边界线。
首先,我们需要导入必要的库。使用tensorflow库来访问draw_bounding_box_on_image()函数,使用matplotlib库来显示图像。
import tensorflow as tf import matplotlib.pyplot as plt
然后,我们需要载入一张图像,并创建一个边界框的列表。每个边界框都是一个包含边界框位置信息的四元组(ymin, xmin, ymax, xmax)。
image_path = "image.jpg" image = tf.io.read_file(image_path) image = tf.image.decode_image(image) # 创建边界框列表 boxes = [(0.1, 0.2, 0.3, 0.4), (0.5, 0.6, 0.7, 0.8)]
接下来,我们使用draw_bounding_box_on_image()函数在图像上绘制边界线,并将结果保存到一个新的图像中。
# 在图像上绘制边界线
with tf.Session() as sess:
image_with_boxes = tf.image.draw_bounding_boxes(
tf.expand_dims(image, 0), [boxes]).eval()
# 将结果保存到新的图像中
output_path = "image_with_boxes.jpg"
with tf.io.gfile.GFile(output_path, "wb") as f:
f.write(image_with_boxes[0])
最后,我们可以使用matplotlib库显示原始图像和绘制了边界线的图像。
# 显示原始图像
plt.subplot(1, 2, 1)
plt.imshow(image)
plt.title("Original Image")
# 显示绘制了边界线的图像
plt.subplot(1, 2, 2)
plt.imshow(image_with_boxes[0])
plt.title("Image with Boxes")
# 显示图像
plt.show()
上述代码中,我们首先使用tf.image.draw_bounding_boxes()函数将边界框绘制在图像上,然后将结果保存到新的图像中。最后,我们使用plt.imshow()函数显示原始图像和绘制了边界线的图像。
通过上述例子,我们可以利用draw_bounding_box_on_image()函数在Python中绘制图像的边界线。它是一个非常实用的函数,在目标检测和边界框可视化任务中非常有用。
