Threshold

This algorithm converts specified image to binary image that has only two colors black and white.

   



									public static void ApplyThreshold(ref Bitmap bmp, short thresholdValue)
{
	int MaxVal = 768;

	if (thresholdValue < 0) return;
	else if (thresholdValue > MaxVal) return;

	BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

	unsafe
	{
		int TotalRGB;

		byte* ptr = (byte*)bmpData.Scan0.ToPointer();
		int stopAddress = (int)ptr + bmpData.Stride * bmpData.Height;

		while ((int)ptr != stopAddress)
		{
			TotalRGB = ptr[0] + ptr[1] + ptr[2];

			if (TotalRGB <= thresholdValue)
			{
				ptr[2] = 0;
				ptr[1] = 0;
				ptr[0] = 0;
			}
			else
			{
				ptr[2] = 255;
				ptr[1] = 255;
				ptr[0] = 255;
			}

			ptr += 3;
		}
	}

	bmp.UnlockBits(bmpData);
}
								


Example

									Bitmap b = (Bitmap)Image.FromFile("rose.jpg");
ApplyThreshold(ref b, 400);