xref: /PHP-8.2/ext/gd/tests/similarity.inc (revision 90de2aea)
1<?php
2
3/**
4 * A very simple algorithm for finding the dissimilarity between images,
5 * mainly useful for checking lossy compression.
6 */
7
8/**
9 * Gets the individual components of an RGB value.
10 *
11 * @param int $color
12 * @param int $red
13 * @param int $green
14 * @param int $blue
15 *
16 * @return void
17 */
18function get_rgb($color, &$red, &$green, &$blue)
19{
20    // assumes $color is an RGB value
21    $red = ($color >> 16) & 0xFF;
22    $green = ($color >> 8) & 0xFF;
23    $blue = $color & 0xFF;
24}
25
26/**
27 * Calculates the euclidean distance of two RGB values.
28 *
29 * @param int $color1
30 * @param int $color2
31 *
32 * @return int
33 */
34function calc_pixel_distance($color1, $color2)
35{
36    get_rgb($color1, $red1, $green1, $blue1);
37    get_rgb($color2, $red2, $green2, $blue2);
38    return sqrt(
39        pow($red1 - $red2, 2) + pow($green1 - $green2, 2) + pow($blue1 - $blue2, 2)
40    );
41}
42
43/**
44 * Calculates dissimilarity of two images.
45 *
46 * @param resource $image1
47 * @param resource $image2
48 *
49 * @return int The dissimilarity. 0 means the images are identical. The higher
50 *             the value, the more dissimilar are the images.
51 */
52function calc_image_dissimilarity($image1, $image2)
53{
54    // assumes image1 and image2 have same width and height
55    $dissimilarity = 0;
56    for ($i = 0, $n = imagesx($image1); $i < $n; $i++) {
57        for ($j = 0, $m = imagesy($image1); $j < $m; $j++) {
58            $color1 = imagecolorat($image1, $i, $j);
59            $color2 = imagecolorat($image2, $i, $j);
60            $dissimilarity += calc_pixel_distance($color1, $color2);
61        }
62    }
63    return $dissimilarity;
64}
65