12、OpenCV Python 图像梯度

时间:2024-06-10 10:06:44
 __author__ = "WSX"
import cv2 as cv
import numpy as np def lapalian_demo(image): #拉普拉斯算子
#dst = cv.Laplacian(image, cv.CV_32F) #内置函数来实现
#lpls = cv.convertScaleAbs(dst)
kernel = np.array([[1, 1, 1], [1, -8, 1], [1, 1, 1]]) #自定义来实现
dst = cv.filter2D(image, cv.CV_32F, kernel=kernel)
lpls = cv.convertScaleAbs(dst)
cv.imshow("lapalian_demo", lpls) def sobel_demo(image): #sobel算子
grad_x = cv.Scharr(image, cv.CV_32F, 1, 0) #x的一阶导数
grad_y = cv.Scharr(image, cv.CV_32F, 0, 1)
gradx = cv.convertScaleAbs(grad_x) # 先绝对值 再转到8位图像上
grady = cv.convertScaleAbs(grad_y)
cv.imshow("gradient-x", gradx) #左右有差异的表现
cv.imshow("gradient-y", grady) #上下有差异的表现
gradxy = cv.addWeighted(gradx, 0.5, grady, 0.5, 0) #一起表现
cv.imshow("gradient", gradxy) def main():
img = cv.imread("1.JPG")
cv.namedWindow("Show", cv.WINDOW_AUTOSIZE)
cv.imshow("Show", img)
sobel_demo(img) cv.waitKey(0)
cv.destroyAllWindows() main()