数字图像处理实验记录
实验三 图像平滑
1、高斯噪声:
import numpy as np
#图像读入
img = cv2.imread('Jellyfish.jpg',0)
h = img.shape[0]
w = img.shape[1]
newimg = np.array(img)
#添加高斯噪声
mean = 0 #选取均值为
var = 0.005 #方差为0.005
img = np.array(img/255,dtype=float)
noise = np.random.normal(mean,var ** 0.5,img.shape)
Gauss_noise_img = img + noise
if Gauss_noise_img.min() < 0:
low_clip = -1
else:
low_clip = 0
Gauss_noise_img = np.clip(Gauss_noise_img,low_clip,1.0)
Gauss_noise_img = np.uint8(Gauss_noise_img*255)
#邻域平均法去除高斯噪声
lbimg = np.zeros((h+2,w+2),np.float32)
tmpimg = np.zeros((h+2,w+2))
myh = h+2
myw = w+2
tmpimg[1:myh-1,1:myw-1] = newimg[0:myh, 0:myw]
a = 1/8.0
kernel = a * np.array([[1,1,1],[1,0,1],[1,1,1]])
for y in range(1,myh-1):
for x in range(1,myw-1):
lbimg[y,x] = np.sum(kernel*tmpimg[y-1:y+2,x-1:x+2])
na_img = np.array(lbimg[1:myh-1,1:myw-1],np.uint8)
#中值滤波去噪
mean_blur_img = cv2.blur(img,(3,3))
#输出图像
cv2.imshow('灰度gray image',img)
cv2.imshow('高斯模糊Gauss noisy image',Gauss_noise_img)
cv2.imshow('领域neighborhood averaging image',na_img)
cv2.imshow('均值mean image',mean_blur_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
2、椒盐:
import numpy as np
def salt(image, number):
rows, cols = image.shape[:2]
saltImage = np.copy(image)
for i in range(number):
ranR = np.random.randint(0, rows) #随机产生整数
ranC = np.random.randint(0, cols)
saltImage[ranR][ranC] = 255
return saltImage
if __name__ == "__main__":
src1 = cv2.imread(r'Jellyfish.jpg', cv2.IMREAD_ANYCOLOR)
src = salt(src1, 2500)
dst = cv2.medianBlur(src, 3)
cv2.imshow("image", src)
cv2.imshow("medianBlurImage", dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
处理图像结果:Jellyfish.jpg变换