imagecolorclosest

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolorclosest β€” ΠŸΠΎΠ»ΡƒΡ‡Π°Π΅Ρ‚ блиТайший индСкс Ρ†Π²Π΅Ρ‚Π°

ОписаниС

function imagecolorclosest(
Β Β Β Β GdImage $image,
Β Β Β Β int $red,
Β Β Β Β int $green,
Β Β Β Β int $blue
): int

Ѐункция Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ индСкс Ρ†Π²Π΅Ρ‚Π° Π² ΠΏΠ°Π»ΠΈΡ‚Ρ€Π΅ изобраТСния, «блиТайшСго» ΠΊ Π·Π°Π΄Π°Π½Π½ΠΎΠΌΡƒ RGB-Π·Π½Π°Ρ‡Π΅Π½ΠΈΡŽ.

«РасстояниС» ΠΌΠ΅ΠΆΠ΄Ρƒ Ρ†Π²Π΅Ρ‚Π°ΠΌΠΈ Π² ΠΏΠ°Π»ΠΈΡ‚Ρ€Π΅ рассчитываСтся гСомСтричСски, ΠΊΠ°ΠΊ Ссли Π±Ρ‹ RGB-значСния ΠΏΡ€Π΅Π΄ΡΡ‚Π°Π²Π»ΡΠ»ΠΈΡΡŒ Π² Π²ΠΈΠ΄Π΅ Ρ‚ΠΎΡ‡Π΅ΠΊ Π² Ρ‚Ρ€Ρ‘Ρ…ΠΌΠ΅Ρ€Π½ΠΎΠΌ пространствС.

Π’ изобраТСниях, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ создали ΠΈΠ· Ρ„Π°ΠΉΠ»Π°, функция распознаёт Ρ‚ΠΎΠ»ΡŒΠΊΠΎ Ρ†Π²Π΅Ρ‚Π° самого рисунка, поэтому ΠΈΠ³Π½ΠΎΡ€ΠΈΡ€ΡƒΠ΅Ρ‚ Ρ†Π²Π΅Ρ‚Π°, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ содСрТит ΠΏΠ°Π»ΠΈΡ‚Ρ€Π°, Π½ΠΎ Π½Π΅ Π²ΠΊΠ»ΡŽΡ‡Π°Π΅Ρ‚ ΠΈΠ·ΠΎΠ±Ρ€Π°ΠΆΠ΅Π½ΠΈΠ΅.

Бписок ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ΠΎΠ²

image
ΠžΠ±ΡŠΠ΅ΠΊΡ‚ GdImage, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ Π²Π΅Ρ€Π½ΡƒΠ»Π° функция imagecreatetruecolor() ΠΈΠ»ΠΈ другая функция Π³Π΅Π½Π΅Ρ€Π°Ρ†ΠΈΠΈ ΠΈΠ·ΠΎΠ±Ρ€Π°ΠΆΠ΅Π½ΠΈΠΉ.
red

Π—Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ красного ΠΊΠΎΠΌΠΏΠΎΠ½Π΅Π½Ρ‚Π° Ρ†Π²Π΅Ρ‚Π°.

green

Π—Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ Π·Π΅Π»Ρ‘Π½ΠΎΠ³ΠΎ ΠΊΠΎΠΌΠΏΠΎΠ½Π΅Π½Ρ‚Π° Ρ†Π²Π΅Ρ‚Π°.

blue

Π—Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ синСго ΠΊΠΎΠΌΠΏΠΎΠ½Π΅Π½Ρ‚Π° Ρ†Π²Π΅Ρ‚Π°.

ΠŸΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€Ρ‹ Ρ†Π²Π΅Ρ‚Π° Ρ€Π°Π·Ρ€Π΅ΡˆΠ°Π΅Ρ‚ΡΡ ΡƒΠΊΠ°Π·Ρ‹Π²Π°Ρ‚ΡŒ Π»ΠΈΠ±ΠΎ цСлочислСнными значСниями Π² Π΄ΠΈΠ°ΠΏΠ°Π·ΠΎΠ½Π΅ ΠΎΡ‚ 0 Π΄ΠΎ 255, Π»ΠΈΠ±ΠΎ ΡˆΠ΅ΡΡ‚Π½Π°Π΄Ρ†Π°Ρ‚Π΅Ρ€ΠΈΡ‡Π½Ρ‹ΠΌΠΈ значСниями Π² Π΄ΠΈΠ°ΠΏΠ°Π·ΠΎΠ½Π΅ ΠΎΡ‚ 0x00 Π΄ΠΎ 0xFF.

