要在使用 Pillow Python 库中的“draw_vertices”函数绘制对象边框时向图像添加显示文本,我们可以遵循分步过程。此过程包括从 Google Vision API 检索检测到的对象的顶点,使用顶点绘制对象边框,最后将显示文本添加到图像中。
1. 检索检测到的物体的顶点:
– 利用 Google Vision API 检测图像中的对象。
– 从 API 响应中提取每个检测到的对象的顶点。顶点代表围绕对象的边界框的四个角。
2. 使用顶点绘制对象边框:
– 使用 Python 中的 Pillow 库加载图像。
– 从 Pillow 库创建 ImageDraw 模块的实例。
– 迭代每个对象的顶点并使用 ImageDraw 模块中的“draw.rectangle”函数绘制一个矩形。
– “draw.rectangle”函数将矩形的左上角和右下角的坐标作为参数。
3. 在图像中添加显示文本:
– 创建 ImageDraw 模块的另一个实例。
– 迭代每个对象的顶点并使用 ImageDraw 模块中的“draw.text”函数添加显示文本。
– “draw.text”函数将文本位置的坐标和文本字符串作为参数。
– 您可以通过在“draw.text”函数中指定附加参数来自定义文本的字体、大小、颜色和其他属性。
下面是一个示例代码片段,演示了上述过程:
python from PIL import Image, ImageDraw, ImageFont # Step 1: Retrieve the vertices of the detected objects # (Assuming you have already obtained the vertices from the Google Vision API) vertices = [ [(100, 100), (200, 100), (200, 200), (100, 200)], # Example vertices of object 1 [(300, 150), (400, 150), (400, 250), (300, 250)] # Example vertices of object 2 ] # Step 2: Draw object borders using the vertices image = Image.open("input_image.jpg") draw = ImageDraw.Draw(image) for vertex in vertices: draw.rectangle(vertex, outline="red") # Step 3: Add display text to the image font = ImageFont.truetype("arial.ttf", 12) text_draw = ImageDraw.Draw(image) for i, vertex in enumerate(vertices): text_position = vertex[0][0], vertex[0][1] - 20 text_draw.text(text_position, f"Object {i+1}", font=font, fill="red") # Save the modified image image.save("output_image.jpg")
在此示例中,我们假设已从 Google Vision API 获取了对象的顶点。然后,我们使用 Pillow 库加载图像,使用顶点绘制对象边框,并在每个对象上方添加显示文本。
请记住根据您的具体要求调整代码,例如字体、字体大小和文本颜色。
最近的其他问题和解答 使用枕头Python库绘制对象边框:
- 提供的代码中“draw.line”方法的参数是什么,以及如何使用它们在顶点值之间绘制线条?
- 如何使用pillow库在Python中绘制对象边框?
- 提供的代码中“draw_vertices”函数的用途是什么?
- Google Vision API 如何帮助理解图像中的形状和对象?
更多问题及解答:
- 领域: 人工智能
- 程序: EITC/AI/GVAPI Google Vision API (前往认证计划)
- 教训: 了解形状和物体 (去相关课程)
- 主题: 使用枕头Python库绘制对象边框 (转到相关主题)
- 考试复习