Palette
class is not made to accurately extract pixel colors from an image, rather its purpose is to give and aesthetically pleasant set of colors that can be used for UX purpose only.
The only things you can do are:
- Increase the number of colors used by the
Palette
algorithm.
- Increase the size to which the largest dimension of the image is scaled down to.
You can tweak the builder settings before generating the palette:
final Palette palette
= Palette
.from(source)
.maximumColorCount(numerOfColors)
.resizeBitmapSize(bitmapLargestDimension)
.generate();
Beware that generating palette is very expensive!
You are using the synchronous version, that block the calling thread, be sure of what you are doing, especially if you increase the settings above.
For information purpose only, here a summary of what Palette
does.
I cannot find the latest source of the Palette
class, I assume that some of the code originally in Palette
has been refactored into Palette.Builder
.
If you look at the source code of the generate
method you will see that
- The image is scaled down so that its largest dimension fit 100 pixels (by default)
- The image is quantized1 so that the number of colors is 16 (by default)
The quantizier does not return an image, but rather the list of remaining colors wrapped in a class called Swatch
(which offer more semantic than a simple int
).
After that an instance of palette is built and the profile swatches (Vibrant, Vibrant Dark, Vibrant Light, Muted, Muted Dark, Muted Light) are searched among the swatches returned by the quantizier.
A profile define a range of acceptable values for saturation and luma along with the ideal saturation and luma values.
Search is performed by looking for swatches that fall within a profile range.
Since multiple swatches can match, a weighting function is computed.
Such function gives an higher score to swatches that have saturation and luma values closer to the ideal ones and represent more pixels.
Saturation matching accounts twice as luma matching that accounts as three times as population counting.
1
Quantization does not work by by reducing the color space (e.g. from going to 24 bit per pixel to 4 bit per pixel) but rather but averaging colors (along the largest dimension) until their number is below or equal the threshold given.
See ColorCutQuantizier source