[函数名称]
一维最大熵法图像二值化WriteableBitmap EntropymaxThSegment(WriteableBitmap src)
[算法说明]
一维最大熵法图像分割就是利用图像的灰度分布密度函数定义图像的信息熵,通过优化一定的熵
准则得到熵最大时对应的阈值,从而进行图像分割的方法。
算法过程:
1,对于一幅灰度图像,灰度范围为[0,L-1],求取图像的最小灰度级min,最大灰度级max;
[函数代码]
/// <summary> /// Entropy max method of image segmention. /// </summary> /// <param name="src">The source iamge.</param> /// <returns></returns> public static WriteableBitmap EntropymaxThSegment(WriteableBitmap src) ////一维熵最大法阈值分割 { if (src != null) { int w = src.PixelWidth; int h = src.PixelHeight; WriteableBitmap dstImage = new WriteableBitmap(w, h); byte[] temp = src.PixelBuffer.ToArray(); byte[] tempMask = (byte[])temp.Clone(); //定义灰度图像信息存储变量 int[] srcData = new int[w * h]; //定义阈值变量 int Th = 0; //定义直方图存储变量 int[] histogram = new int[256]; //定义熵值变量 double Ht = 0.0; double Hl = 0.0; double sigma = 0.0; //定义灰度最值变量 int max = 0; int min = 255; //定义临时变量 double t = 0.0, pt = 0.0, tempMax = 0.0; int tempV = 0; for (int j = 0; j < h; j++) { for (int i = 0; i < w; i++) { tempV = (int)((double)tempMask[i * 4 + j * w * 4] * 0.114 + (double)tempMask[i * 4 + 1 + j * w * 4] * 0.587 + (double)tempMask[i * 4 + 2 + j * w * 4] * 0.299); srcData[i + j * w] = tempV; histogram[tempV]++; if (tempV > max) { max = tempV; } if (tempV < min) { min = tempV; } } } for (int i = min; i < max; i++) { t = (double)((double)histogram[i] / (double)(w * h)); if (t > 0.00000001) { Hl += -t * Math.Log10(t); } else continue; } for (int i = min; i < max; i++) { t = (double)((double)histogram[i] / (double)(w * h)); pt += t; if (t > 0.00000001) { Ht += -t * Math.Log10(t); sigma = Math.Log10(pt * (1 - pt)) * Ht / pt + (Hl - Ht) / (1 - pt); if (sigma > tempMax) { tempMax = (int)sigma; Th = i; } } else continue; } for (int j = 0; j < h; j++) { for (int i = 0; i < w; i++) { temp[i * 4 + j * w * 4] = temp[i * 4 + 1 + j * w * 4] = temp[i * 4 + 2 + j * w * 4] = (byte)(srcData[i + j * w] < Th ? 0 : 255); } } Stream sTemp = dstImage.PixelBuffer.AsStream(); sTemp.Seek(0, SeekOrigin.Begin); sTemp.Write(temp, 0, w * 4 * h); return dstImage; } else { return null; } }