PHP grayscale to heatmap convert function

PHP에서 0부터 255까지의 수치를 heatmap RGB 값으로 전환하는 함수입니다.

(0-255 범위는 조정 가능합니다)

Grayscale로 된 이미지 연산 결과를 heatmap으로 전환하기 위해 만들어봤습니다.
The following PHP function converts a value between 0 to 255 into a heatmap RGB value.
(The range 0 to 255 can be adjusted)
I wrote this function to visualize a calcuation result as a heatmap.
The brief concept is like this.
The heatmap starts with a full (=255) blue color, and the green channel steeply increases.
Then blue starts to steeply decrease to 0, while the green channel gets saturated.
After the middle point, green minimally decreases while red quickly increases.
In the end part, red gets saturated while green fades away swiftly.
Ratio1 designates the value for Cyan, ratio2 for pure green, ratio3 for yellow.
Here is the function with an example usage.
<?php
function heatmap($val, $min=0, $max=255) {
// heatmap function by mahler83 2013.Apr.9
$ratio = ($val – $min) / ($max – $min);
$ratio1 = 0.3;
$ratio2 = 0.5;
$ratio3 = 0.7;
$cut = 200;
if($ratio < $ratio1) {
$ratioSpan = $ratio1;
$r = 0;
$g = $cut * $ratio / $ratioSpan;
$b = (1 – $ratio / $ratioSpan) * (255-$cut) + $cut;
} elseif($ratio < $ratio2) {
$ratioSpan = $ratio2 – $ratio1;
$r = 0;
$g = ($ratio – $ratio1) / $ratioSpan * (255-$cut) + $cut;
$b = (1 – ($ratio – $ratio1) / $ratioSpan) * $cut;
} elseif($ratio < $ratio3) {
$ratioSpan = $ratio3 – $ratio2;
$r = ($ratio – $ratio2) / $ratioSpan * $cut;
$g = (1 – ($ratio – $ratio2) / $ratioSpan) * (255-$cut) + $cut;
$b = 0;
} else {
$ratioSpan = 1 – $ratio3; 
$r = ($ratio – $ratio3) / $ratioSpan * (255-$cut) + $cut;
$g = (1 – ($ratio – $ratio3) / $ratioSpan) * $cut;
$b = 0;
}
if($r < 0) $r = 0;
if($g < 0) $g = 0;
if($b < 0) $b = 0;
if($r > 255) $r = 255;
if($g > 255) $g = 255;
if($b > 255) $b = 255;
return array(round($r), round($g), round($b));
}

$img = imagecreatetruecolor(2 * 256, 100);

for($x = 1; $x <= 256 * 2; $x++) {
$a = intval($x / 2);
for($y = 1; $y <= 100; $y++) {
$heat = heatmap($a);
$color = imagecolorallocate($img, $heat[0], $heat[1], $heat[2]);
imagesetpixel($img, $x, $y, $color);
}
}

header(‘Content-type: image/jpeg’);
imagejpeg($img);
imagedestroy($img);
?>


The code above will output something like the following.

CC BY-NC-SA 4.0 This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Leave a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.