/// <summary> /// Histogram Equalization will enhance general contrast /// by distributing grey levels wider and more evenly. /// </summary> /// <param name="imageBytes">Image bytes</param> /// <param name="pixelDepth">Pixel depth of image</param> /// <param name="imageWidth">Image width</param> /// <param name="imageHeight">Image height</param> public static void HistogramEqualizationDirect(byte[] imageBytes, int pixelDepth, int imageWidth, int imageHeight) { int[] histogram = ImageHistogram.GetHistogramValues(imageBytes, pixelDepth); double numberOfPixels = imageWidth * imageHeight; double numberOfLevels = histogram.Length; int cumulativeFrequency = 0; int equalizedValue; // Calculate cumulative distribution for histogram for (int i = 0; i < histogram.Length; i++) { cumulativeFrequency += histogram[i]; // Calculate equalized value equalizedValue = (int)Math.Round((numberOfLevels * cumulativeFrequency) / numberOfPixels) - 1; // Ensure +ve value histogram[i] = Math.Max(0, equalizedValue); } bool isColor = BitmapDataExt.IsColorPixelDepth(pixelDepth); int limit = BitmapDataExt.GetSafeArrayLimitForImage(isColor, pixelDepth, imageBytes); // Apply distribution to image to equalize if (isColor) { // Exclude alpha/transparency byte int pixelDepthWithoutAlpha = Math.Min(pixelDepth, Constants.PixelDepthRGB); for (int i = 0, j; i < limit; i += pixelDepth) { for (j = 0; j < pixelDepthWithoutAlpha; j++) { imageBytes[i + j] = (byte)histogram[imageBytes[i + j]]; } } } else { for (int i = 0; i < limit; i++) { imageBytes[i] = (byte)histogram[imageBytes[i]]; } } }
/// <summary> /// Obtains threshold value for image using Otsu's Method. /// </summary> /// <param name="imageBytes">Image bytes</param> /// <param name="pixelDepth">Pixel depth</param> /// <returns>Threshold value</returns> public static byte GetByOtsuMethod(byte[] imageBytes, int pixelDepth) { int[] histValues = ImageHistogram.GetHistogramValues(imageBytes, pixelDepth); return(GetByOtsuMethod(histValues)); }