python实现图像添加随机高斯噪音
时间: 2023-07-11 13:12:42 浏览: 57
可以使用Python中的OpenCV库和Numpy库来添加随机高斯噪音。以下是一个示例代码:
```python
import cv2
import numpy as np
# 读取图像
img = cv2.imread("image.jpg")
# 添加随机高斯噪音
mean = 0
var = 0.1
sigma = var ** 0.5
gaussian = np.random.normal(mean, sigma, img.shape)
noisy_image = np.clip(img + gaussian * 255, 0, 255).astype(np.uint8)
# 显示原图和添加噪音后的图像
cv2.imshow("Original Image", img)
cv2.imshow("Noisy Image", noisy_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在上面的代码中,首先读取图像,然后使用NumPy库生成随机高斯噪音。其中,`mean`表示噪音的均值,`var`表示噪音的方差,`sigma`表示噪音的标准差。然后,将随机高斯噪音添加到原始图像中,并使用`clip`函数将像素值限制在0到255之间。最后,将添加噪音后的图像显示出来。
相关问题
python实现图像随机添加高斯噪音
可以使用OpenCV库来实现图像随机添加高斯噪音。以下是示例代码:
```python
import cv2
import numpy as np
# 加载图像
img = cv2.imread('image.jpg')
# 随机生成高斯噪音
mean = 0
var = 0.1
sigma = var ** 0.5
gaussian = np.random.normal(mean, sigma, img.shape)
# 添加噪音
noisy_image = np.zeros(img.shape, np.float32)
if len(img.shape) == 2:
noisy_image = img + gaussian
else:
noisy_image[:, :, 0] = img[:, :, 0] + gaussian
noisy_image[:, :, 1] = img[:, :, 1] + gaussian
noisy_image[:, :, 2] = img[:, :, 2] + gaussian
# 转换为0-255范围内的整数
cv2.normalize(noisy_image, noisy_image, 0, 255, cv2.NORM_MINMAX, dtype=-1)
noisy_image = noisy_image.astype(np.uint8)
# 显示图像
cv2.imshow('Original Image', img)
cv2.imshow('Noisy Image', noisy_image)
cv2.waitKey(0)
```
在此代码中,我们首先加载图像,然后随机生成一个高斯分布,并将其添加到原始图像中,最后将结果转换为0-255范围内的整数,并显示原始图像和添加噪音后的图像。
python给图像加高斯噪声和去噪
要给图像加高斯噪声和去噪,我们可以使用Python中的OpenCV库。首先,我们需要导入必要的库和图像。
```python
import cv2
import numpy as np
# 加载图像
image = cv2.imread('image.jpg')
```
接下来,我们可以通过使用`cv2.randn()`函数来添加高斯噪声。该函数可以生成一个具有指定均值和标准差的随机高斯数组,与原始图像尺寸相同。
```python
# 生成高斯噪声
mean = 0
std_deviation = 50
gaussian_noise = np.zeros(image.shape, np.uint8)
cv2.randn(gaussian_noise, mean, std_deviation)
```
可以调整`mean`和`std_deviation`的值来控制噪声的强度。生成的高斯噪声数组与原始图像相加。
```python
# 添加高斯噪声到图像
noisy_image = cv2.add(image, gaussian_noise)
```
现在图像上添加了高斯噪声。如果要将其去噪,可以使用OpenCV库中的`cv2.fastNlMeansDenoising()`函数。
```python
# 去噪
denoised_image = cv2.fastNlMeansDenoisingColored(noisy_image, None, 10, 10, 7, 21)
```
在这里,我们使用了`cv2.fastNlMeansDenoisingColored()`函数来对带有高斯噪声的彩色图像进行去噪。该函数采用一些参数,如去噪强度、空间窗口大小和色彩距离权重等。您可以根据需要调整这些参数。
最后,可以使用`cv2.imshow()`函数显示添加了高斯噪声和去噪后的图像。
```python
# 显示结果
cv2.imshow('Original Image', image)
cv2.imshow('Noisy Image', noisy_image)
cv2.imshow('Denoised Image', denoised_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
通过运行以上代码,您将能够在显示窗口中看到原始图像、添加了高斯噪声的图像和经过去噪处理的图像。