如何使用 OpenCV Python 中的 Scharr 运算符查找图像梯度?
使用 Scharr 运算符,我们可以使用一阶导数计算水平和垂直方向的图像梯度。梯度是针对灰度图像计算的。您可以使用方法 cv2.scharr() 对图像应用 Scharr 操作。
语法
以下语法用于使用 Scharr 导数计算图像梯度 -
cv2.Scharr(img, ddepth, xorder, yorder)
参数
img - 原始输入图像
ddepth - 输出图像的所需深度。它包含有关输出图像中存储了哪种数据的信息。我们使用 cv2.CV_64F 作为 ddepth。它是一个 64 位浮点 opencv
xorder − 水平方向(X 方向)导数的阶数。设置 xorder=1,yorder=0 为 X 方向的一阶导数。
Yorder − 垂直方向(Y 方向)导数的阶数。设置 xorder=0,yorder=1 为 Y 方向的一阶导数。
步骤
您可以使用以下步骤使用 Scharr 导数查找图像梯度 −
导入所需的库。在以下所有 Python 示例中,所需的 Python 库都是 OpenCV。确保您已经安装了它。
import cv2
使用 cv2.imread() 将输入图像读取为灰度图像。
img = cv2.imread('lines.jpg',0)
使用 cv2.Scharr() 计算 Sobel 或 Laplacian 导数。该导数指的是图像梯度。
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"作为上述程序中的输入文件。
输出
上述程序执行后将产生以下两个输出窗口