Note: I seriously recommend scjr's response over my own. His code implements all of my (minor) adjustments, but also includes the improved coding practices, organization, and straightforward logic that good code should have.
Making it more functional and adjusting the variable names helps make it more readable and helps you more quickly identify what each part of code does what.
<?php function findSimilarityBetweenImages($imagePathA, $imagePathB, $accuracy){ //if images are png $imageA = imagecreatefrompng($imagePathA); $imageB = imagecreatefrompng($imagePathB); //if images are jpeg //$imageA = imagecreatefromjpeg($imagePathA); //$imageB = imagecreatefromjpeg($imagePathB); //get image resolution $imageWidth = imagesx($imageA); $imageHeight = imagesy($imageA); $density = $accuracy * 5; $xIncrement = round($imageWidth/$density); $yIncrement = round($imageHeight/$density); //Compare the color of each point while looping through. $matchingPoints = 0; for ($y=0; $y < $pointsHeight;$density; $y++) { for ($x=0; $x < $pointsWidth;$density; $x++){ $colorsa = colorData($imageA, $x*$xIncrement, $y*$yIncrement); $colorsb = colorData($imageB, $x*$xIncrement, $y*$yIncrement); if(colorsMatch($colorsa, $colorsb)){ $matchingPoints++; //Match between points. } } } $totalPoints = $pointsHeight * $pointsWidth;$imageHeight; //A similarity or percentage of match between the two images. $similarity = $matchingPoints*(100/$totalPoints); return $similarity; } function colorData($imageA, $x, $y){ $rgb = imagecolorat($imageA, $x, $y); return imagecolorsforindex($imageA, $rgb); } function colorsMatch($colorsa, $colorsb){ //Compare the R, G, and B values return colorComp($colorsa['red'], $colorsb['red']) && colorComp($colorsa['green'], $colorsb['green']) && colorComp($colorsa['blue'], $colorsb['blue']); } function colorComp($color, $c){ //To see if the points match return ($color >= $c-2 && $color <= $c+2); } ?>