Specifying the number of DominantColors to be extracted from an image

How does one get a certain number of DominantColors and is it always possible to do so? I have tried specifying the number as well as the option ColorCoverage -> 0.

More examples: 1, 2, 3

• DominantColors[img, no. of colors]. Your problem may not be so trivial. In that case give an example where you think it is not working. Jan 11 '17 at 17:59
• @Sumit, I added an example. Jan 11 '17 at 18:14
• FWIW I can not reproduce any case where DominantColors returns less than the requested number. (unless starting with an image with fewer discrete colors) @E.Alderson what version do you have? Can you see if you have this issue with some standard example, eg ExampleData[{"TestImage", "Splash"}] Jan 11 '17 at 23:07
• @george2079, Mathematica 11.0.1. The issue mostly occurs when working with monochromatic images (I added more examples). It works fine on Example Data. Jan 12 '17 at 10:30
• Have you seen this? Jan 12 '17 at 17:32

This seems to work in every case I've tried (v. 10.4, Mac).

ColorQuantize forces the number of colors in the image. Here's a screenshot of the original:

Here's the quantized image:

quantizedImage = ColorQuantize[img, 5]


My code worked fine on the screen shot of the poser's image, though admittedly the colors are rather dark.

Here are the extracted colors:

DominantColors[quantizedImage, 5]

{RGBColor[0.242519, 0.347167, 0.144226],
RGBColor[0.233793, 0.319928, 0.134609],
RGBColor[0.357113, 0.483923, 0.216957],
RGBColor[0.340756, 0.432562, 0.162432],
RGBColor[0.16798, 0.278479, 0.11706]}


or

Graphics[
Table[{SortBy[DominantColors[quantizedImage, 5],Mean][[i]],
Disk[{2 i, 0}]},
{i, 5}]]


I believe the dark colors arise because most of the image is quite dark, and the light highlights, while centered, represent a very small portion of the total image.

• I tried to grab the OP's image, had to do a screencapture for it, but here it is. But I couldn't get it to work with your code Jan 11 '17 at 20:01
• @user9490, didn't work for me too, I got only two colors. Jan 11 '17 at 20:02
• This does give the five colors from the quantized image, they are a bit darker than the dominant colors found by the built-in function: RGBColor@*Most /@ Union[Flatten[ImageData[quantizedImage], 1]] Jan 11 '17 at 20:06
• I have been using this function for color extraction, even though it does not produce the desired output:color[img_] := MapAt[RGBColor, Tally[Flatten[ImageData[ColorQuantize[ImageResize[img, 50], 5]], 1]], {All, 1}] col[img_] := First[#] & /@ color[img]; Jan 11 '17 at 20:10
• @David didn't work for me either
– M.R.
Jan 11 '17 at 21:04