使用draw_bounding_box_on_image()函数在Python中绘制图像边界框
发布时间:2024-01-04 05:59:19
在Python中,可以使用draw_bounding_box_on_image()函数来绘制图像边界框。该函数有几个参数,包括图像、边界框列表、类别标签列表、边界框颜色和字体颜色。以下是一个例子,演示如何使用draw_bounding_box_on_image()函数在Python中绘制图像边界框。
首先,我们需要安装必要的库。在Python中,可以使用pip来安装所需的库。我们将安装PIL库(Python Imaging Library)来处理图像,并安装matplotlib库用于显示图像和绘制边界框。可以在终端或命令提示符中运行以下命令来安装这些库:
pip install pillow pip install matplotlib
一旦安装完这些库,我们可以开始编写代码。下面是一个例子,演示如何使用draw_bounding_box_on_image()函数在Python中绘制图像边界框:
import matplotlib.pyplot as plt
from PIL import Image
from PIL import ImageDraw
def draw_bounding_box_on_image(image, boxes, labels, color=(255, 0, 0), font_color=(255, 255, 255)):
draw = ImageDraw.Draw(image)
for box, label in zip(boxes, labels):
ymin, xmin, ymax, xmax = box
im_width, im_height = image.size
(left, right, top, bottom) = (xmin * im_width, xmax * im_width,
ymin * im_height, ymax * im_height)
draw.line([(left, top), (left, bottom), (right, bottom),
(right, top), (left, top)], width=2, fill=color)
text_width, text_height = draw.textsize(label)
draw.rectangle([(left, top - text_height), (left + text_width, top)], fill=color)
draw.text((left, top - text_height), label, fill=font_color)
return image
# 读取图像
image_path = 'image.jpg'
image = Image.open(image_path)
# 边界框列表
boxes = [(0.1, 0.1, 0.4, 0.4), (0.6, 0.6, 0.9, 0.9)]
# 类别标签列表
labels = ['Object A', 'Object B']
# 绘制边界框
image_with_boxes = draw_bounding_box_on_image(image, boxes, labels)
# 显示图像
plt.imshow(image_with_boxes)
plt.axis('off')
plt.show()
在上面的例子中,我们首先导入了必要的库,然后定义了一个draw_bounding_box_on_image()函数,该函数使用了ImageDraw模块提供的方法来绘制边界框和文本。然后,我们读取了一个图像,并定义了边界框列表和类别标签列表。接下来,我们调用draw_bounding_box_on_image()函数来绘制图像边界框,并将结果显示出来。
最后,我们使用plt.imshow()函数显示绘制了边界框的图像,并使用plt.axis('off')函数隐藏坐标轴。最后,使用plt.show()函数来显示图像。
