如何在 OpenCV Python 中使用 Sobel 和 Laplacian 導數查詢影像梯度?


使用 Sobel 運算元,我們可以計算水平和垂直方向的影像梯度。梯度是針對灰度影像計算的。拉普拉斯運算元使用二階導數計算梯度。

語法

以下語法用於使用 Sobel 和 Laplacian 導數計算影像梯度:

cv2.Sobel(img, ddepth, xorder, yorder, ksize)
cv2.Laplacian(img, ddepth)

引數

  • img − 原始輸入影像。

  • ddepth − 輸出影像的所需深度。它包含有關輸出影像中儲存的資料型別的資訊。我們使用 cv2.CV_64F 作為 ddepth。它是一個 64 位浮點 OpenCV。

  • xorder − 水平方向(X 方向)的導數階數。對於 X 方向的一階導數,設定 xorder=1yorder=0

  • yorder − 垂直方向(Y 方向)的導數階數。對於 Y 方向的一階導數,設定 xorder=0,yorder=1。

  • ksize − 核大小。對於 5×5 核大小,設定 ksize=5。

步驟

您可以使用以下步驟使用 Sobel 和 Laplacian 導數查詢影像梯度:

匯入所需的庫。在以下所有 Python 示例中,所需的 Python 庫是 OpenCV。確保您已安裝它。

import cv2

使用 cv2.imread() 讀取輸入影像作為灰度影像。

img = cv2.imread('lines.jpg',0)

使用 cv2.Sobel()cv2.Laplacian() 計算 Sobel 或 Laplacian 導數。此導數指的是影像梯度。

sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)

使用 cv2.imshow() 方法顯示影像梯度。

cv2.imshow("Sobel X", sobelx)
cv2.waitKey(0)
cv2.destroyAllWindows()

我們將在以下示例中使用此影像作為輸入檔案

示例 1

在下面的 Python 程式中,我們使用 X 和 Y 方向(分別為水平和垂直)的一階 Sobel 導數計算影像梯度。我們使用 5×5 的核大小。

# import required libraries import cv2 import numpy as np from matplotlib import pyplot as plt # read the input image as a grayscale image img = cv2.imread('lines.jpg',0) # compute the 1st order Sobel derivative in X-direction sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5) # compute the 1st order Sobel derivative in Y-direction sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=5) # display sobelx and sobely cv2.imshow("Sobel X", sobelx) cv2.waitKey(0) cv2.imshow("Sobel Y", sobely) cv2.waitKey(0) cv2.destroyAllWindows()

輸出

執行上述程式時,它將生成以下兩個輸出視窗。Sobel X 視窗顯示 X 方向(水平)的導數,Sobel Y 視窗顯示 Y 方向(垂直)的導數。

示例 2

在下面的 Python 程式中,我們使用 Laplacian 導數計算影像梯度。

# import required libraries import cv2 import numpy as np from matplotlib import pyplot as plt # read the input image as a grayscale image img = cv2.imread('lines.jpg',0) # compute Laplacian derivative of the input image laplacian = cv2.Laplacian(img,cv2.CV_64F) # display the laplacian cv2.imshow("Laplacian", laplacian) cv2.waitKey(0) cv2.destroyAllWindows()

輸出

執行上述程式時,它將生成以下輸出視窗

更新於: 2022-09-27

2K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.