要在使用 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庫繪製對象邊框 (轉到相關主題)
- 考試複習