如何使用OpenCV Python在影像中檢測三角形?


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

for cnt in contours:
   approx = cv2.approxPolyDP()
   if len(approx) == 3:
      cv2.drawContours()
      cv2.putText("Triangle")

步驟

您可以使用以下步驟在輸入影像中檢測三角形:

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

import cv2

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

img = cv2.imread('approx1.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

對灰度影像應用閾值處理以建立二值影像。調整第二個引數以獲得更好的輪廓檢測。

ret,thresh = cv2.threshold(gray,50,255,0)

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

contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

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

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

approx = cv2.approxPolyDP(cnt,epsilon,True)

如果近似輪廓approx中的頂點數量為3,則在影像上繪製輪廓並將其設定為三角形。

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

cv2.imshow("Shapes", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

讓我們來看一些例子以便更好地理解。

示例1

在下面的Python程式碼中,我們檢測輸入影像中的三角形。

# import required libraries import cv2 # read the input image img = cv2.imread('shapes.jpg') # 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) if len(approx) == 3: img = cv2.drawContours(img, [cnt], -1, (0,255,255), 3) # compute the center of mass of the triangle M = cv2.moments(cnt) if M['m00'] != 0.0: x = int(M['m10']/M['m00']) y = int(M['m01']/M['m00']) cv2.putText(img, 'Triangle', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 2) cv2.imshow("Shapes", img) cv2.waitKey(0) cv2.destroyAllWindows()

我們將在上面的程式程式碼中使用以下影像作為輸入檔案

輸出

執行上述程式碼時,它將在控制檯上產生以下輸出

Number of contours detected: 4

並且我們得到以下視窗,顯示輸出

在上面的輸出影像中,檢測到一個三角形。

示例2

在這個例子中,我們將展示如何檢測影像中的多個三角形。

import cv2 import numpy as np img = cv2.imread('shapes1.jpg') img1 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(img1,150,255,0) contours,hierarchy = cv2.findContours(thresh, 1, 2) print("Number of contours detected:",len(contours)) for cnt in contours: approx = cv2.approxPolyDP(cnt, 0.1*cv2.arcLength(cnt, True), True) if len(approx) == 3: img = cv2.drawContours(img, [cnt], -1, (0,255,255), 3) M = cv2.moments(cnt) if M['m00'] != 0.0: x = int(M['m10']/M['m00']) y = int(M['m01']/M['m00']) cv2.putText(img, 'Triangle', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 2) cv2.imshow("Triangles", img) cv2.waitKey(0) cv2.destroyAllWindows()

我們將在本程式中使用以下影像作為輸入檔案

輸出

執行上述程式碼時,它將在控制檯上產生以下輸出

Number of contours detected: 6

並且我們得到以下視窗,顯示輸出

在上面的輸出影像中,我們檢測到四個三角形。

更新於:2022年9月28日

5K+瀏覽量

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告