1. 程式人生 > >opencv-影象梯度(gradient)

opencv-影象梯度(gradient)

前言:
目標:

  • 尋找影象的梯度,邊緣等
  • 學習cv2.Sobel(),cv2.Scharr(),cv2.Laplacian()

Opencv有三種梯度濾波器或者說是高通濾波器,它們分別是:Sobel,Scharr,Laplacian。

Sobel Derivatives(導數)

cv2.Sobel(src, ddepth, dx, dy[, dst[, ksize[, scale[, delta[, borderType]]]]])

\rightarrow dst

  • src – input image.

  • dst – output image of the same size and the same number of channels as src .

  • ddepth – output image depth; the following combinations of src.depth() and ddepth are supported:
    – src.depth() = CV_8U, ddepth = -1/CV_16S/CV_32F/CV_64F
    – src.depth() = CV_16U/CV_16S, ddepth = -1/CV_32F/CV_64F
    – src.depth() = CV_32F, ddepth = -1/CV_32F/CV_64F
    – src.depth() = CV_64F, ddepth = -1/CV_64F
    when ddepth=-1, the destination image will have the same depth as the source; in the case of 8-bit input images it will result in truncated derivatives.

  • xorder – order of the derivative x.

  • yorder – order of the derivative y.

  • ksize – size of the extended Sobel kernel; it must be 1, 3, 5, or 7.

  • scale – optional scale factor for the computed derivative values; by default, no scaling is applied (see getDerivKernels() for details).

  • delta – optional delta value that is added to the results prior to storing them in dst.

  • borderType – pixel extrapolation method (see borderInterpolate() for details).

  • ddepth的取值,主要是影象的深度。
    注意一點的是如果我們的畫素資料型別為cv2.CV_8U或者np.uint8,這種資料型別是由黑色向白色變換的是正斜率,而白色向黑絲變換的是負斜率。所以在得到的梯度影象時,會有正數和負數之分。
    如果你想儲存這兩種變化得到的梯度,最好使用更高階的形式,比如cv2.CV_16S,cv2.CV_64F等等,取其絕對值然後將其轉換為cv2.CV_8U就可以了。見下面的例子:
    在這裡插入圖片描述

img = cv2.imread('box.png',0)
'單邊灰度變換的邊緣檢測'
sobelx8u = cv2.Sobel(img,cv2.CV_8U,1,0,ksize=3)
'雙邊灰度變換的梯度檢驗'
sobelx64f = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)
abs_sobel64f = np.absolute(sobelx64f)
sobel_8u = np.uint8(abs_sobel64f)

Laplacian Derivatives

拉普拉斯導數,其數學公式為: s r c = 2 s r c x 2 + 2 s r c y 2 \triangle src = \frac{\partial^2 src}{\partial x^2} + \frac{\partial^2 src}{\partial y^2}
如果ksize = 1,則核為:
k = [ 0 1 0 1 4 1 0 1 0 ] k = \begin{bmatrix} 0 &1 &0 \\ 1& -4 &1 \\ 0&1 &0 \end{bmatrix}