OpenCV Python - 影像輪廓



輪廓是指連線邊界上所有連續點的一條曲線,這些點具有相同的顏色或強度。輪廓對於形狀分析和物體檢測非常有用。

查詢輪廓

在查詢輪廓之前,我們應該應用閾值或 Canny 邊緣檢測。然後,透過使用 **findContours()** 方法,我們可以在二值影像中找到輪廓。

**findContours()** 函式的使用命令如下:

cv.findContours(image, mode, method, contours)

引數

**findContours()** 函式的引數如下:

  • image - 源影像,一個 8 位單通道影像。
  • mode - 輪廓檢索模式。
  • method - 輪廓近似方法。

mode 引數的值如下:

  • **cv.RETR_EXTERNAL** - 只檢索最外層的輪廓。

  • **cv.RETR_LIST** - 檢索所有輪廓,但不建立任何層次關係。

  • **cv.RETR_CCOMP** - 檢索所有輪廓,並將它們組織成兩級層次結構。

  • **cv.RETR_TREE** - 檢索所有輪廓,並重建巢狀輪廓的完整層次結構。

另一方面,近似方法可以是以下之一:

  • **cv.CHAIN_APPROX_NONE** - 儲存所有輪廓點。

  • **cv.CHAIN_APPROX_SIMPLE** - 壓縮水平、垂直和對角線段,只保留它們的端點。

繪製輪廓

在檢測到輪廓向量後,可以使用 **cv.drawContours()** 函式在原始影像上繪製輪廓。

cv.drawContours() 函式的命令如下:

cv.drawContours(image, contours, contourIdx, color)

引數

**drawContours()** 函式的引數如下:

  • image - 目標影像。
  • contours - 所有輸入輪廓。每個輪廓都儲存為一個點向量。
  • contourIdx - 指示要繪製的輪廓的引數。如果為負數,則繪製所有輪廓。
  • color - 輪廓的顏色。

示例

以下程式碼是在具有三個填充黑色形狀的輸入影像上繪製輪廓的示例。

第一步,我們獲取灰度影像,然後執行 Canny 邊緣檢測。

在結果影像上,我們然後呼叫 findContours() 函式。其結果是一個點向量。然後我們呼叫 drawContours() 函式。

完整的程式碼如下:

import cv2
import numpy as np

img = cv2.imread('shapes.png')
cv2.imshow('Original', img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

canny = cv2.Canny(gray, 30, 200)

contours, hierarchy = cv2.findContours(canny,
   cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
print("Number of Contours = " ,len(contours))
cv2.imshow('Canny Edges', canny)

cv2.drawContours(img, contours, -1, (0, 255, 0), 3)

cv2.imshow('Contours', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

輸出

原始影像、經過 Canny 邊緣檢測後的影像以及繪製了輪廓的影像將分別顯示在不同的視窗中,如下所示:

separate windows

經過 **Canny 邊緣檢測** 後,影像如下所示:

canny edge detection

經過 **繪製輪廓** 後,影像如下所示:

contours are drawn
廣告

© . All rights reserved.