opencv c++给视频添加椒盐噪声和高斯噪声
时间: 2023-12-31 20:05:29 浏览: 46
在 OpenCV 中,可以使用 `rand()` 函数生成随机数来给视频添加噪声。以下是分别添加椒盐噪声和高斯噪声的示例代码:
1. 椒盐噪声:
```cpp
void add_salt_pepper_noise(Mat& image, float snr)
{
int num_salt = static_cast<int>(image.total() * (1 - snr));
int num_pepper = static_cast<int>(image.total() * snr);
// 添加椒盐噪声
for (int i = 0; i < num_salt; ++i)
{
int row = rand() % image.rows;
int col = rand() % image.cols;
image.at<uchar>(row, col) = 255;
}
for (int i = 0; i < num_pepper; ++i)
{
int row = rand() % image.rows;
int col = rand() % image.cols;
image.at<uchar>(row, col) = 0;
}
}
```
2. 高斯噪声:
```cpp
void add_gaussian_noise(Mat& image, float mean, float stddev)
{
Mat noise(image.size(), CV_32F);
randn(noise, mean, stddev); // 生成高斯噪声
Mat temp;
image.convertTo(temp, CV_32F); // 将图像转换为浮点型
add(temp, noise, temp); // 添加噪声
temp.convertTo(image, CV_8UC1); // 转换回无符号8位整型
}
```
使用以上函数,可以在读取视频帧时,调用函数,对每一帧进行噪声处理后再显示出来,实现给视频添加噪声的效果。