Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

average of RGB color of Image

I'm trying to get average of RGB color of Image in php.

by gd lib I program it

    $x = imagesx($im);
    $y = imagesy($im);
    for ($i = 0;$i < $x;$i++)
        for ($j = 0;$j < $y;$j++){
            $rgb = imagecolorat($im,$i,$j);
            $sum['R'] += ($rgb >> 16) & 0xFF;
            $sum['G'] += ($rgb >> 8) & 0xFF;
            $sum['B'] += $rgb & 0xFF; 
        }

But it's not good way I think. It needs a lot of ram to process. Is there another way to do it?

like image 568
Moein Hosseini Avatar asked Aug 05 '11 21:08

Moein Hosseini


People also ask

What is the average color of an image?

The average colour is the sum of all pixels divided by the number of pixels. However, this approach may yield a colour different to the most prominent visual color. What you might really want is dominant color rather than average colour.

How many colors are in an RGB image?

The three RGB colors are each 8-bits (possible values [0.. 255], 28 = 256) of each of Red, Green, and Blue. The three 8-bit RGB components can create up to 256×256×256 = 16.7 million possible RGB color combinations, called 24-bit "color". Of course, any one real photo image will not use most of these possible colors.

What is the average colour?

The team determined that the average color of the universe is a beige shade not too far off from white.

How do you find the RGB of an image?

Click on the color selector icon (the eyedropper), and then click on the color of in- terest to select it, then click on 'edit color'. 3. The RGB values for that color will appear in a dialogue box.


2 Answers

I would go with resampling:

$tmp_img = ImageCreateTrueColor(1,1);
ImageCopyResampled($tmp_img,$im,0,0,0,0,1,1,$x,$y); // or ImageCopyResized
$rgb = ImageColorAt($tmp_img,0,0);
like image 50
Jacek Kaniuk Avatar answered Oct 29 '22 01:10

Jacek Kaniuk


One way to do this is to scale the picture to just one pixel and then use the colors of that pixel as a reference.

<?php
$image = new Imagick('800x480.jpg');
$image->scaleImage(1, 1, true);
$pixel = $image->getImagePixelColor(0,0);

$red   = ($rgb >> 16) & 0xFF;
$green = ($rgb >> 8) & 0xFF;
$blue  =  $rgb & 0xFF; 
?>

That way you don't need to handle messy details. and you can use smarter scaling algorithms to achieve better precision.

Edit: You can use Imagick::resizeImage instead if you need a more sophisticated algorithm. it can use different algorithms like Interpolation filter.

like image 45
Mehran Avatar answered Oct 29 '22 01:10

Mehran