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;
}
}