dst = cv.blur(image,(5,5)) # (5,5)卷积核大小
用途:适用于随机噪声
dst = cv.medianBlur(image,5)
用途:适用于椒盐噪声
kernel = np.ones([5,5],np.float32)/25 # 除以25防止数值超过255,溢出
dst = cv.filter2D(image,-1,kernel=kernel)
用途:用户根据需要,自定义,灵活性好
kernel = np.array([[0,-1,0],[-1,5,-1],[0,-1,0]],np.float32) #使用了图像的锐化算子
dst = cv.filter2D(image,-1,kernel=kernel)
cv.imshow('sharp_demo',dst)
用途:用于图像增强,突出边框特征
下面是代码演示
import cv2 as cv
import numpy as np
# 均值模糊,可以去燥,对随机噪声效果好
def blur_demo(image):
dst = cv.blur(image,(5,5)) # (5,5)卷积核大小
cv.imshow('blur',dst)
# 中值模糊,对椒盐噪声效果好
def median_blur_demo(image):
dst = cv.medianBlur(image,5)
cv.imshow("median_blue",dst)
# 自定义
def custom_blur_demo(image):
kernel = np.ones([5,5],np.float32)/25 # 除以25防止数值超过255,溢出
dst = cv.filter2D(image,-1,kernel=kernel)
cv.imshow('custom_blur',dst)
# 利用自定义模糊,实现图像的锐化
def sharp_demo(image):
kernel = np.array([[0,-1,0],[-1,5,-1],[0,-1,0]],np.float32)
dst = cv.filter2D(image,-1,kernel=kernel)
cv.imshow('sharp_demo',dst)
src = cv.imread('D:/images/lenanoise.png')
cv.imshow('input image',src)
blur_demo(src)
median_blur_demo(src)
custom_blur_demo(src)
sharp_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()
运行效果
带有权重的均值模糊,是均值模糊的一种扩展。去噪的效果更好。
高斯模糊对高斯噪声有明显的抑制作用
看下面的代码
import cv2 as cv
import numpy as np
# 方式溢出
def clamp(pv):
if pv>255:
return 255
if pv<0:
return 0
else:
return pv
def gaussian_noise(image):
h,w,c = image.shape
for row in range(h):
for col in range(w):
s = np.random.normal(0,20,3)
b = image[row,col,0]
g = image[row,col,1]
r = image[row,col,2]
image[row,col,0] = clamp(b + s[0])
image[row,col,1] = clamp(g + s[1])
image[row,col,2] = clamp(r + s[2])
cv.imshow('guassian_nosie_image',image)
src = cv.imread('D:/images/demo.png')
cv.imshow('input image',src)
dst = cv.GaussianBlur(src,(0,0),15)
cv.imshow('Gaussian_blur',dst)
# 加入高斯噪声
t1 = cv.getTickCount()
gaussian_noise(src)
t2 = cv.getTickCount()
print('time consume:%.2fs'%((t2-t1)/cv.getTickFrequency()))
# 对加入高斯噪声后的图像进行高斯模糊
cv.imshow('Gaussian_blur_after_GaussNoise',cv.GaussianBlur(src,(5,5),0))
cv.waitKey(0)
cv.destroyAllWindows()
运行结果
time consume:2.49s
时间消耗的挺长的