## Python+OpenCV：图像梯度

Python OpenCV 梯度 图像 python+opencv

### 理论

OpenCV提供了三种类型的梯度滤波器或高通滤波器，Sobel, Scharr和Laplacian。

1. Sobel和Scharr导数

Sobel算子是一种联合高斯平滑加微分运算，具有较强的抗噪声能力。

2. Laplacian导数

### 示例

``````####################################################################################################
"""

"""
# 读取图像
image = lmc_cv.cvtColor(image, lmc_cv.COLOR_BGR2GRAY)
laplacian_image = lmc_cv.Laplacian(image, lmc_cv.CV_64F, ksize=3, scale=1, delta=0,
borderType=lmc_cv.BORDER_DEFAULT)
sobelx_image = lmc_cv.Sobel(image, lmc_cv.CV_64F, 1, 0, ksize=5, scale=1, delta=0,
borderType=lmc_cv.BORDER_DEFAULT)
sobely_image = lmc_cv.Sobel(image, lmc_cv.CV_64F, 0, 1, ksize=5, scale=1, delta=0,
borderType=lmc_cv.BORDER_DEFAULT)
# 显示图像
pyplot.figure('Image Display')
titles = ['Original', 'Laplacian', 'Sobel X', 'Sobel Y']
images = [image, laplacian_image, sobelx_image, sobely_image]
for i in range(4):
pyplot.subplot(2, 2, i + 1)
pyplot.imshow(images[i], 'gray')
pyplot.title(titles[i])
pyplot.xticks([])
pyplot.yticks([])
pyplot.show()
# 根据用户输入保存图像
if ord("q") == (lmc_cv.waitKey(0) & 0xFF):
# 销毁窗口
pyplot.close()
return``````

### 强调

``````####################################################################################################
# 正负梯度(Positive-Negative slope)
def lmc_cv_positive_negative_slope():
"""

"""
# 读取图像
image = lmc_cv.cvtColor(image, lmc_cv.COLOR_BGR2GRAY)
# 正负梯度(Positive-Negative slope)
# Output dtype = cv.CV_8U
sobelx8u_image1 = lmc_cv.Sobel(image, lmc_cv.CV_8U, 1, 0, ksize=5, scale=1, delta=0,
borderType=lmc_cv.BORDER_DEFAULT)
# Output dtype = cv.CV_64F. Then take its absolute and convert to cv.CV_8U
sobelx64f_image = lmc_cv.Sobel(image, lmc_cv.CV_64F, 1, 0, ksize=5, scale=1, delta=0,
borderType=lmc_cv.BORDER_DEFAULT)
abs_sobel64f_image = np.absolute(sobelx64f_image)
sobelx8u_image2 = np.uint8(abs_sobel64f_image)
# 显示图像
pyplot.figure('Image Display')
titles = ['Original', 'Sobel CV_8U', 'Sobel abs(CV_64F)']
images = [image, sobelx8u_image1, sobelx8u_image2]
for i in range(3):
pyplot.subplot(1, 3, i + 1)
pyplot.imshow(images[i], 'gray')
pyplot.title(titles[i])
pyplot.xticks([])
pyplot.yticks([])
pyplot.show()
# 根据用户输入保存图像
if ord("q") == (lmc_cv.waitKey(0) & 0xFF):
# 销毁窗口
pyplot.close()
return``````

https://blog.csdn.net/liubing8609/article/details/109695123