Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have to add noise to the image in black and white. Can you help me ?

What I have tried:

I tried this code first but I couldn't add black.
public static  void SaltPepperNoise(Image<Bgr, byte> image, int n)
{
       ////random number generator
       Random random = new Random();
       for (int k = 0; k < n; k++)
       {
         //random pixel to set white color
         int w = random.Next() % image.Width;
         int h = random.Next() % image.Height;
         image[h, w] = new Bgr(255,255,255);
       }
}

I tried this code first but I couldn't add black.

Then I found the python code and tried converting it to C # but Mat black and Mat white also give error
C#
Mat saltpepper_noise = new Mat(image.Width, image.Height, Emgu.CV.CvEnum.DepthType.Cv8U,3);

            CvInvoke.Randu(saltpepper_noise,new MCvScalar(0), new MCvScalar(255));

            Mat black = saltpepper_noise < 30; //error
            Mat white = saltpepper_noise > 225; //error

            Mat saltpepper_img = (Mat)image.ToBitmap().Clone();

            saltpepper_img.SetTo(new MCvScalar(255),white);
            saltpepper_img.SetTo(new MCvScalar(0), black);
Posted
Updated 28-May-20 1:52am

1 solution

You only insert white because of this line:
C#
image[h, w] = new Bgr(255,255,255);
If you want to add black or white, then you have to get an intermediate random number:
C#
//random pixel to set black or white color
int w = random.Next() % image.Width;
int h = random.Next() % image.Height;
int shade = (random.Next(0, 256) > 127) ? 255 : 0;
image[h, w] = new Bgr(shade, shade, shade);
 
Share this answer
 
Comments
Muhammet Ali Gülbahçe 28-May-20 8:03am    
I am very happy, thank you very much.But why was it bigger than 127? I'm asking to understand.
phil.o 28-May-20 8:14am    
The Next function, when called with two parameters, will return an integer greater than or equal to the first parameter, and strictly lower than second parameter. Thus, it will return a value between 0 and 255 (inclusive). If this value is greater than 127, we choose white (255); otherwise, we choose black (0).
Maciej Los 28-May-20 8:58am    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900