FileDocCategorySizeDatePackage
ColorHistogram.javaAPI DocAndroid 5.1 API3623Thu Mar 12 22:22:56 GMT 2015android.support.v7.graphics

ColorHistogram

public final class ColorHistogram extends Object
Class which provides a histogram for RGB values.

Fields Summary
private final int[]
mColors
private final int[]
mColorCounts
private final int
mNumberColors
Constructors Summary
ColorHistogram(int[] pixels)
A new {@link ColorHistogram} instance.

param
pixels array of image contents

        // Sort the pixels to enable counting below
        Arrays.sort(pixels);

        // Count number of distinct colors
        mNumberColors = countDistinctColors(pixels);

        // Create arrays
        mColors = new int[mNumberColors];
        mColorCounts = new int[mNumberColors];

        // Finally count the frequency of each color
        countFrequencies(pixels);
    
Methods Summary
private static intcountDistinctColors(int[] pixels)

        if (pixels.length < 2) {
            // If we have less than 2 pixels we can stop here
            return pixels.length;
        }

        // If we have at least 2 pixels, we have a minimum of 1 color...
        int colorCount = 1;
        int currentColor = pixels[0];

        // Now iterate from the second pixel to the end, counting distinct colors
        for (int i = 1; i < pixels.length; i++) {
            // If we encounter a new color, increase the population
            if (pixels[i] != currentColor) {
                currentColor = pixels[i];
                colorCount++;
            }
        }

        return colorCount;
    
private voidcountFrequencies(int[] pixels)

        if (pixels.length == 0) {
            return;
        }

        int currentColorIndex = 0;
        int currentColor = pixels[0];

        mColors[currentColorIndex] = currentColor;
        mColorCounts[currentColorIndex] = 1;

        if (pixels.length == 1) {
            // If we only have one pixel, we can stop here
            return;
        }

        // Now iterate from the second pixel to the end, population distinct colors
        for (int i = 1; i < pixels.length; i++) {
            if (pixels[i] == currentColor) {
                // We've hit the same color as before, increase population
                mColorCounts[currentColorIndex]++;
            } else {
                // We've hit a new color, increase index
                currentColor = pixels[i];

                currentColorIndex++;
                mColors[currentColorIndex] = currentColor;
                mColorCounts[currentColorIndex] = 1;
            }
        }
    
int[]getColorCounts()

return
an array containing the frequency of a distinct colors within the image.

        return mColorCounts;
    
int[]getColors()

return
an array containing all of the distinct colors in the image.

        return mColors;
    
intgetNumberOfColors()

return
number of distinct colors in the image.

        return mNumberColors;