[函數名稱]html
一維最大熵法圖像二值化WriteableBitmap EntropymaxThSegment(WriteableBitmap src)算法
[算法說明]函數
一維最大熵法圖像分割就是利用圖像的灰度分佈密度函數定義圖像的信息熵,經過優化必定的熵優化
準則獲得熵最大時對應的閾值,從而進行圖像分割的方法。spa
算法過程:.net
1,對於一幅灰度圖像,灰度範圍爲[0,L-1],求取圖像的最小灰度級min,最大灰度級max;code
[函數代碼]htm
/// <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; } }