给图像添加高斯噪声 附源码
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <cv/cv_tools.h> #include <picture/cv_picture.h> using namespace cv; using namespace std; double generateGaussianNoise(double mu, double sigma) { static double V1, V2, S; static int phase = 0; double X; double U1, U2; if (phase == 0) { do { U1 = (double)rand() / RAND_MAX; U2 = (double)rand() / RAND_MAX; V1 = 2 * U1 - 1; V2 = 2 * U2 - 1; S = V1 * V1 + V2 * V2; } while (S >= 1 || S == 0); X = V1 * sqrt(-2 * log(S) / S); } else { X = V2 * sqrt(-2 * log(S) / S); } phase = 1 - phase; return mu + sigma*X; } void addNoise(uint8_t * data, int w, int h,int stride, double mu, double sigma, int k) { for (int i = 0; i<h; i++) { for (int j = 0; j<w; j++) { int of = i*stride + j; float temp = (int)data[of] + k*generateGaussianNoise(mu, sigma); temp = temp>255 ? 255: (temp<0?0 :temp); data[of] = (int)temp; } } } int main() { cv::Mat src = imread("D:/pic/wu.jpg",0); cv::Mat n1=src.clone(); cv::Mat n2 = src.clone(); cv::Mat n3 = src.clone(); int w = src.cols; int h = src.rows; addNoise(n1.data, w,h,w,0, 0, 1); addNoise(n2.data, w, h, w, 0, 5, 1); addNoise(n3.data, w, h, w, 0, 10, 1); myShow(n1); myShow(n2); myShow(n3); cv::waitKey(); }