using imagemagick, awk and kmeans to find dominant colors in images

30 Sep 2015

Some days ago I was reading “Using python to generate awesome linux desktop themes” and got impressed by a technique to obtain dominant colors from images, I went ahead and tried to run the examples but PIL proved difficult to install, so I looked around to see if I could replace it for some other utility and it turned out that convert (which is part of the imagemagick package) is powerful enough for the duty.

Besides resizing, convert can output the rgb values of any image, so I reimplemented the kmean algorithm on awk and that’s how dcolors was born. By default dcolor will resize (on RAM) the input image to 25x25 using a 1px deviation and 3 clusters for an average time of 1s per image, further customization are possible to increase quality, quantity or performance.

$ time dcolors akira_800x800.jpg
163,80,50
65,77,93
40,26,34

real    0m1.176s

                                

$ time ./dcolors --resize 100x100 -d 10 akira-cycle-2.png
49,85,118
19,42,69
125,173,165

real    0m3.188s

                                

$ time ./dcolors -f hex -k 8 akira-neo-tokyo-7_800x800.png
#495D66
#223634
#1C293A
#68706E
#3C4F4A
#38495D
#293C48
#0B1016

real    0m1.005s

                                                                                       

That’s it, happy hacking 😋