stwhite
stwhite

Reputation: 3275

Getting colors from image that are most Visually Prominent with PHP

Question: Is it possible to get a colors luminance value in php?

What I'm trying to do is get the most "visually prominent" colors from an image with PHP. I've gone through all of Stack Overflow and I've not been able to find any solution.

Currently I've built a color search by images that loops through every pixel of an image, stores the colors, calculates color differences and brightness value then stores those in the database.

The problem: The results are mathematically correct, however they aren't visually accurate to the image the colors were previously matched from. I assumed that some sort of luminance comparison might solve this problem.

I've noticed that when I order the results by ascending (lowest first), that the results are actually more accurate (although not as accurate in some cases). This means that the color occurrence values are much lower than when ordering DESC (highest first).

To calculate "brightness", I'm using this—I don't believe its that powerful:

function luminance($pixel){

   $pixel = sprintf('%06x',$pixel);
   $red = hexdec(substr($pixel,0,2))*0.30;
   $green = hexdec(substr($pixel,2,2))*0.59;
   $blue = hexdec(substr($pixel,4))*0.11;

   return $red+$green+$blue;
}

Here is one scenario that shows the problem: http://twitpic.com/33e23p http://twitpic.com/33e3x0

I'm also starting to wonder if my color distance function is not finding the most similar color:

function colorDistance(array $color1, array $color2) {
  return sqrt(pow($color1[0] - $color2[0], 2) +
    pow($color1[1] - $color2[1], 2) +
    pow($color1[2] - $color2[2], 2));
}

Upvotes: 1

Views: 1120

Answers (1)

AlcubierreDrive
AlcubierreDrive

Reputation: 3664

Since your color space is standard RGB, the Wikipedia article Luminance (relative) says your multipliers on R, G, and B should be

  • R: 0.21
  • G: 0.72
  • B: 0.07

instead of what you have. So

function luminance($pixel){

   $pixel = sprintf('%06x',$pixel);
   $red = hexdec(substr($pixel,0,2))*0.21;
   $green = hexdec(substr($pixel,2,2))*0.72;
   $blue = hexdec(substr($pixel,4))*0.07;

   return $red+$green+$blue;
}

Upvotes: 1

Related Questions