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}

猜你喜欢

转载自blog.csdn.net/qq_28485501/article/details/85258364