soulkphp
soulkphp

Reputation: 3833

How can you find the "majority colors" of an image using PHP?

How can I calculate what the majority colors of an image are in PHP? I'd prefer to group different shades of a similar color into a single bucket, so for example all shades of blue are just counted as "blue".

In other words, I'd like a function that takes an image and returns a simple array similar to:

"blue":90%, "white":10%

No need for high accuracy, just enough to categorize the images by dominant and sub-dominant colors. Thanks!

Upvotes: 0

Views: 741

Answers (1)

Ben
Ben

Reputation: 68628

Here's one approach:

1) Define a set of colours which we'll call centroids -- these are the middle of the basic colours you want to break images into. You can do this using a clustering algorithm like k-means, for example. So now you've got, say, 100 centroids (buckets, you can think of them as), each of which is an RGB colour triple with a name you can manually attach to it.

2) To generate the histogram for a new image:

  • open the image in gd or whatever
  • convert it to an array of pixel values (e.g. using imagecolorat)
  • determine the distance (euclidean distance is ok) between the pixel value and all the centroids. Classify each pixel as to which bucket it's closest to.
  • Your output is a centroid assignment for each pixel. Or, given you just want a histogram, you can just count how many times each centroid occurs.

Bear in mind that this kind of colour assignment is somewhat subjective. I'm not sure there'll be a definitive mapping from colours to names (e.g., it's language dependent). But if you google, there might exist a look-up table that you could use, although I've not come across one.

Hope this helps!

Ben

Upvotes: 2

Related Questions