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.