Bubble.ro - because there is always something new to learn about

How to create the histogram of an image using PHP

 

Category: Programming/PHP

A histogram is: a graphical display of tabulated frequencies. In our case, color frequencies that appear in an image. In some image manipulation software this can be named also as Levels.

Statistically speaking, each level has the meaning of probability to appear in the image is a random pixel is chosen. A more practical approach would define each level as the number of pixels of that particular value per total number of pixels contained in the image.

Overlay histogram

The algorithm to calculate the histogram for an image is pretty straight forward if you know how to extract the RGB value of each pixel, by counting the number of pixels of each value (and then divide by the total number of pixels in order to get a normalized value).

The script described next will output the histogram directly on the page, creating an HTML table which can be then viewed. Of course, this is one of the simplest solutions; you can of course display it as an image, store or perform any additional tasks on it.
<?php
$source_file = "test_image.jpg";

// histogram options

$maxheight = 300;
$barwidth = 2;

$im = ImageCreateFromJpeg($source_file);

$imgw = imagesx($im);
$imgh = imagesy($im);

// n = total number or pixels

$n = $imgw*$imgh;

$histo = array();

for ($i=0; $i<$imgw; $i++)
{
        for ($j=0; $j<$imgh; $j++)
        {
       
                // get the rgb value for current pixel
               
                $rgb = ImageColorAt($im, $i, $j);
               
                // extract each value for r, g, b
               
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;
               
                // get the Value from the RGB value
               
                $V = round(($r + $g + $b) / 3);
               
                // add the point to the histogram
               
                $histo[$V] += $V / $n;
       
        }
}

// find the maximum in the histogram in order to display a normated graph

$max = 0;
for ($i=0; $i<255; $i++)
{
        if ($histo[$i] > $max)
        {
                $max = $histo[$i];
        }
}

echo "<div style='width: ".(256*$barwidth)."px; border: 1px solid'>";
for ($i=0; $i<255; $i++)
{
        $val += $histo[$i];
       
        $h = ( $histo[$i]/$max )*$maxheight;

        echo "<img src=\"img.gif\" width=\"".$barwidth."\"
height=\""
.$h."\" border=\"0\">";
}
echo "</div>";
?>
Related links:

Source files
(115 KB)
How to check if an image is grayscale in PHP
How to convert an image to grayscale using PHP
PHP Image functions

Digg!
Posted by: Indy on October 30, 2006 at 08:37.
 

» Comments

Bug?
You may want to have a look at this :
http://www.dfanning.com/ip_tips/color2gray.html

Posted by Brook on November 1, 2006 at 02:58 PM.

Re: Bug?
A grayscale version of a given color image can be defined in many ways and therefor there are more "equivalents".

The one described in the link above takes into account the response (sensibility) courve of the human eye and thus through statistical research, some weights were determined.

The method used in this article is a more simple one, which only takes into account the actual RGB value.

Both methods can be considered correct since the idea of "good" or "bad" image is purely subjective and depends on each individual.

Posted by Indy on November 2, 2006 at 12:37 AM.

execution time exceeded
Hi
First I would like to thank you for posting this code.I have tried with single image itz working fine.I need to generate histogram of more than 1000 jpeg images.I have kept the images in a folder and generating the histogram for the images.The program is able to generate histogram for 170 images after that it shows exceeded 60 secs execution time at the line where the RGB values are obtained [$rgb = ImageColorAt($im, $i, $j); ].how to avoid this problem.Is there any efficient method to extract the rgb values from the jpeg image.

Posted by kokila on March 15, 2007 at 12:35 AM.

Re:
There isn't any faster way in PHP, you can use programs written in C for example to do it faster, you can set a higher value for timeout or you can save the histogram information in an additional and run the script several times.

Image operations in PHP take far too long to run in a dynamic page, you have to use some sort of caching to avoid problems.

Posted by Indy on March 15, 2007 at 01:59 AM.

Nice article
Nice job! Very interesting stuff.

Posted by Danny on March 21, 2009 at 01:14 AM.

John
This script works fine but I want also to expand, equalise, and smooth histogram

Posted by John on April 14, 2009 at 07:43 AM.

Mrs
I ask please, do not have the source code of image retrieval based on histogram with php language?. If I send to my email address-wanto03@gmail.com. thanks before ..... please confirmation to my email

