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来计算,结果如下:
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()
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()