添加噪声的python代码
时间: 2023-08-31 12:10:49 浏览: 71
以下是添加高斯噪声和椒盐噪声的Python代码示例:
添加高斯噪声:
```python
import numpy as np
import cv2
def add_gaussian_noise(image, mean=0, var=0.1):
h, w, c = image.shape
sigma = var ** 0.5
noise = np.random.normal(mean, sigma, (h, w, c))
noise = noise.reshape(h, w, c)
noisy_image = image + noise
return np.clip(noisy_image, 0, 255).astype(np.uint8)
# Example usage
img = cv2.imread('image.jpg')
noisy_img = add_gaussian_noise(img, mean=0, var=0.1)
cv2.imshow('Noisy Image', noisy_img)
cv2.waitKey()
cv2.destroyAllWindows()
```
添加椒盐噪声:
```python
import numpy as np
import cv2
def add_salt_pepper_noise(image, prob=0.05):
h, w, c = image.shape
noisy_image = np.copy(image)
# Salt mode
num_salt = int(prob * h * w)
coords = [np.random.randint(0, i - 1, num_salt) for i in image.shape]
noisy_image[coords[0], coords[1], :] = 255
# Pepper mode
num_pepper = int(prob * h * w)
coords = [np.random.randint(0, i - 1, num_pepper) for i in image.shape]
noisy_image[coords[0], coords[1], :] = 0
return noisy_image
# Example usage
img = cv2.imread('image.jpg')
noisy_img = add_salt_pepper_noise(img, prob=0.05)
cv2.imshow('Noisy Image', noisy_img)
cv2.waitKey()
cv2.destroyAllWindows()
```
阅读全文