如何在OpenCV Python中使用Scharr算子查找图像梯度?
使用Scharr算子,我们可以使用一阶导数计算水平和垂直方向的图像梯度。梯度是针对灰度图像计算的。您可以使用cv2.scharr()方法对图像应用Scharr运算。
语法
使用Scharr导数计算图像梯度使用的语法如下:
cv2.Scharr(img, ddepth, xorder, yorder)
参数
img - 原始输入图像
ddepth - 期望的输出图像深度。它包含关于输出图像中存储的数据类型的信息。我们使用cv2.CV_64F作为ddepth。它是一个64位浮点opencv类型。
xorder - 水平方向(X方向)的导数阶数。对于X方向的一阶导数,设置xorder=1,yorder=0。
yorder - 垂直方向(Y方向)的导数阶数。对于Y方向的一阶导数,设置xorder=0,yorder=1。
步骤
您可以使用以下步骤使用Scharr导数查找图像梯度:
导入所需的库。在所有以下Python示例中,所需的Python库是OpenCV。确保您已安装它。
import cv2
使用cv2.imread()读取输入图像作为灰度图像。
img = cv2.imread('lines.jpg',0)
使用cv2.Scharr()计算Sobel或拉普拉斯导数。此导数指的是图像梯度。
scharrx = cv2.Scharr(img,cv2.CV_64F,1,0)
使用cv2.imshow()方法显示图像梯度。
cv2.imshow("Scharr X", scharrx)
cv2.waitKey(0)
cv2.destroyAllWindows()
让我们来看一些例子,以便更清楚地理解。
示例1
在下面的Python示例中,我们使用Scharr算子在X(水平)和Y(垂直)方向上计算图像梯度。
# import required libraries import cv2 # read the input image as a grayscale image img = cv2.imread('window.jpg',0) # compute the 1st order Sobel derivative in x direction scharrx = cv2.Scharr(img,cv2.CV_64F,1,0) # compute the 1st order Sobel derivative in y direction scharry = cv2.Scharr(img,cv2.CV_64F,0,1) # display scharrx and scharry cv2.imshow("Scharr X", scharrx) cv2.waitKey(0) cv2.imshow("Scharr Y", scharry) cv2.waitKey(0) cv2.destroyAllWindows()
我们将在上述程序中使用图像“window.jpg”作为输入文件。

输出
执行上述程序后,它将生成以下两个输出窗口:“Scharr X”和“Scharr Y”。


示例2
在下面的Python示例中,我们使用Scharr算子在X(水平)和Y(垂直)方向上计算图像梯度。
# import required libraries import cv2 # read the input image as a grayscale image img = cv2.imread('tutorialspoint.png',0) # compute the 1st order Sobel derivative in x direction scharrx = cv2.Scharr(img,cv2.CV_64F,1,0) # compute the 1st order Sobel derivative in y direction scharry = cv2.Scharr(img,cv2.CV_64F,0,1) # display scharrx and scharry cv2.imshow("Scharr X", scharrx) cv2.waitKey(0) cv2.imshow("Scharr Y", scharry) cv2.waitKey(0) cv2.destroyAllWindows()
我们将在上述程序中使用图像“tutorialspoint.png”作为输入文件。

输出
上述程序执行后将生成以下两个输出窗口。


广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP