CowBoy
CowBoy

Reputation: 195

How can I add noise to my black and white bitmap image?

I have a black and white image that I need to store location of the back pixels and then add some noise by turning for example half of them to white randomly.
can anyone tell me how can i store the location of ONLY black pixels and randomly turn half of them to white color?

Upvotes: 0

Views: 1159

Answers (1)

Matt Burland
Matt Burland

Reputation: 45155

You could create a List<Point> to store your black pixels. Then just iterate through it and change them randomly:

List<Point> blackPixels = new List<Point>();

Now in your loop above:

else if (color.ToArgb() == Color.Black.ToArgb())
{
        blackColor++;
        blackPixels.Add(new Point(x,y));
}

And when you want to add noise just do something like:

Random r = new Random();

foreach(Point p in blackPixels) 
{
    if(r.NextDouble() < 0.5) 
    {
        bmp.SetPixel(p.X,p.Y,Color.White);
    }
}

This will statistically set about half your black pixels to white, but it may be more or less. If you truly want exactly half, then you can just randomly pick a set n/2 random numbers from 0 to n without repeats and toggle the pixels at those indexes in blackPixels. Or you could even shuffle your list of blackPixels and then change the first n/2 of them.

Note, however, that the performance of GetPixel and SetPixel isn't great. If your image is large, be sure to check out LockBits for better performance.

Upvotes: 2

Related Questions