给图片同时添加高斯噪声和椒盐噪声python代码
时间: 2023-10-25 07:06:33 浏览: 146
下面是使用Python代码同时添加高斯噪声和椒盐噪声的示例:
```python
import numpy as np
import cv2
def add_noise(image):
# 添加高斯噪声
mean = 0
var = 0.1
sigma = var ** 0.5
gauss = np.random.normal(mean, sigma, image.shape)
gauss = gauss.reshape(image.shape)
noisy_image = image + gauss
# 添加椒盐噪声
s_vs_p = 0.5
amount = 0.004
out = np.copy(noisy_image)
# 添加盐噪声
num_salt = np.ceil(amount * image.size * s_vs_p)
coords = [np.random.randint(0, i - 1, int(num_salt))
for i in image.shape]
out[coords] = 1
# 添加椒噪声
num_pepper = np.ceil(amount * image.size * (1. - s_vs_p))
coords = [np.random.randint(0, i - 1, int(num_pepper))
for i in image.shape]
out[coords] = 0
return out
# 读入一张图片
img = cv2.imread('test.jpg')
# 添加高斯噪声和椒盐噪声
noisy_image = add_noise(img)
# 显示原始图片和添加噪声后的图片
cv2.imshow('Original Image', img)
cv2.imshow('Noisy Image', noisy_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这段代码使用了numpy和OpenCV库来实现添加高斯噪声和椒盐噪声。其中,高斯噪声的方差为0.1,椒盐噪声的比例为50%,噪声强度为0.4%。可以根据需要调整这些参数来控制噪声的强度和类型。
阅读全文