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

Posted by: Indy on October 30, 2006 at 14: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 08: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 06: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 05: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 06:59 AM.

Nice article
Nice job! Very interesting stuff.

Posted by Danny on March 21, 2009 at 06: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 12:43 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 [email protected]. thanks before ..... please confirmation to my email

Posted by Andi on May 10, 2009 at 03:25 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 [email protected]. thanks before ..... please confirmation to my email

Posted by Andi on May 10, 2009 at 03:27 AM.

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

Posted by Nancy on August 28, 2009 at 07: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 07: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 05: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 07: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 04:48 PM.

Sajan
"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..."

Can be have it fixed ??
Please provide me with fixed code
thanks


Posted by Sajan on April 19, 2011 at 07:30 AM.

hazro
my name is khan

Posted by shah123 on July 15, 2011 at 11:13 AM.

hye
is this gud...?


Posted by wafa chaht on October 5, 2011 at 12:32 PM.

count the pixels - don't add luminance itself!
A histogram should count the pixels of a certain luminance. When you add the luminance itself to your array $histo you're getting a wrong histogram. Take an all-black image: $V would be 0 for all the pixels! Instead of having a peak in the histogram to the left side, your code would just have a array with 0 as first value and no value for the other entries.

Posted by Sebastian on October 11, 2011 at 06:11 PM.

count the pixels, don't add luminance itself!
A histogram should count the pixels of a certain luminance. When you add the luminance itself to your array $histo you're getting a wrong histogram. Take an all-black image: $V would be 0 for all the pixels! Instead of having a peak in the histogram to the left side, your code would just have a array with 0 as first value and no value for the other entries.

Posted by Sebastian on October 11, 2011 at 06:12 PM.

wrong algorithm
Well, I think that line

$histo[$V] += $V / $n;

should change to

$histo[$V] ++;

Posted by Vasileios Gavriilidis on December 4, 2012 at 12:38 AM.

One small correction I encountered
You might change from

for ($i=0; $i<255; $i++)
to
for ($i=0; $i<=255; $i++)

Posted by Rohan on April 16, 2013 at 09:18 AM.

pixel value histogram
thanks, this is exactly the php code i was looking for..
i've tried it with only one color element (green), here is the code:
//$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF; //green only
//$b = $rgb & 0xFF;

$histo[$V] = $g;
echo $histo[$V];
echo ' ';

output for image size 60 x 60 pixels: 60 58 57 61 64 . . . until pixel 3600.

but, is there who can share on how to create output of frequency for each pixel value. exmpl:
pixel value = 0 1 2 . . . 255
frequency = 0 0 5 . . . 4 <<-this is what i want as output

thanks for any help

Posted by susan on May 2, 2013 at 11:36 AM.

PHP Class
We've been using this class: http://www.histogramgenerator.com for our photo galleries and photography portfolios. That script even offers other great (though pretty advanced) features. Sadly, it isn't free but we have been receiving free upgrades since last year, it's worth the money we paid for.

Posted by Catherine Mayer on June 28, 2013 at 09:21 AM.

Your code was useful for me
Hi,

this weekend, I've used your source in order to develop a plugin for Wordpress. My plugin shows the EXIF data automatically from the images that the user have included in his post. Now, I am printing the RGB histogram over the thumbnail.

I've mentioned this URL as comment in my source and I will link to your web in the final version.

Thanks again
jmarior from <a href="http://www.jmarior.net">www.jmarior.net</a>

Posted by jmaror on August 5, 2013 at 07:22 AM.

hello
hi.can you help me for php code for image prosessing?

Posted by neda on November 20, 2013 at 08:14 PM.

volleyball betting tips
Very interesting information! Perfect just what I was looking for! My site: <a href="https://www.okbetcasino.live/en/sports-betting/volleyball/">Volleyball Betting in the Philippines</a>


Posted by volleyball betting tips on May 26, 2023 at 09:52 AM.

Random Article


Search


Feeds


Bubble.ro RSS Feed

All Categories


Articles


Aetolia - The Midnight Age
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?
How do I create my own Yahoo ID?
© Copyright 2006-2020 Bubble. All rights reserved. Sitemap - Contact