C # Image Processing: convert a color image to a black/white image

Source: Internet
Author: User

First, explain the so-called black and white images. In fact, it should be called a 256-level grayscale image more accurately. When R = G = B of A color point, it is called "gray ". The value range of RGB is [0,255], so there are only 256 possibilities.

Therefore, the principle of converting a color image into a black image or a black image is very simple. You only need to scan each point of the color chart to make the R = G = B of the corresponding point of the output chart become. The key to the problem is how to set the value.

There are two types: one is the arithmetic average value of RGB three-point, and the other is the weighted average value. The weighted average takes into account the sensitivity of human eyes to different components.

The Code is as follows:

 

 

 

/** // <Summary>
/// Black/white chart
/// </Summary>
/// <Param name = "bmp"> original graph </param>
/// <Param name = "mode"> mode. 0: weighted average 1: arithmetic average </param>
/// <Returns> </returns>
Private Bitmap ToGray (Bitmap bmp, int mode)
{
If (bmp = null)
{
Return null;
}

Int w = bmp. Width;
Int h = bmp. Height;
Try
{
Byte newColor = 0;
BitmapData srcData = bmp. LockBits (new Rectangle (0, 0, w, h), ImageLockMode. ReadWrite, PixelFormat. Format24bppRgb );
Unsafe
{
Byte * p = (byte *) srcData. Scan0.ToPointer ();
For (int y = 0; y {
For (int x = 0; x <w; x ++)
{

If (mode = 0) // weighted average
{
NewColor = (byte) (float) p [0] * 0.114f + (float) p [1] * 0.587f + (float) p [2] * 0.299f );
}
Else // arithmetic mean
{
NewColor = (byte) (float) (p [0] + p [1] + p [2])/3.0f );
}
P [0] = newColor;
P [1] = newColor;
P [2] = newColor;

P + = 3;
}
P + = srcData. Stride-w * 3;
}
Bmp. UnlockBits (srcData );
Return bmp;
}
}
Catch
{
Return null;
}

}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.