所有代码如下 :
# 不同算子的差异
import cv2
import numpy as np
def cv_show(img, name): # 图片展示
cv2.imshow(name, img)
cv2.waitKey()
cv2.destroyAllWindows()
# sobel
img = cv2.imread('lena.jpg', cv2.IMREAD_GRAYSCALE) # 读灰度图
sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3) # cv2.CV_64F表示可以读到更大的范围,包括负数
sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3)
sobelx = cv2.convertScaleAbs(sobelx) # cv2.convertScaleAbs()-->绝对值
sobely = cv2.convertScaleAbs(sobely)
sobelxy = cv2.addWeighted(sobelx, 0.5, sobely, 0.5, 0) # 0.5x + 0.5y *分别计算x,y再求和*
# scharr
scharrx = cv2.Scharr(img, cv2.CV_64F, 1, 0)
scharry = cv2.Scharr(img, cv2.CV_64F, 0, 1)
scharrx = cv2.convertScaleAbs(scharrx)
scharry = cv2.convertScaleAbs(scharry)
scharrxy = cv2.addWeighted(scharrx, 0.5, scharry, 0.5, 0)
# lpls
laplacian = cv2.Laplacian(img, cv2.CV_64F)
laplacian = cv2.convertScaleAbs(laplacian)
res = np.hstack((sobelxy, scharrxy, laplacian))
cv_show(res, 'res')
最终结果如下: