如何使用OpenCV Python在影像中檢測多邊形?


我們首先檢測影像中所有物體的輪廓以檢測多邊形。然後迴圈遍歷所有輪廓。找到每個輪廓的近似輪廓。如果近似輪廓中的頂點數量為5個或更多,則繪製輪廓並將其設定為三角形。請參見下面的虛擬碼。

for cnt in contours:
   approx = cv2.approxPolyDP()
   if len(approx) >= 5:
      cv2.drawContours()
      cv2.putText("Polygon")

步驟

我們可以使用以下步驟在影像中檢測多邊形:

  • 匯入所需的庫。在以下所有示例中,所需的Python庫是OpenCV。確保您已安裝它。

  • 使用cv2.imread()讀取輸入影像並將其轉換為灰度影像。

  • 在灰度影像上應用閾值cv2.threshold()以建立二值影像。調整第二個引數以獲得更好的輪廓檢測。

  • 使用cv2.findContours()函式查詢影像中的輪廓。

  • 從輪廓列表中選擇一個輪廓(例如第一個輪廓)cnt。或者迴圈遍歷所有檢測到的輪廓。

  • 使用cv2.approxPolyDP()函式計算每個輪廓cnt的近似輪廓點(approx)。

  • 如果近似輪廓approx中的頂點總數為5個或更多,則在影像上繪製近似輪廓並將其設定為多邊形。

  • 顯示繪製了輪廓和近似輪廓的影像。

讓我們來看下面的示例以便更好地理解。

示例

在這個Python程式中,我們檢測輸入影像中的多邊形。我們還繪製了檢測到的多邊形的輪廓。

# import required libraries import cv2 # read the input image img = cv2.imread('polygons.png') # convert the image to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # apply thresholding to convert the grayscale image to a binary image ret,thresh = cv2.threshold(gray,50,255,0) # find the contours contours,hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) print("Number of contours detected:",len(contours)) for cnt in contours: approx = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt, True), True) (x,y)=cnt[0,0] if len(approx) >= 5: img = cv2.drawContours(img, [approx], -1, (0,255,255), 3) cv2.putText(img, 'Polygon', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 2) cv2.imshow("Polygon", img) cv2.waitKey(0) cv2.destroyAllWindows()

我們將使用以下影像作為此程式的輸入檔案


執行上述Python程式後,它將生成以下輸出視窗:

Number of contours detected: 3

我們將得到以下輸出視窗:


更新於:2022年12月5日

5K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.