Skip to content

Instantly share code, notes, and snippets.

@stronk7
Created March 4, 2023 10:43
Show Gist options
  • Save stronk7/d80c22606ecdc357970bf80c70c22112 to your computer and use it in GitHub Desktop.
Save stronk7/d80c22606ecdc357970bf80c70c22112 to your computer and use it in GitHub Desktop.
Compare / calculate the difference between 2 images using the Root Mean Squared Error (RMSE) metric
<?php
/**
* Calculate the Root Mean Squared Error (RMSE) metric between 2 images.
*
* Quick and dirty pure PHP implementation
* of the Root Mean Squared Error metric (RMSE)
* used to compare two images and calculate their difference:
* - Requires the php-gd extension to be available.
* - Using the four (RGB+A) channels.
* - 0-1 normalised using the max difference value.
*
* Note: The 2 images must be exactly the same size. Ensure it always.
*
* @copyright 2023 onwards Eloy Lafuente (stronk7) {@link https://stronk7.com}
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$image1 = '1.png';
$image2 = '2.png';
$nrmse = nrmse($image1, $image2);
echo "PHP NRMSE: {$nrmse}" . PHP_EOL;
function nrmse($image1, $image2): float {
$image1 = imagecreatefrompng($image1);
$image2 = imagecreatefrompng($image2);
$width = imagesx($image1);
$height = imagesy($image1);
$mse = 0;
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$rgb1 = imagecolorat($image1, $x, $y);
$rgb2 = imagecolorat($image2, $x, $y);
$red1 = ($rgb1 >> 16) & 0xFF;
$green1 = ($rgb1 >> 8) & 0xFF;
$blue1 = $rgb1 & 0xFF;
$trans1 = ($rgb1 >> 24) & 0x7F;
$red2 = ($rgb2 >> 16) & 0xFF;
$green2 = ($rgb2 >> 8) & 0xFF;
$blue2 = $rgb2 & 0xFF;
$trans2 = ($rgb2 >> 24) & 0x7F;
$mse += pow(($red1 - $red2) / 255, 2);
$mse += pow(($green1 - $green2) / 255, 2);
$mse += pow(($blue1 - $blue2) / 255, 2);
$mse += pow(($trans1 - $trans2) / 127, 2);
}
}
$mse /= $width * $height * 4;
return sqrt($mse);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment