PHP 自动识别矫正歪斜图片

在处理图像时,有时会遇到图片因为角度问题导致歪斜的情况。针对这种情况,可以使用 PHP 的图像处理库 GD 来进行自动识别和矫正。

以下是一个简单的示例代码,演示如何使用 GD 库来实现自动矫正歪斜图片:

// 加载图像
$img = imagecreatefromjpeg('path/to/image.jpg');

// 检测角度
$angle = 0;
if (function_exists('imageistruecolor') && !imageistruecolor($img)) {
    $tmp = imagecreatetruecolor(imagesx($img), imagesy($img));
    imagecopy($tmp, $img, 0, 0, 0, 0, imagesx($img), imagesy($img));
    $img = $tmp;
}
$degrees = 10;
$width = imagesx($img);
$height = imagesy($img);
$threshold = intval(max($width, $height) * 0.25);

// 检测是否需要矫正
for ($i = -$degrees; $i <= $degrees; $i++) {
    $rotated = imagerotate($img, $i, 0);
    $histo = array();
    for ($x = 0; $x < $width; $x++) {
        for ($y = 0; $y < $height; $y++) {
            $rgb = imagecolorat($rotated, $x, $y);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            $gray = round(($r + $g + $b) / 3);
            if (!isset($histo[$y])) {
                $histo[$y] = array();
            }
            if (!isset($histo[$y][$gray])) {
                $histo[$y][$gray] = 1;
            } else {
                $histo[$y][$gray]++;
            }
        }
    }
    $max = 0;
    $total = 0;
    for ($y = 0; $y < $height; $y++) {
        $histo[$y] = array_filter($histo[$y]);
        krsort($histo[$y]);
        reset($histo[$y]);
        $first_key = key($histo[$y]);
        $max_value = $histo[$y][$first_key];
        $total += $max_value;
        if ($max_value > $max) {
            $max = $max_value;
            $max_angle = $i;
        }
    }
}

// 矫正图片
if (abs($max_angle) > $threshold) {
    $img = imagerotate($img, $max_angle, 0);
}

// 保存图像
imagejpeg($img, 'path/to/rotated-image.jpg');

?>

以上代码会自动识别图片的角度,并进行矫正。你可以根据实际情况进行调整,来获得更好的效果。

希望这篇文章能帮助到你解决图片歪斜问题!

PHP 自动识别矫正歪斜图片 - 图像处理技巧

原文地址: https://www.cveoy.top/t/topic/lj6B 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录