public static int?EntroypSelectionThreshold(WriteableBitmap writeableBitmap) { ImageHistogramData bitmapHistogramData = new ImageHistogramData(writeableBitmap); if (bitmapHistogramData.IsGrayscale) { var grayscaleHistogram = bitmapHistogramData.GrayscaleHistogram; int threshold = 0; double max_entrophy = Double.MinValue; int length = grayscaleHistogram.Length; for (int i = 0; i < length; ++i) { double background_entrophy = CalculateBackgroundEntropy(grayscaleHistogram, i); double foreground_entrophy = CalculateForegorundEntropy(grayscaleHistogram, length, i); Debug.WriteLine(background_entrophy + foreground_entrophy + " : " + max_entrophy); if (background_entrophy + foreground_entrophy > max_entrophy) { max_entrophy = background_entrophy + foreground_entrophy; threshold = i; } } return(threshold); } return(null); }
public static int GetOtsuThreshold(WriteableBitmap bmp) { double[] vet = new double[256]; ImageHistogramData imageHistogramData = new ImageHistogramData(bmp); int[] hist = imageHistogramData.R; // loop through all possible t values and maximize between class variance for (int k = 1; k != 255; ++k) { double p1 = Px(0, k, hist); double p2 = Px(k + 1, 255, hist); double p12 = p1 * p2; if (p12 == 0) { p12 = 1; } double diff = (Mx(0, k, hist) * p2) - (Mx(k + 1, 255, hist) * p1); vet[k] = diff * diff / p12; //vet[k] = (float)Math.Pow((Mx(0, k, hist) * p2) - (Mx(k + 1, 255, hist) * p1), 2) / p12; } return(FindMaxElementIndex(vet)); }
public static int?PercentageBlackSelectionThreshold(WriteableBitmap writeableBitmap, double percentage) { ImageHistogramData bitmapHistogramData = new ImageHistogramData(writeableBitmap); if (bitmapHistogramData.IsGrayscale) { var grayscaleHistogram = bitmapHistogramData.GrayscaleHistogram; int desiredPixelsCount = (int)Math.Floor(writeableBitmap.PixelHeight * writeableBitmap.PixelWidth * percentage); for (int count = 0, i = 0; i < 256; ++i) { count += grayscaleHistogram[i]; if (count > desiredPixelsCount) { return(Math.Min(255, i)); } } } return(null); }