Posted by Andi on May 9, 2009 at 10:25 PM.

Mrs
I ask please, do not have the source code of image retrieval based on histogram with php language?. If I send to my email address-wanto03@gmail.com. thanks before ..... please confirmation to my email

Posted by Andi on May 9, 2009 at 10:27 PM.

Sr. Research Engineer
This is exactly what I needed... thank you!!

Posted by Nancy on August 28, 2009 at 02:44 PM.

wfcFB
For our photo site this is an addition, I tried it and works, it generates the histo, but als allot of this:
Notice: Undefined offset: 31 (256 times)

I've done nothing to the code, just added a path to the picture I'm testing, what is causing this Notice: Undefined offset to appear?

Thanks for any advise.
Gerard

Posted by Gerard on September 5, 2009 at 02:47 AM.

wfcFB
I've tried it and works fine as stand alone version, how ever I want it intergrated in PhotoPost galery, that works also, but it shows a normal and mirrored histogram, and on some photo's no histogram.

Any ideas?

Posted by Gerard on September 5, 2009 at 12:54 PM.

wfcFB
Finally I got it working, however a histo in Photoshop of image X shows a bit different from a histo generated with this routine, no editing was done to the jpg.

Do you have any idea why the two histo's can differ?

Posted by Gerard on September 7, 2009 at 02:10 PM.

Histogram improvement
Hello,

at first, thanks for this nice snippet of PHP code.

However, after some research, I discovered that this algorithm would treat color RGB(1,0,0) = RGB(0,1,0) = RGB(0,0,1), meaning that it will mix pure red, green and blue pixels together.

The consequence of the above is, that you won't be able to differ between pure red, green and blue values in the histogram, because they represent the same value.

To fix this, one should not take the average RGB value of pixel (R+G+B / 3), but the original one (the highest precision available). The drawback is, that it could be pretty slow in PHP and for large images some parallelization should be used...

Please correct me if I am wrong.

Posted by Mireque on October 19, 2009 at 11:48 AM.

Random Article


Stumble Upon - random surfing around the web

If you are bored of browsing the same old sites every time you log on to your computer , you have a solution just a few clicks away. ...

Search


Feeds


Bubble.ro RSS Feed

All Categories


Articles


How to create the histogram of an image using PHP
How to convert an image to grayscale using PHP
How to check if an image is grayscale in PHP
Interchanging 2 variables without the use of a third
Error launching browser window:no XBL binding for browser
Convert the AOL user session collection to a MySQL database
Introduction to Matlab
Creating a customized session handling system in PHP (part II)
Creating a customized session handling system in PHP (part I)
Firefox crashing with Yahoo! Messenger
ADL Search for oDC
Video codecs explained
Browsershots
How to use Auto-Away Message with oDC
Create complete Windows XP disk with SP2 and all updates
Data Execution Prevention error message in Windows XP
Google Mars
Logarithmic scale graphs in Excel
Urban Dictionary (or wtf does l33t mean?)
Learn more about BIOS
Backup your Firefox and Thunderbird settings
Syndicate your Yahoo 360 profile
What is Google PageRank?
'Cannot Open the File: Mk:@MSITStore' Error Message
Get your Gmail with Mozilla Thunderbird
E-Books links
Change the size of your Explorer thumbnails
Remove previews from Windows Explorer
How can I turn off system beeps?
How do I disable Internet Explorer?
What are proxies or how do I protect my anonymity?
How to set aliases triggers or macros in MushClient
What is RSS?
Palm Zire 31 fast review
oDC Installation and Basic Configuration
How I built a 2x80W amplifier (using power modules)
Leech/HotLink Protection
How to block referrer detection?
How to find out your IP address
Getting started with Mushclient
What is spyware and how do I protect my PC from it?
Stumble Upon - random surfing around the web
Automatic file backup for Windows users
How can I read foreign language sites?
Protect your web surfing privacy!
What is BitTorrent?
No more ads! Adblock for Firefox
Why use Firefox instead of Internet Explorer?
Aetolia - The Midnight Age
How do I create my own Yahoo ID?
© Copyright 2006-2010 Bubble. All rights reserved. Sitemap - Contact