Π’ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅ΠΌΡ‹Π΅ значСния

Ѐункция Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ блиТайший ΠΊ Π·Π°Π΄Π°Π½Π½ΠΎΠΌΡƒ индСкс Ρ†Π²Π΅Ρ‚Π° Π² ΠΏΠ°Π»ΠΈΡ‚Ρ€Π΅ изобраТСния.

Бписок измСнСний

ВСрсия ОписаниС
8.0.0 ΠŸΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ image Ρ‚Π΅ΠΏΠ΅Ρ€ΡŒ ΠΏΡ€ΠΈΠ½ΠΈΠΌΠ°Π΅Ρ‚ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ GdImage; Ρ€Π°Π½ΡŒΡˆΠ΅ ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ ΠΏΡ€ΠΈΠ½ΠΈΠΌΠ°Π» ΠΊΠΎΡ€Ρ€Π΅ΠΊΡ‚Π½Ρ‹ΠΉ gd-рСсурс (resource).

ΠŸΡ€ΠΈΠΌΠ΅Ρ€Ρ‹

ΠŸΡ€ΠΈΠΌΠ΅Ρ€ #1 Поиск Π½Π°Π±ΠΎΡ€Π° Ρ†Π²Π΅Ρ‚ΠΎΠ² изобраТСния

<?php

// Π‘ΠΎΠ·Π΄Π°Π½ΠΈΠ΅ изобраТСния ΠΈ ΠΏΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΠΎΠ²Π°Π½ΠΈΠ΅ Π΅Π³ΠΎ Π² ΠΏΠ°Π»ΠΈΡ‚Ρ€ΠΎΠ²ΠΎΠ΅
$im = imagecreatefrompng('figures/imagecolorclosest.png');
imagetruecolortopalette($im, false, 255);

// Π¦Π²Π΅Ρ‚Π° для поиска (RGB)
$colors = array(
array(
254, 145, 154),
array(
153, 145, 188),
array(
153, 90, 145),
array(
255, 137, 92)
);

// ΠŸΡ€ΠΎΡ…ΠΎΠ΄ ΠΏΠΎ ΠΊΠ°ΠΆΠ΄ΠΎΠΌΡƒ Ρ†Π²Π΅Ρ‚Ρƒ ΠΈ поиск блиТайшСго ΠΊ Π½Π΅ΠΌΡƒ Π² ΠΏΠ°Π»ΠΈΡ‚Ρ€Π΅.
// Π’ΠΎΠ·Π²Ρ€Π°Ρ‚ Π½ΠΎΠΌΠ΅Ρ€Π° ΠΏΠΎ порядку, RGB искомого Ρ†Π²Π΅Ρ‚Π° ΠΈ Π½Π°ΠΉΠ΄Π΅Π½Π½ΠΎΠ΅ RGB соотвСтствиС
foreach ($colors as $id => $rgb) {
$result = imagecolorclosest($im, $rgb[0], $rgb[1], $rgb[2]);
$result = imagecolorsforindex($im, $result);
$result = "({$result['red']}, {$result['green']}, {$result['blue']})";

echo
"#$id: Поиск ($rgb[0], $rgb[1], $rgb[2]); Π‘Π»ΠΈΠΆΠ°ΠΉΡˆΠ΅Π΅ сходство: $result.\n";
}

?>

Π’Ρ‹Π²ΠΎΠ΄ ΠΏΡ€ΠΈΠ²Π΅Π΄Ρ‘Π½Π½ΠΎΠ³ΠΎ ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π° Π±ΡƒΠ΄Π΅Ρ‚ ΠΏΠΎΡ…ΠΎΠΆ Π½Π°:

#0: Поиск (254, 145, 154); Π‘Π»ΠΈΠΆΠ°ΠΉΡˆΠ΅Π΅ сходство: (252, 150, 148).
#1: Поиск (153, 145, 188); Π‘Π»ΠΈΠΆΠ°ΠΉΡˆΠ΅Π΅ сходство: (148, 150, 196).
#2: Поиск (153, 90, 145); Π‘Π»ΠΈΠΆΠ°ΠΉΡˆΠ΅Π΅ сходство: (148, 90, 156).
#3: Поиск (255, 137, 92); Π‘Π»ΠΈΠΆΠ°ΠΉΡˆΠ΅Π΅ сходство: (252, 150, 92).

Π‘ΠΌΠΎΡ‚Ρ€ΠΈΡ‚Π΅ Ρ‚Π°ΠΊΠΆΠ΅

  • imagecolorexact() - ΠŸΠΎΠ»ΡƒΡ‡Π°Π΅Ρ‚ индСкс Ρ†Π²Π΅Ρ‚Π°
  • imagecolorclosestalpha() - ΠŸΠΎΠ»ΡƒΡ‡Π°Π΅Ρ‚ блиТайший индСкс Ρ†Π²Π΅Ρ‚Π° с ΡƒΡ‡Ρ‘Ρ‚ΠΎΠΌ прозрачности
  • imagecolorclosesthwb() - ΠŸΠΎΠ»ΡƒΡ‡Π°Π΅Ρ‚ индСкс Ρ†Π²Π΅Ρ‚Π° с Π·Π°Π΄Π°Π½Π½Ρ‹ΠΌΠΈ Ρ‚ΠΎΠ½ΠΎΠΌ, Π±Π΅Π»ΠΈΠ·Π½ΠΎΠΉ ΠΈ Π·Π°Ρ‚Π΅ΠΌΠ½Π΅Π½ΠΈΠ΅ΠΌ
οΌ‹Π”ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ

ΠŸΡ€ΠΈΠΌΠ΅Ρ‡Π°Π½ΠΈΡ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ 4 notes

up
4
info at codeworx dot ch ΒΆ
14 years ago
Here is a function that compares two HEX colors for similarity. This can be useful if you want to detect colors that are not different enough to see for the naked eye. It returns a bool: TRUE if the colors are similar to each other (within tolerance) or FALSE if they are different enough.
I tested a few colors and came up with a tolerance of 35 (rgb value - should be between 0 and 255) but you can change that tolerance by passing a third parameter to the function.

<?php
function compareColors ($col1, $col2, $tolerance=35) {
    $col1Rgb = array(
        "r" => hexdec(substr($col1, 0, 2)),
        "g" => hexdec(substr($col1, 2, 2)),
        "b" => hexdec(substr($col1, 4, 2))
    );
    $col2Rgb = array(
        "r" => hexdec(substr($col2, 0, 2)),
        "g" => hexdec(substr($col2, 2, 2)),
        "b" => hexdec(substr($col2, 4, 2))
    );
    return ($col1Rgb['r'] >= $col2Rgb['r'] - $tolerance && $col1Rgb['r'] <= $col2Rgb['r'] + $tolerance) && ($col1Rgb['g'] >= $col2Rgb['g'] - $tolerance && $col1Rgb['g'] <= $col2Rgb['g'] + $tolerance) && ($col1Rgb['b'] >= $col2Rgb['b'] - $tolerance && $col1Rgb['b'] <= $col2Rgb['b'] + $tolerance);
}
?>
up
1
Hayley Watson ΒΆ
8 years ago
RGB space isn't the best choice for measuring the distance between two colours, since it ignores, for example, the fact that we count both dark green and light green as "green" (the RGB distance between #000000 and #7f7f7f is the same as the distance between #000000 and #5443c0 - a slightly darkened SlateBlue).

A better choice of colour space that conforms better to how colours are perceived is the so-called Lab space, which measures colours according to how light/dark, red/green, and yellow/blue they are. (There are still better models, but they come at the expense of increased computation.)

<?php

