繪制多邊形¶
概要¶
講解了如何使用OpenCV在圖片中繪制多邊形.
keywords OpenCV 多邊形繪制
多邊形繪制(cv2.polylines)¶
多邊形繪制的這個函數比較特殊, 傳入的點集需要滿足的條件為:維度是N×1×2
類似這樣:
[[[100 50]] [[200 300]] [[700 200]] [[500 100]]]
cv2.polylines(img=canvas, pts=[points], isClosed=True, color=(0,0,255), thickness=3)
參數說明
-
img
畫布 -
pts
點集 -
isClosed
是否閉合 , 如果是閉合的話, 就將第一個與最后一個鏈接起來。 -
color
顏色 -
thickness
寬度, 如果是-1就會填充(如果是閉合圖像的話)
演示例程
src/draw_polygon.py
''' 繪制多邊形 ''' import cv2 import numpy as np # 初始化一個空畫布 1000×500 三通道 背景色為白色 canvas = np.ones((500, 1000, 3), dtype="uint8") canvas *= 255 # 初始化點集 points = np.array([[100,50],[200,300],[700,200],[500,100]], np.int32) # 點集矩陣變形 points = points.reshape((-1,1,2)) print("points after reshape") # RESHAPE TO N*1*2 print(points) ''' [[[100 50]] [[200 300]] [[700 200]] [[500 100]]] ''' ''' pts : 點集數組 isClosed: 多邊形是否閉合 color: 顏色 thickness: 線條寬度 ''' cv2.polylines(canvas, pts=[points], isClosed=True, color=(0,0,255), thickness=3) cv2.imshow("polylines", canvas) cv2.imwrite("polylines.png", canvas) cv2.waitKey(0)