views:

252

answers:

2

I have a picture (jpg file, for example).

I need to know "overall average" the color of the picture. I mean the prevailing color in this picture. I can not strictly furmulate my task.

I will cite an example:

alt text

(Image above: at the top - the original image, at the bottom - the "overall average" color which is associated with picture)

If you help me to formulate a strictly my task I shall be very grateful. At first glance there can use the histogram of the image (channel RGB).

Supplement: at work I use mostly JavaScript and PHP (a little Python) therefore welcomed the decision in these languages. Maybe ther are library for working with images that address similar problems.

Supplement NO2:I do not need to dynamically determine the color of the picture. I need just once go through the entire array of images and determine the color of each separately (this information I will remember for future use).

+6  A: 

You can use PHP to get an array of the color palette like so:

<?php 
function colorPalette($imageFile, $numColors, $granularity = 5) 
{ 
   $granularity = max(1, abs((int)$granularity)); 
   $colors = array(); 
   $size = @getimagesize($imageFile); 
   if($size === false) 
   { 
      user_error("Unable to get image size data"); 
      return false; 
   } 
   $img = @imagecreatefromjpeg($imageFile); 
   if(!$img) 
   { 
      user_error("Unable to open image file"); 
      return false; 
   } 
   for($x = 0; $x < $size[0]; $x += $granularity) 
   { 
      for($y = 0; $y < $size[1]; $y += $granularity) 
      { 
         $thisColor = imagecolorat($img, $x, $y); 
         $rgb = imagecolorsforindex($img, $thisColor); 
         $red = round(round(($rgb['red'] / 0x33)) * 0x33); 
         $green = round(round(($rgb['green'] / 0x33)) * 0x33); 
         $blue = round(round(($rgb['blue'] / 0x33)) * 0x33); 
         $thisRGB = sprintf('%02X%02X%02X', $red, $green, $blue); 
         if(array_key_exists($thisRGB, $colors)) 
         { 
            $colors[$thisRGB]++; 
         } 
         else 
         { 
            $colors[$thisRGB] = 1; 
         } 
      } 
   } 
   arsort($colors); 
   return array_slice(array_keys($colors), 0, $numColors); 
} 
// sample usage: 
$palette = colorPalette('rmnp8.jpg', 10, 4); 
echo "<table>\n"; 
foreach($palette as $color) 
{ 
   echo "<tr><td style='background-color:#$color;width:2em;'>&nbsp;</td><td>#$color</td></tr>\n"; 
} 
echo "</table>\n";

Which gives you an array whose values are higher for how often that color has been used.

JKirchartz
+2  A: 

Start with PIL. http://www.pythonware.com/products/pil/

Open the Image object. Use the getdata method to get all pixels. Average the values you get back.

Something like this.

http://stackoverflow.com/questions/2270874/image-color-detection-using-python

S.Lott