I do not intend to elaborate on professional terms, and interested readers can refer to the reference link at the end of the article, where there are understandable explanations:
Let's look at an example image (taken with Canon 550D):
Example Picture: butterfly.jpg
Here's how to implement the image histogram using Imagick:
Copy Code code as follows:
<?php
$file = ' butterfly.jpg ';
$size = Array (
' Width ' => 256,
' Height ' => 100,
);
$image = new Imagick ($file);
$histogram = Array_fill_keys (range (0, 255), 0);
foreach ($image->getimagehistogram () as $pixel) {
$rgb = $pixel->getcolor ();
$histogram [$rgb [' R ']] + = $pixel->getcolorcount ();
$histogram [$rgb [' G ']] + = $pixel->getcolorcount ();
$histogram [$rgb [' B ']] + = $pixel->getcolorcount ();
}
$max = max ($histogram);
$threshold = ($image->getimagewidth () * $image->getimageheight ())/256 * 12;
if ($max > $threshold) {
$max = $threshold;
}
$image = new Imagick ();
$draw = new Imagickdraw ();
$image->newimage ($size [' width '], $size [' Height '], ' white ');
foreach ($histogram as $x => $count) {
if ($count = = 0) {
Continue
}
$draw->setstrokecolor (' black ');
$height = min ($count, $max)/$max * $size [' height '];
$draw->line ($x, $size [' height '], $x, $size [' height ']-$height);
$image->drawimage ($draw);
$draw->clear ();
}
$image->setimageformat (' png ');
$image->writeimage (' histogram.png ');
?>
Note: The code is added to the $threshold this threshold, because sometimes the value of certain levels may be very large, if not done will interfere with the final build effect. As for why to first except 256, and then multiply by 12, there is no reason to say, all is my one shot head decision, you can also use other methods.
The resulting histogram is basically the same as Photoshop, where Photoshop is posted:
Photoshop-generated histogram
Note: After using Photoshop to open the picture, select the window and select the histogram.
This article is actually just RGB channel histogram rendering method, principle, RGB histogram is the result of red-green and blue histogram accumulation, as for the red and green blue three primary colors of the histogram, the above code slightly modified.
Note: xarg.org has a HTML5 to achieve the image histogram open source project, the effect is good, it is worth learning.
Finally, incidentally, if you are interested in photography, you can refer to: How to interpret the histogram of a digital camera.