Skip to content

Instantly share code, notes, and snippets.

@stoensin
Created February 28, 2019 15:13
Show Gist options
  • Save stoensin/9e0b4406c088660b89a5e709df745b4e to your computer and use it in GitHub Desktop.
Save stoensin/9e0b4406c088660b89a5e709df745b4e to your computer and use it in GitHub Desktop.
均值滤波器:在滑窗的过程中,计算窗口内像素的平均值,用这个平均值来代替锚点的像素值,遍历过后,图像的纹理信息减弱,噪声减弱,图像变得平滑。 高斯滤波是一种线性平滑滤波,适用于消除高斯噪声,广泛应用于图像处理的减噪过程。通俗的讲,高斯滤波就是对整幅图像进行加权平均的过程,每一个像素点的值,都由其本身和邻域内的其他像素值经过加权平均后得到。高斯滤波的具体操作是:用一个模板(或称卷积、掩模)扫描图像中的每一个像素,用模板确定的邻域内像素的加权平均灰度值去替代模板中心像素点的值。 中值滤波在图像处理中,常用于保护边缘信息,是经典的平滑噪声的方法。 双边滤波器能够在平滑图像(降噪)的同时,还能保留明显的边缘信息.ps的磨皮、人物卡通化都是通过双边滤波实现的
import cv2
import numpy as np
image = cv2.imread('./trex.png')
image_blur = np.hstack( # 均值滤波器结果图像的水平拼接
[cv2.blur(image, (3, 3)), # kernel_size为3×3
cv2.blur(image, (5, 5)),
cv2.blur(image, (7, 7))] # 能够看到图像变得越来越模糊
)
cv2.imwrite('blur_of_diff_size.jpg', image_blur)
image_gaussian = np.hstack([
cv2.GaussianBlur(image, (3, 3), 0),
cv2.GaussianBlur(image, (5, 5), 0),
cv2.GaussianBlur(image, (7, 7), 0) # 可以看出效果没有均值滤波模糊的那么厉害
])
cv2.imwrite('blur_of_diff_gaussian_size.jpg', image_gaussian)
def make_sp_noise(image, ratio):
"""人为的为图像添加椒盐噪声,ratio规定了噪声点占全局像素的比例"""
h, w = image.shape[:2]
image_copy = image.copy()
nums = int(h * w * ratio) # 椒盐噪声点占比
for i in range(nums):
row = np.random.randint(0, h)
col = np.random.randint(0, w)
if i % 2 == 0:
image_copy[row, col] = 255
else:
image_copy[row, col] = 0
return image_copy
image_with_sp = make_sp_noise(image, 0.7)
cv2.imwrite('image_with_sp.jpg', image_with_sp)
image_mid_blur = np.hstack([
cv2.medianBlur(image_with_sp, 3), #中值滤波 在图像处理中,常用于保护边缘信息,是经典的平滑噪声的方法
cv2.medianBlur(image_with_sp, 5),
cv2.medianBlur(image_with_sp, 7) # 邻域越大,过滤椒盐噪声效果越好,但是图像质量也会下降明显。除非非常密集椒盐噪声,否则不推荐Ksize=7这么大的卷积核
])
cv2.imwrite('image_remove_noise.jpg', image_mid_blur)
# 对比:高斯滤波对滤除椒盐噪声
image_gaussian_compare = np.hstack([
cv2.GaussianBlur(image_with_sp, (3, 3), 0),
cv2.GaussianBlur(image_with_sp, (5, 5), 0),
cv2.GaussianBlur(image_with_sp, (7, 7), 0)
])
cv2.imwrite('image_remove_noise_compare.jpg', image_gaussian_compare)
image = cv2.imread('./beach.png')
image_bilater = np.hstack([
cv2.bilateralFilter(image, 5, 21, 21),# 双边滤波器:ps的磨皮、人物卡通化都是通过双边滤波实现的
cv2.bilateralFilter(image, 7, 31, 31),
cv2.bilateralFilter(image, 9, 41, 41)
])
cv2.imwrite('image_bilater.jpg', image_bilater)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment