opencv加性噪声
时间: 2023-11-20 18:58:14 浏览: 28
以下是使用OpenCV为图像添加椒盐噪声和高斯噪声的示例代码:
1. 添加椒盐噪声
```cpp
void addSaltNoise(cv::Mat &m, int num) {
// 随机数产生器
std::random_device rd;
// 种子
std::mt19937 gen(rd()); // 随机数引擎
auto cols = m.cols * m.channels();
for (int i = 0; i < num; i++) {
auto row = static_cast<int>(gen() % m.rows);
auto col = static_cast<int>(gen() % cols);
auto p = m.ptr<uchar>(row); p[col++] = 255;
p[col++] = 255;
p[col] = 255; }
}
```
2. 添加高斯噪声
```python
import numpy as np
import cv2
def addGaussianNoise(image, mean=0, var=0.001):
"""
添加高斯噪声
:param image: 输入图像
:param mean: 均值
:param var: 方差
:return: 添加噪声后的图像
"""
row, col, ch = image.shape
sigma = var ** 0.5
gauss = np.random.normal(mean, sigma, (row, col, ch))
gauss = gauss.reshape(row, col, ch)
noisy = image + gauss
return noisy
# 加载图像
img = cv2.imread('test.jpg')
# 添加高斯噪声
noisy_img = addGaussianNoise(img)
# 显示图像
cv2.imshow('noisy image', noisy_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```