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