python添加高斯噪声_使用Python-OpenCV向图片添加噪声(高斯噪声、椒盐噪声)
时间: 2023-11-02 18:06:35 浏览: 105
添加高斯噪声可以使用NumPy和OpenCV库。具体的步骤如下:
1. 导入NumPy和OpenCV库:
```python
import numpy as np
import cv2
```
2. 读取图片:
```python
img = cv2.imread('image.jpg')
```
3. 生成高斯噪声:
```python
mean = 0
var = 100
sigma = var ** 0.5
gaussian = np.random.normal(mean, sigma, (img.shape[0], img.shape[1], img.shape[2]))
gaussian = gaussian.reshape(img.shape)
```
其中,mean表示噪声的均值,var表示噪声的方差,sigma表示噪声的标准差,np.random.normal是生成高斯分布的函数。
4. 将高斯噪声添加到图片中:
```python
img_gaussian = img + gaussian
```
5. 显示添加噪声后的图片:
```python
cv2.imshow('Gaussian noise', img_gaussian)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
完整代码如下:
```python
import numpy as np
import cv2
img = cv2.imread('image.jpg')
mean = 0
var = 100
sigma = var ** 0.5
gaussian = np.random.normal(mean, sigma, (img.shape[0], img.shape[1], img.shape[2]))
gaussian = gaussian.reshape(img.shape)
img_gaussian = img + gaussian
cv2.imshow('Gaussian noise', img_gaussian)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
注意:在添加噪声后,像素值可能会超出0-255的范围,需要使用clip函数将其限制在0-255之间,如下所示:
```python
img_gaussian = np.clip(img_gaussian, 0, 255)
```
阅读全文