例子源于OpenCV官网手册(https://docs.opencv.org/4.x/d5/db5/tutorial_laplace_operator.html)
使用OpenCV函数Laplacian()实现拉普拉斯算子的离散模拟。
该程序的功能:
加载一个图像
去除噪声应用高斯模糊,然后将原始图像转换为灰度
对灰度图像应用拉普拉斯算子并存储输出图像
在窗口中显示结果
代码:
"""
@file laplace_demo.py
@brief Sample code showing how to detect edges using the Laplace operator
"""
import sys
import cv2 as cv
def main(argv):#argv是sys模块下的方法用于接收命令行传参
# [variables]
# Declare the variables we are going to use(声明变量)
ddepth = cv.CV_16S#图像深度
kernel_size = 3#内核大小
window_name = "Laplace Demo"
# [variables]
# [load](加载图片)
imageName = argv[0] if len(argv) > 0 else 'lena.jpg'
src = cv.imread(cv.samples.findFile(imageName), cv.IMREAD_COLOR) # Load an image
# Check if image is loaded fine
if src is None:
print ('Error opening image')
print ('Program Arguments: [image_name -- default lena.jpg]')
return -1
# [load]
# [reduce_noise]
# Remove noise by blurring with a Gaussian filter(降噪)
src = cv.GaussianBlur(src, (3, 3), 0)#高斯滤波器对图像进行平滑处理
# [reduce_noise]
# [convert_to_gray]
# Convert the image to grayscale(变为灰度图)
src_gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
# [convert_to_gray]
# Create Window(创建窗口)
cv.namedWindow(window_name, cv.WINDOW_AUTOSIZE)
# [laplacian]
# Apply Laplace function(拉普拉斯算子)
dst = cv.Laplacian(src_gray, ddepth, ksize=kernel_size)
# [laplacian]
# [convert]
# converting back to uint8(将输出转换为CV_8U映像)
abs_dst = cv.convertScaleAbs(dst)
# [convert]
# [display](输出结果)
cv.imshow(window_name, abs_dst)
cv.waitKey(0)
# [display]
return 0
if __name__ == "__main__":
main(sys.argv[1:])
运行效果图:
原图:
拉普拉斯算子处理后: