php计算两张照片的相似度,范围:0-100

发布于:2024-07-13 ⋅ 阅读:(122) ⋅ 点赞:(0)

可以是本地图片也可以是网络图片

需要gd库

/**

 * 计算图片相似度

 * @param $imagePath1 string 图片路径1

 * @param $imagePath2 string 图片路径2

 * @return float|int 0(完全两张图片)-100(两张一模一样的图片)

 */

function calculateImageSimilarity($imagePath1, $imagePath2)

{

    // 加载图片1

    $image1 = imagecreatefromstring(file_get_contents($imagePath1));

    if (!$image1) {

        echo "image1加载失败\n";

        return 0; // 加载失败,相似度为 0

    }

    // 加载图片2

    $image2 = imagecreatefromstring(file_get_contents($imagePath2));

    if (!$image2) {

        echo "image2加载失败\n";

        imagedestroy($image1);

        return 0; // 加载失败,相似度为 0

    }

    // 获取图片尺寸

    $width1 = imagesx($image1);

    $height1 = imagesy($image1);

    $width2 = imagesx($image2);

    $height2 = imagesy($image2);

    // 确保两张图片尺寸一致

    if ($width1 != $width2 || $height1 != $height2) {

        echo "图片尺寸不一致\n";

        imagedestroy($image1);

        imagedestroy($image2);

        return 0; // 尺寸不一致,相似度为 0

    }

    // 获取图片1的像素总数

    $totalPixels = $width1 * $height1;

    var_export("totalPixels:" . $totalPixels . "\n");

    // 计算差异像素数

    $diffPixels = 0;

    for ($x = 0; $x < $width1; $x++) {

        for ($y = 0; $y < $height1; $y++) {

            $rgb1 = imagecolorat($image1, $x, $y);

            $rgb2 = imagecolorat($image2, $x, $y);

            // 比较 RGB 值

            $r1 = ($rgb1 >> 16) & 0xFF;

            $g1 = ($rgb1 >> 8) & 0xFF;

            $b1 = $rgb1 & 0xFF;

            $r2 = ($rgb2 >> 16) & 0xFF;

            $g2 = ($rgb2 >> 8) & 0xFF;

            $b2 = $rgb2 & 0xFF;

            // 比较 RGB 值的差异

            $diffPixels += abs($r1 - $r2) + abs($g1 - $g2) + abs($b1 - $b2);

        }

    }

    // 将差异归一化到0-255范围内

    $diffPixels /= 3;

    // 计算相似度

    $similarity = max(0, min(100, 100 - ($diffPixels / ($totalPixels * 255) * 100)));

    var_export("diffPixels:" . $diffPixels . "\n");

    // 释放图片资源

    imagedestroy($image1);

    imagedestroy($image2);

    return $similarity;

}