简体   繁体   English

如何在黑白位图图像中添加噪点?

[英]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? 任何人都可以告诉我如何存储只有黑色像素的位置,并随机将其中一半变为白色?

You could create a List<Point> to store your black pixels. 您可以创建List<Point>来存储黑色像素。 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 . 如果你真的想正好一半,那么你可以随机挑选一组n从0到N / 2个随机数不重复并在这些索引切换像素blackPixels Or you could even shuffle your list of blackPixels and then change the first n/2 of them. 或者您甚至可以随机播放blackPixels列表,然后更改它们的前n / 2个。

Note, however, that the performance of GetPixel and SetPixel isn't great. 但请注意, GetPixelSetPixel的性能不是很好。 If your image is large, be sure to check out LockBits for better performance. 如果您的图片很大,请务必查看LockBits以获得更好的性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM