OpenCV-Python之影象梯度
阿新 • • 發佈:2018-12-22
- Sobel運算元對應一階導數
- Laplace運算元對應二階導數
Sobel運算元(Schar)
import cv2 as cv
def sobel_demo(image):
grad_x = cv.Sobel(image, cv.CV_32F, 1, 0) # 使用CV_32F防止資料溢位
grad_y = cv.Sobel(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)
# 合併x, y兩個梯度
addImage = cv.addWeighted(gradx, 0.5, grady, 0.5, 0)
cv.imshow('add image', addImage)
src = cv.imread('./data/lena.jpg', 1)
sobel_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()
仔細觀察三張圖不難發現,X方向梯度在Y方向上邊緣較為清晰,而Y方向梯度在X方向上邊緣較為清晰,合併後的影象則綜合了兩張圖的特徵。如果邊緣輪廓不清晰或不理想可以考慮用Scarr來計算,結果如下:
Laplace運算元
def Laplace_demo(image):
dst = cv.Laplacian(image, cv.CV_32F)
laps = cv.convertScaleAbs(dst)
cv.imshow('Laplace image', laps)
src = cv.imread('./data/lena.jpg', 1)
Laplace_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()
藉助filter2D()函式自定義掩模計算Laplace演算法
def Laplace_demo (image):
# dst = cv.Laplacian(image, cv.CV_32F)
# laps = cv.convertScaleAbs(dst)
kernel = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]])
dst = cv.filter2D(image, cv.CV_32F, kernel=kernel)
laps = cv.convertScaleAbs(dst)
cv.imshow('Laplace image', laps)
src = cv.imread('./data/lena.jpg', 1)
Laplace_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()
幾乎上上圖一樣,改變核為[[1,1,1],[1,-8,1],[1,1,1]]再觀察
影象增強了