1、固定阈值法二值化模块 public Bitmap Threshoding(Bitmap b, byte threshold)int width = b.Width;int height = b.Height;BitmapData data = b.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);unsafebyte* p = (byte*)data.Scan0;int offset = data.Stride - width * 4;byte R
2、, G, B, gray;for (int y = 0; y 16);if (gray = threshold)p0 = p1 = p2 = 255;elsep0 = p1 = p2 = 0;p += 4;p += offset;b.UnlockBits(data);return b;#endregion#region 自适应阈值法二值化模块/ / 自适应阈值/ / 位图流/ public Bitmap AutoFitThreshold(Bitmap b)/ 图像灰度化b = Gray(b);/ 建立直方图,并获取灰度统计信息Histogram histogram = new Histogra
3、m(b);int GrayLevel = histogram.Red.Value;int peak1, peak2, valley;int peak1Index, peak2Index, valleyIndex;/ 取双峰peak1 = peak2 = GrayLevel0;peak1Index = peak2Index = 0;for (int i = 1; i peak1)peak2 = peak1;peak2Index = peak1Index;peak1 = GrayLeveli;peak1Index = i; / i/ 判断两个峰值索引int max = peak1Index;int
4、 min = peak2Index;if (max / Otsu 阈值/ / 位图流/ public Bitmap OtsuThreshold(Bitmap b)/ 图像灰度化b = Gray(b);int width = b.Width;int height = b.Height;byte threshold = 0;int hist = new int256;int AllPixelNumber = 0, PixelNumberSmall = 0, PixelNumberBig = 0;double MaxValue, AllSum = 0, SumSmall = 0, SumBig, P
5、robabilitySmall, ProbabilityBig, Probability;BitmapData data = b.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);unsafebyte* p = (byte*)data.Scan0;int offset = data.Stride - width * 4;for (int j = 0; j MaxValue)MaxValue = Probability;threshold = (byte)i;Console.WriteLine(“Threshold = “ + threshold);return this.Threshoding(b, threshold); / end of OtsuThreshold 2#endregion