1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
#include<opencv2/opencv.hpp>
#include <random>
namespace mycv {
const double pi = 3.1415926;
void createGaussianNoise(cv::Mat& src, cv::Mat& dst)
{
dst = src.clone();
//1、灰阶范围[0, G - 1], 取sigma > 0; sigma越小噪声越小
const int G = 256;
double sigma = 20;
for(int i = 0; i < src.rows; ++i)
for (int j = 0; j < src.cols - 1; ++j)
{
//2、产生位于[0, 1]独立随机数gamma、phi
std::random_device rd;
std::mt19937 gen(rd());
double gamma = std::generate_canonical<double, 2>(gen);
double phi = std::generate_canonical<double, 2>(gen);
//3、计算z1、z2
double z1 = sigma * std::cos(2 * pi*phi)*std::sqrt(-2 * std::log(gamma));
double z2 = sigma * std::sin(2 * pi*phi)*std::sqrt(-2 * std::log(gamma));
//4、
double tmpxy = src.at<uchar>(i, j) + z1;
double tmpxy1 = src.at<uchar>(i, j + 1) + z2;
//5
if (tmpxy < 0)
dst.at<uchar>(i, j) = 0;
else if (tmpxy > G - 1)
dst.at<uchar>(i, j) = G - 1;
else
dst.at<uchar>(i, j) = static_cast<int>(tmpxy);
if (tmpxy1 < 0)
dst.at<uchar>(i, j + 1) = 0;
else if (tmpxy > G - 1)
dst.at<uchar>(i, j + 1) = G - 1;
else
dst.at<uchar>(i, j + 1) = static_cast<int>(tmpxy1);
}
}
}//mycv
int main(void)
{
cv::Mat src = cv::imread("lena.jpg", 0);
if (src.empty()) return -1;
cv::Mat dst;
mycv::createGaussianNoise(src, dst);
cv::imshow("src", src);
cv::imshow("dst", dst);
cv::waitKey(0);
return 0;
}//main
|