我们将常会听到平滑(去噪),锐化(和平滑是相反的),那我们就会有疑惑?什么是噪声呢?图像噪声是指存在于图像数据中不必要的或多余的干扰信息,噪声的存在严重影响了图像的质量。噪声在理论上是”不可预测“的,所以我们只能用概率论方法认识“随机误差”。
光电管的噪声、摄像管噪声、摄像机噪声、椒盐噪声(数字图像常见的噪声,椒盐噪声就是在图像上随机出现黑色白色的像素)等等。
椒盐噪声又被称作脉冲噪声,它会随机改变图像中的像素值,是由相机成像、图像传输、解码处理等过程产生的黑白相间的亮暗点噪声,其样子就像在图像上随机的撒上一些盐粒和黑椒粒,因此被称为椒盐噪声。
代码如下:
- import numpy as np
- import cv2
- def cv_show(name,img):
- cv2.imshow(name,img)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
- def add_sp_noise(img,sp_number):
- new_image=img
- row,col,channel=img.shape#获取行列,通道信息
- s=int(sp_number*img.size/channel)#根据sp_number确定椒盐噪声
- #确定要扫椒盐的像素值
- change=np.concatenate((np.random.randint(0,row,size=(s,1)),np.random.randint(0,col,size=(s,1))),axis=1)
- for i in range(s):
- r=np.random.randint(0,2)#确定撒椒(0)还是盐(1)
- for j in range(channel):
- new_image[change[i,0],change[i,1],j]=r
- return new_image
注意:在进行实验的时候,我们需要注意要进行拷贝不然原图会被破坏。
测试:
- img=cv2.imread("C:/Users/bwy/Desktop/peppers.JPG")
- im=img.copy()
- im2=img.copy()
- im3=img.copy()
- im=add_sp_noise(im,0.05)
- im2=add_sp_noise(im2,0.1)
- im3=add_sp_noise(im3,0.3)
- r=np.hstack((img,im,im2,im3))
- cv_show('r',r)
结果如图所示:

从图上看出,sp_number越大,噪声点越多。
高斯滤波(手写代码):滤掉噪声的代价就是图像会有所模糊。

计算过程:

此时还要确保这九个点加起来为1(高斯模板的特性),这9个点的权重为0.4787147,因此将9个值都除以0.4787147,得到最终的高斯模板。
再与图像像素进行乘积,四周加和代替中间的。
(1)灰度图像高斯滤波:
- def gaosi_f(img,k_size,sigma):
- ##滤波图片的尺寸
- h=img.shape[0]
- w=img.shape[1]
- ##用0填充边缘
- pad=k_size//2
- transform_img=np.zeros((h+2*pad,w+2*pad))
- transform_img[pad:h+pad,pad:w+pad]=img
- new_img=np.zeros((h,w))
-
- ##先计算高斯滤波核
- gaosi_filter=np.zeros((k_size,k_size))
- for x in range(-pad,-pad+k_size):
- for y in range(-pad,-pad+k_size):
- gaosi_filter[y+pad,x+pad]=np.exp(-(x**2+y**2)/(2*sigma**2))/(2*np.pi*sigma**2)
- gaosi_filter=gaosi_filter/np.sum(gaosi_filter)
-
- ##计算滤波后的图片
- for i in range(pad,h+pad):
- for j in range(pad,w+pad):
- ##取图像k_size x k_size的像素值
- p_img=transform_img[i-pad:i+pad+1,j-pad:j+pad+1]
- ##进行高斯滤波
- value=np.sum(np.multiply(p_img,gaosi_filter))
- new_img[i-pad,j-pad]=value
- ##对滤波后的图片中的像素值取整
- new_img=np.round(new_img).astype(np.uint8)
-
- return new_img
彩色图像高斯滤波:
- def gaosi_fS(img,k_size,sigma):
- h=img.shape[0]
- w=img.shape[1]
- imShape=img.shape
- dim=len(imShape)
- if dim==2:
- eim=gaosi_f(img,k_size,sigma)
- else:
- imR=img[:,:,0]
- imG=img[:,:,1]
- imB=img[:,:,2]
- eim=np.zeros((h,w,3))
- eimr=gaosi_f(imR,k_size,sigma)
- eimg=gaosi_f(imG,k_size,sigma)
- eimb=gaosi_f(imB,k_size,sigma)
- eim[:,:,0]=eimr
- eim[:,:,1]=eimg
- eim[:,:,2]=eimb
- return eim
测试:
- new_img=gaosi_fS(im,3,0.5)
- cv_show("new_img",new_img)
- cv_show("im",im)
结果如图所示:


- aussian = cv2.GaussianBlur(im, (5,5), 1)
- cv_show("aussian",aussian)
结果如图所示:
