예제 #1
0
 /// <summary>
 /// Inserts Gaussian noise into a bitmap.
 /// </summary>
 /// <param name="source">Bitmap to be processed</param>
 /// <param name="amount">Standard deviation of perturbation for each color channel.</param>
 /// <returns>New, speckled bitmap</returns>
 /// <remarks>
 /// This code uses Bitmap.GetPixel and SetPixel methods for clarity. An implementation using Bitmap.LockBits
 /// and then directly modifying the image data may be faster, espectially for large images.
 /// </remarks>
 public static Bitmap AddNoise(this Bitmap source, double amount)
 {
     if (source == null)
         throw new ArgumentNullException("source");
     Bitmap bitmap = null;
     Bitmap tempBitmap = null;
     try
     {
         var generator = new GaussianRandom(0.0, amount, SampleUtilities.MakeRandomSeed());
         tempBitmap = new Bitmap(source.Width, source.Height);
         for (int y = 0; y < tempBitmap.Height; y++)
         {
             for (int x = 0; x < tempBitmap.Width; x++)
             {
                 var pixel = source.GetPixel(x, y);
                 Color newPixel = AddPixelNoise(pixel, generator);
                 tempBitmap.SetPixel(x, y, newPixel);
             }
         }
         bitmap = tempBitmap;
         tempBitmap = null;
     }
     finally
     {
         if (tempBitmap != null) tempBitmap.Dispose();
     }
     return bitmap;
 }
예제 #2
0
 static Color AddPixelNoise(Color pixel, GaussianRandom generator)
 {
     int newR = (int)pixel.R + generator.NextInteger();
     int newG = (int)pixel.G + generator.NextInteger();
     int newB = (int)pixel.B + generator.NextInteger();
     int r = Math.Max(0, Math.Min(newR, 255));
     int g = Math.Max(0, Math.Min(newG, 255));
     int b = Math.Max(0, Math.Min(newB, 255));
     return Color.FromArgb(r, g, b);
 }