Can I get a list of the number of different color pixels with ImageMagick?

Viewed 159

Let's say I have the following image:

enter image description here

When I use the ImageMagick, the command identify -format %k image.png counts the number of different colors on this image. My output for this image is 1031, which would mean that this image has 1031 different colors. However, visually saying I have around 5 different colors:

black
white
grey
light green
dark green

I'd like to find a way of getting a list of the number of major color pixels. For example, let's say that I have 1000 pixels on the last image, so I'd expect something like:

black:10
white:50
grey:200
light green:690
dark green:50

Is there any way to make ImageMagick display output values like the last ones? Just so I'll know the percentage of the main colors on my image?

1 Answers

You can load the image, tell ImageMagick you want it reduced to 5 colours and then get the histogram like this:

magick 0N9iv.png -colors 5 -verbose info: | grep -A5 Histogram:

  Histogram:
    459: (181.83,198.952,162.503,229.414) #B6C7A3E5 srgba(71.306%,78.0204%,63.7265%,0.899662)
    26749: (182.035,228.807,158.076,254.874) #B6E59EFF srgba(71.3861%,89.7283%,61.9907%,0.999506)
    577: (191.945,227.688,174.459,100.095) #C0E4AE64 srgba(75.2725%,89.2894%,68.4152%,0.392528)
    727: (196.666,220.169,180.959,255) #C5DCB5FF srgba(77.124%,86.3407%,70.9642%,1)
    4384: (219.415,217.829,213.189,255) #DBDAD5FF srgba(86.045%,85.423%,83.6034%,1)

Note that means that ImageMagick chooses the colours itself. If you specifically want your image mapped to your own particular set of colours, make a palette of those colours like this:

magick xc:black xc:white xc:gray xc:lightgreen xc:darkgreen +append palette.png

enter image description here

And then tell ImageMagick to map all the colours to those 5 colours and see the output:

magick 0N9iv.png +dither -remap palette.png -verbose info: | grep -A5 Histogram:

Sample output

Histogram:
81: (0,0,0,255) #000000FF black
22: (126,126,126,255) #7E7E7EFF gray
28270: (144,238,144,255) #90EE90FF LightGreen
4523: (255,255,255,255) #FFFFFFFF white
Colormap entries: 5

You can also select just the histogram like this:

magick 0N9iv.png +dither -remap palette.png -format %c histogram:info:-

Sample Output

81: (0,0,0,255) #000000FF black
22: (126,126,126,255) #7E7E7EFF gray
28270: (144,238,144,255) #90EE90FF LightGreen
4523: (255,255,255,255) #FFFFFFFF white
Related