////// 二值化图像 /// /// ///private static unsafe Bitmap Binaryzation(Bitmap bmp) { BitmapData dstData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat); byte* data = (byte*)(dstData.Scan0); //将图像转换为0,1二值得图像; int step = dstData.Stride; int means = getThreshold(data, bmp.Height * step); for (int y = 0; y < bmp.Height; y++) { for (int x = 0; x < bmp.Width * 3; x += 3) { if (data[y * step + x + 2] > means) data[y * step + x] = data[y * step + x + 1] = data[y * step + x + 2] = 255; else data[y * step + x] = data[y * step + x + 1] = data[y * step + x + 2] = 0; } } bmp.UnlockBits(dstData); return bmp; } /// /// 图像二值化 获取阀值 /// /// /// height * Stride ///private static unsafe int getThreshold(byte* inPixels, int length) { int inithreshold = 127; int finalthreshold = 0; List temp = new List (); for (int index = 0; index < length; index += 3) { temp.Add(inPixels[index + 2]); } List sub1 = new List (); List sub2 = new List (); int means1 = 0, means2 = 0; while (finalthreshold != inithreshold) { finalthreshold = inithreshold; for (int i = 0; i < temp.Count(); i++) { if (temp[i] <= inithreshold) { sub1.Add(temp[i]); } else { sub2.Add(temp[i]); } } means1 = getMeans(sub1); means2 = getMeans(sub2); sub1.Clear(); sub2.Clear(); inithreshold = (means1 + means2) / 2; } return finalthreshold; } /// /// 图像二值化 获取Means /// /// ///private static int getMeans(List data) { int result = 0; int size = data.Count(); foreach (int i in data) { result += i; } return (result / size); }