Laplacian滤波器实现并用于图像锐化
一. 拉普拉斯滤波器简介:
我们知道:
二. 3*3的laplacian滤波器实现
# laplacian filter def laplacian_filter(img, K_size=3): H, W = img.shape # zero padding pad = K_size // 2 out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float) out[pad: pad + H, pad: pad + W] = img.copy().astype(np.float) tmp = out.copy() # laplacian kernle K = [[0., 1., 0.],[1., -4., 1.], [0., 1., 0.]] # filtering for y in range(H): for x in range(W): out[pad + y, pad + x] = np.sum(K * (tmp[y: y + K_size, x: x + K_size])) out = np.clip(out, 0, 255) out = out[pad: pad + H, pad: pad + W].astype(np.uint8) return out
三. 利用laplacian滤波器实现图像的锐化
由于拉普拉斯是一种微分算子,它的应用可增强图像中灰度突变的区域,减弱灰度的缓慢变化区域。
因此,锐化处理可选择拉普拉斯算子对原图像进行处理,产生描述灰度突变的图像,再将拉普拉斯图像与原始图像叠加而产生锐化图像:
其中,f(x,y)为原始图像,g(x,y)为锐化后图像,c为-1(卷积核中间为负数时,若卷积核中间为正数,则c为1)。
四. 通过laplacian滤波器实现图像锐化 python源码
import cv2 import numpy as np # Image sharpening by laplacian filter def laplacian_sharpening(img, K_size=3): H, W = img.shape # zero padding pad = K_size // 2 out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float) out[pad: pad + H, pad: pad + W] = img.copy().astype(np.float) tmp = out.copy() # laplacian kernle K = [[0., 1., 0.],[1., -4., 1.], [0., 1., 0.]] # filtering and adding image -> Sharpening image for y in range(H): for x in range(W): # core code out[pad + y, pad + x] = (-1) * np.sum(K * (tmp[y: y + K_size, x: x + K_size])) + tmp[pad + y, pad + x] out = np.clip(out, 0, 255) out = out[pad: pad + H, pad: pad + W].astype(np.uint8) return out # Read Gray Scale image img = cv2.imread("../paojie_g.jpg",0).astype(np.float) # Image sharpening by laplacian filter out = laplacian_sharpening(img, K_size=3) # Save result cv2.imwrite("out.jpg", out) cv2.imshow("result", out) cv2.waitKey(0) cv2.destroyAllWindows()
五. 实验结果:
六. 参考内容