AForge.Imaging.Filters.SaltAndPepperNoise.ProcessFilter C# (CSharp) Method

ProcessFilter() protected method

Process the filter on the specified image.
protected ProcessFilter ( UnmanagedImage image, Rectangle rect ) : void
image UnmanagedImage Source image data.
rect System.Drawing.Rectangle Image rectangle for processing by the filter.
return void
        protected override unsafe void ProcessFilter( UnmanagedImage image, Rectangle rect )
        {
            int startX  = rect.Left;
            int startY  = rect.Top;
            int width   = rect.Width;
            int height  = rect.Height;
            int stride  = image.Stride;

            int noisyPixels = (int) ( ( width * height * noiseAmount ) / 100 );

            // values to set
            byte[] values = new byte[2] { 0, 255 };

            // do the job
            byte* ptr = (byte*) image.ImageData.ToPointer( );

            if ( image.PixelFormat == PixelFormat.Format8bppIndexed )
            {
                // grayscale image
                for ( int i = 0; i < noisyPixels; i++ )
                {
                    int x = startX + rand.Next( width );
                    int y = startY + rand.Next( height );

                    ptr[y * stride + x] = values[rand.Next( 2 )];
                }
            }
            else
            {
                int pixelSize = ( image.PixelFormat == PixelFormat.Format24bppRgb ) ? 3 : 4;

                // color image
                for ( int i = 0; i < noisyPixels; i++ )
                {
                    int x = startX + rand.Next( width );
                    int y = startY + rand.Next( height );
                    int colorPlane = rand.Next( 3 );

                    ptr[y * stride + x * pixelSize + colorPlane] = values[rand.Next( 2 )];
                }
            }
        }
    }