OpenCV - Gaussian Noise

Hello,

here's my problem: I'm trying to create a simple program which adds Gaussian noise to an input image. The only constraints are that the input image is of type CV_64F (i.e. double) and the values are and must be kept normalized between 0 and 1.

The code I wrote is the following:

Mat my_noise;
my_ noise = Mat (input.size(), input.type());

randn(noise, 0, 5); //mean and variance

input += noise;


The above code doesn't work, the resulting image doesn't get displayed properly. I think that happens because it gets out of the 0,1 range. I modified the code like this:

Mat my_noise;
my_ noise = Mat (input.size(), input.type());

randn(noise, 0, 5); //mean and variance

input += noise;

normalize(input, input, 0.0, 1.0, CV_MINMAX, CV_64F);


but it still doesn't work. Again, the resulting image doesn't get displayed properly. Where is the problem? Remember: the input image is of type CV_64F and the values are normalized between 0 and 1 before adding noise and have to remain like also after the noise addition.

edit retag close merge delete

1
2

@thdrksdfthmn because he wants to add noise, not apply blurring to remove possible noise. You should read with attention ;)

Sort by » oldest newest most voted

There may be two reasons for the results you got:

• The noise matrix and the image are not normalized in the same range of [0,1].
• The stddev value you used (5) was too large.

The code following works for me:

// imGray is the grayscale of the input image
cv::Mat noise = Mat(imGray.size(),CV_64F);
normalize(imGray, result, 0.0, 1.0, CV_MINMAX, CV_64F);
cv::randn(noise, 0, 0.05);
result = result + noise;
normalize(result, result, 0.0, 1.0, CV_MINMAX, CV_64F);
cv::imshow("OUTPUT",result);


And here is the illustration (an input image and Gaussian noise version with stddev=0.05 and 0.1, respectively):   more
    Mat input = imread("inputImage.png");
Mat imGray;
cvtColor(input,imGray,CV_BGR2GRAY);
cv::Mat noise = Mat(imGray.size(),CV_64F);
Mat result;
normalize(imGray, result, 0.0, 1.0, CV_MINMAX, CV_64F);
cv::randn(noise, 0, 0.1);
result = result + noise;
normalize(result, result, 0.0, 1.0, CV_MINMAX, CV_64F);
result.convertTo(result, CV_32F, 255, 0);
cv::imwrite("result.png",result);
cv::waitKey(0);

more