本博客针对某一原始图片添加高斯或椒盐噪声,再使用均值、中值、高斯和双边滤波对加噪图像进行去噪,相关函数如下所示。
添加高斯噪声
def clamp(pv):
if pv > 255:
return 255
if pv < 0:
return 0
else:
return pv
def gaussian_noise(image):
image_ori = image.copy()
h, w, c = image.shape
for row in range(h):
for col in range(w):
s = np.random.normal(0, 20, 3)
# s = np.random.normal(0, 60, 3)
b = image[row, col, 0] # blue
g = image[row, col, 1] # green
r = image[row, col, 2] # red
image[row, col, 0] = clamp(b + s[0])
image[row, col, 1] = clamp(g + s[1])
image[row, col, 2] = clamp(r + s[2])
cv2.imwrite('gaussian_noise_picture.png', image)
return image
添加椒盐噪声
def sp_noise(image):
prob = 0.01
output = np.zeros(image.shape,np.uint8)
thres = 1 - prob
for i in range(image.shape[0]):
for j in range(image.shape[1]):
rdn = random.random()
if rdn < prob:
output[i][j] = 0
elif rdn > thres:
output[i][j] = 255
else:
output[i][j] = image[i][j]
cv2.imwrite('sp_noise_picture.png',output)
return output
均值滤波
均值滤波也成线性滤波,其采用的主要方法为邻域平均法。线性滤波的基本原理是用原图像中某个像素临近值的均值代替原图像中的像素值。即滤波器的核(kernel)中所有的系数都相等,然后用该核去对图像做卷积。
- 优点: 在一定程度上拉小灰度差异,减少噪声影响。对高斯噪声的表现比较好。
- 缺点: 对图像的边缘处也做均值,导致边缘处变模糊。对椒盐噪声的表现比较差。
def mean_filter(noise_img):
result = cv2.blur(noise_img, (5, 5))
cv2.imwrite('mean_filter_picture.png', result)
中值滤波
中值滤波器,使用滤波器窗口包含区域的像素值的中值来得到窗口中心的像素值。是一种非线性平滑滤波器。在去噪同时,较好的保持边缘轮廓细节,适合处理椒盐噪声,但对高斯噪声效果不好。
def median_filter(noise_img):
result = cv2.medianBlur(noise_img, 5)
cv2.imwrite("median_filter_picture.png", result)
高斯滤波
高斯滤波是一种线性平滑滤波,适用于消除高斯噪声,对整幅图像进行加权平均的过程,每一个像素点的值,都由其本身和邻域内的其他像素值经过加权平均后得到。
高斯模糊的卷积核里的数值是满足高斯分布,相当于更重视中间的,离得越近的像素点发挥的作用越大。
高斯核主要取决于σ。如果σ越小,高斯分布中心区域更加聚集,平滑效果越差;反之,则更离散,平滑效果越明显。
def gaussian_filter(noise_img):
gaussian_blurred = cv2.GaussianBlur(noise_img, (5, 5), 0)
cv2.imwrite('gaussian_filter_picture.png', gaussian_blurred)
双边滤波
双边滤波器是一种可以保边去噪的滤波器,也是一种加权平均滤波器,与高斯滤波不同的是,其滤波核是由两个函数构成,一个函数是由几何空间距离决定滤波器系数,另一个由像素差值决定滤波器系数。
双边滤波器适合处理高斯噪声,但对椒盐噪声基本不起任何作用。
def bilateral_filter(noise_img):
bilateral_blurred = cv2.bilateralFilter(noise_img, d=20, sigmaColor=50, sigmaSpace=15)
cv2.imwrite('bilateral_filter_picture.png', bilateral_blurred)