Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding most common color of an image

I have a bunch of products on a page that have 200x200 images. My first run at this was to get the data for each pixel (nested for loop, one for x, one for y), then convert rgb to hex, and store them in an array and then get the most frequent one. This script needs to run on 96 items per page at a time.

Currently, it creates a canvas and puts the product image in that canvas and then performs the above operations.

Is there some kind of averaging algorithm that would make this faster?

like image 423
Steve Avatar asked Mar 07 '13 05:03

Steve


2 Answers

Yes!

Lokesh Dhakar has created a script called "color thief" that calculates the dominant color of an image. It uses the modified median cut quantization algorithm (MCCQ) to quickly cluster colors and determine the dominant color (or even the whole color palette).

There is a demo here: http://lokeshdhakar.com/projects/color-thief/ and the script is available on github here: https://github.com/lokesh/color-thief

like image 103
markE Avatar answered Nov 17 '22 03:11

markE


I know it sounds easy to use library and all, but i found a much simpler solution that pretty much serves the purpose. When you apply a blur filter what it does is takes the average of pixel intensities. So if you apply a blur to the image with pretty high pixel value like

filter:blur(30px);

or

filter:blur(50px);

or anything that suits, it average outs the entire image and provides you with a solid background color which is most of time the prominent color from the image.

Its much simpler to do, and should work almost always. Just try tinkering with the blur amount.

Also remember to set overflow-y to be hidden because high blur causes white padding outside the image. hiding the overflow will fix that.

Hope that helps :)

like image 41
Praneet Mehta Avatar answered Nov 17 '22 01:11

Praneet Mehta