21 #define DISPLAY_SCALING 255
24 #define JPEGQUALITY 95
29 puts(
"Image noise simulator, P. Getreuer, 2012\n\n"
30 "Syntax: imnoise <model>:<sigma> <input> <output>\n");
31 puts(
"where <input> and <output> are "
34 "The <model> argument denotes the noise model. The parameter <sigma>\n"
35 "is the noise level, which is defined to be the square root of the\n"
36 "expected mean squared error.\n");
38 "The pixel intensities are denoted below by X[n] and Y[n], and they\n"
39 "are scaled as values between 0 and 255. Values of Y[n] outside of\n"
40 "this range are saturated.\n");
42 " gaussian:<sigma> Additive white Gaussian noise\n"
43 " Y[n] ~ Normal(X[n], sigma^2)\n"
44 " p(Y[n]|X[n]) = exp( -|Y[n] - X[n]|^2/(2 sigma^2) )\n");
46 " laplace:<sigma> Laplace noise\n"
47 " Y[n] ~ Laplace(X[n], sigma/sqrt(2))\n"
48 " p(Y[n]|X[n]) = exp( -|Y[n] - X[n]| sqrt(2)/sigma )\n");
50 " poisson:<sigma> Poisson noise\n"
51 " Y[n] ~ Poisson(X[n]/a) a\n"
52 " where a = 255 sigma^2 / (mean value of X)\n");
54 " imnoise laplace:10 input.bmp noisy.bmp\n");
57 void GaussianNoise(
float *Image,
long NumEl,
float Sigma);
58 void LaplaceNoise(
float *Image,
long NumEl,
float Sigma);
59 void PoissonNoise(
float *Image,
long NumEl,
float Sigma);
60 int IsGrayscale(
const float *Image,
long NumPixels);
63 int main(
int argc,
char **argv)
65 const char *Model, *InputFile, *OutputFile;
69 long NumPixels, NumEl;
70 int Width, Height, NumChannels, Status = 1;
72 if(argc != 4 || !(ParamString = strchr(argv[1],
':')))
87 if(!(Image = (
float *)
ReadImage(&Width, &Height, InputFile,
88 IMAGEIO_RGB | IMAGEIO_PLANAR | IMAGEIO_FLOAT)))
91 NumPixels = ((long)Width) * ((long)Height);
92 NumChannels = (
IsGrayscale(Image, NumPixels)) ? 1 : 3;
93 NumEl = NumChannels * NumPixels;
98 if(!strcmp(Model,
"gaussian"))
99 GaussianNoise(Image, NumEl, Param);
100 else if(!strcmp(Model,
"laplace"))
101 LaplaceNoise(Image, NumEl, Param);
102 else if(!strcmp(Model,
"poisson"))
103 PoissonNoise(Image, NumEl, Param);
106 fprintf(stderr,
"Unknown noise model, \"%s\".\n", Model);
111 if(!
WriteImage(Image, Width, Height, OutputFile,
112 ((NumChannels == 1) ? IMAGEIO_GRAYSCALE : IMAGEIO_RGB)
115 fprintf(stderr,
"Error writing to \"%s\".\n", OutputFile);
126 void GaussianNoise(
float *Image,
long NumEl,
float Sigma)
130 for(n = 0; n < NumEl; n++)
135 void LaplaceNoise(
float *Image,
long NumEl,
float Sigma)
137 const float Mu = (float)(
M_1_SQRT2 * Sigma);
140 for(n = 0; n < NumEl; n++)
145 void PoissonNoise(
float *Image,
long NumEl,
float Sigma)
150 for(n = 0; n < NumEl; n++)
154 a = Sigma * Sigma / ((Mean > 0) ? Mean : (0.5/255));
156 for(n = 0; n < NumEl; n++)
161 int IsGrayscale(
const float *Image,
long NumPixels)
163 const float *Red = Image;
164 const float *Green = Image + NumPixels;
165 const float *Blue = Image + 2*NumPixels;
168 for(n = 0; n < NumPixels; n++)
169 if(Red[n] != Green[n] || Red[n] != Blue[n])