function warp1($c)
{
    if($c > 10.3148)
    {
        return pow((561 + 40*$c)/10761, 2.4);
    }
    else
    {
        return $c / 3294.6;
    }
}
function warp2($c)
{
    if($c > 0.008856)
    {
        return pow($c, 1/3);
    }
    else
    {
        return 7.787 * $c + 4/29;
    }
}
function rgb2lab($rgb)
{
    [$red, $green, $blue] = array_map('warp1', $rgb);

    $x = warp2($red * 0.4339 + $green * 0.3762 + $blue * 0.1899);
    $y = warp2($red * 0.2126 + $green * 0.7152 + $blue * 0.0722);
    $z = warp2($red * 0.0178 + $green * 0.1098 + $blue * 0.8730);

    $l = 116*$y - 16;
    $a = 500 * ($x - $y);
    $b = 200 * ($y - $z);
    
    return array_map('intval', [$l, $a, $b]);
}

function generate_palette_from_image($image)
{
    $pal = [];
    $width = imagesx($image);
    $height = imagesy($image);
    for($x = 0; $x < $width; ++$x)
    {
        for($y = 0; $y < $height; ++$y)
        {
            $pal[] = imagecolorat($image, $x, $y);
        }
    }
    return array_map(function($col)use($image)
    {
        $rgba = imagecolorsforindex($image, $col);
        return [$rgba['red'], $rgba['green'], $rgba['blue']];
    },    array_unique($pal));
}

function closest_rgb_in_palette($rgb, $palette)
{
    // Quick return when the exact
    // colour is in the palette.
    if(($idx = array_search($rgb, $palette)) !== false)
    {
        return $idx;
    }
    [$tl, $ta, $tb] = rgb2lab($rgb);
    $dists = array_map(function($plab)use($tl, $ta, $tb)
    {
        [$pl, $pa, $pb] = $plab;
        $dl = $pl - $tl;
        $da = $pa - $ta;
        $db = $pa - $tb;
        return $dl * $dl + $da * $da + $db * $db;
    }, array_map('rgb2lab', $palette));
    return array_search(min($dists), $dists);
}

function closest_rgb_in_image($rgb, $image)
{
    $palette = generate_palette_from_image($image);
    return $palette[closest_rgb_in_palette($rgb, $palette)];
}

$lena = imagecreatefrompng('lena.png');
$red = closest_rgb_in_image([255,0,0],$lena);
echo join(' ', $red);  // 228 71 82

?>

If you're going to be matching a lot of colours to a palette, you may want to precompute and reuse the Lab palette, instead of generating it fresh each time as done here.
up
-1
MagicalTux at FF dot st ΒΆ
20 years ago
A way to get each time an answer :

<?php
function imagegetcolor($im, $r, $g, $b) {
        $c=imagecolorexact($im, $r, $g, $b);
        if ($c!=-1) return $c;
        $c=imagecolorallocate($im, $r, $g, $b);
        if ($c!=-1) return $c;
        return imagecolorclosest($im, $r, $g, $b);
}
?>

If the *exact* color is found in the image, it will be returned. If we don't have the exact color, we try to allocate it. If we can't allocate it, we return the closest color in the image.
up
-1
Vikrant Korde <vakorde at hotmail dot com> ΒΆ
22 years ago
This functuion is useful when you are dealing with previously present images like .png, .jpg, etc. You can use this function for writing a text on the image.

For me the function imagecolorallocate() was returning the -1 value. after lot of RnD and site search i found a function use of imagecolorclosest(). This solved my problem of writing the text on the image with customised color. 

Actually previously it was writing on the image but the color was not distinct. It was using the same color as of that background image. 

The following code segment was fine with me.

header ("Content-type: image/jpeg"); 
$im = imagecreatefromjpeg("BlankButton.jpg");
$white = imageColorClosest($im, 255,255,255);
// this is for TTF fonts
imagettftext ($im, 20, 0, 16, 30, $white, "/usr/X11R6/lib/X11/fonts/TTF/luximb.ttf", "Vikrant"); 

//this is for notmal font
imagestring($im, 4, 0,0,"Korde", $white);
imagejpeg($im,"",150); 
imagedestroy ($im);