1. 程式人生 > >opencv的Canny邊緣檢測

opencv的Canny邊緣檢測

前言:
目標:

  • 理解Canny邊緣檢測
  • OpenCV函式的學習cv2.Canny()

Canny演算法原理


Canny是一個非常受歡迎的邊緣檢測演算法,主要分為四步的過程:

  1. 去噪
    邊緣對噪聲敏感,第一步先用高斯濾波器來濾波。
  2. 尋找影象的密度梯度
    對平滑後的影象進行濾波用sobel濾波器來求出x,y方向的導數。
    梯度方向總是垂直於邊緣
  3. 非極大值抑制
    在得到梯度的值和方向後,對影象進行全面掃描,取出不需要的畫素,這些畫素可能不構成邊緣。對於這一點如果畫素是其梯度方向上鄰域的最大值,如果是,則考慮下一個,如果不是,則將值抑制,設定為0。
  4. 滯後閾值法
  5. 這個階段決定哪些是邊哪些不是邊。因此我們需要兩個閾值minval和maxval。大於maxval的一定是邊,小於minval的一定不是邊,居於兩者中間的則進一步考察其連通性來確定是否為邊緣。
    如圖所示:
    在這裡插入圖片描述

opencv中的用法


Finds edges in an image,尋找一個影象中的邊緣。

cv2.Canny(image, threshold1, threshold2[, edges[, apertureSize[, L2gradient]]])

\rightarrow edges

  • image – 8-bit input image.
  • edges – output edge map; single channels 8-bit image, which has the same size as image .
  • threshold1 – first threshold for the hysteresis procedure.
  • threshold2 – second threshold for the hysteresis procedure.
  • apertureSize – aperture size for the Sobel() operator.
  • L2gradient – a flag, indicating whether a more accurate L2 norm =p(dI=dx)2 + (dI=dy)2 should be used to calculate the image gradient magnitude (L2gradient=true ), or whether the default L1 norm = jdI=dxj + jdI=dyj is enough (L2gradient=false ).