PHP - 快速循环图像像素

时间:2017-03-10 23:55:22

标签: php loops optimization ocr

下午好,SO社区,

我一直致力于一个需要一些光学字符识别的项目。我试图让项目保持轻便和便携,因此安装第三方程序不会成为一种选择。

无论如何,我决定用PHP编写自己的OCR,但它在图像中循环很慢。我目前正在做的方式是两个嵌套for循环。我尝试遍历给定的图像(在这种情况下,图像是PNG。263x55像素),并将rgba写入文本文件。 (格式:' rgba(0,0,0,0)')。由于它使用PHP,因此alpha介于0和127之间。

我的代码有效,但速度很慢,而且图像真的不大。你能想出我能加速的方法吗?

提前致谢,

<?php
// To prevent the script from timing out
ini_set('max_execution_time', 0);
If (isset($_GET["Image"])) {
    $pImage = $_GET["Image"];
} Else {
    $pImage = "1";
}
parseImage($pImage);

// END TEST SYSTEM

Function parseImage($ImgNum) {
    Echo "Parsing Image $ImgNum";
    $logFile = "Image$ImgNum.txt";
    $fHandle = fopen($logFile, "w");
    If ($ImgNum != 1 AND $ImgNum != 2 AND $ImgNum != 3 AND $ImgNum != 4 AND $ImgNum != 5 AND $ImgNum != 6) {
        Echo "Error: Image number is invalid.";
        Exit();
    }

    // Start Optical Character Recognition
    $Image = "https://www.example.com/img/Image$ImgNum.png";
    $size   = getimagesize($Image);
    $width  = $size[0];
    $height = $size[1];
    $ctrH = 0;
    $ctrW = 0;

    for($x=1;$x<=$width;$x++) {
        for($y=1;$y<=$height;$y++) {
            $pixel = getPixel($Image, $x, $y);
            fwrite($fHandle, $pixel . "\n");
            $ctrH ++;
        }
        $ctrW ++;
    }
    fclose($fHandle);

    Echo "Analyzing <a href='$Image'>$Image</a><br />";
    Echo $ctrW . "px wide<br />";
    Echo ($ctrH / $ctrW) . "px tall<br />";
}


function getPixel($image, $x, $y) {
    // Echo "<br />Reading $image. X: $x - Y: $y<br />";
    $im = imagecreatefrompng($image);
    $rgb = imagecolorat($im, $x, $y);
    $colors = imagecolorsforindex($im, $rgb);
    $r = $colors["red"];
    $g = $colors["green"];
    $b = $colors["blue"];
    $a = $colors["alpha"];
    $print = "Pixel (" . $x . "x" . $y . "): rgba($r, $g, $b, $a)";
    return $print;
}
?>

1 个答案:

答案 0 :(得分:1)

您的问题是,每次通过在getPixel函数中使用imagecreatefrompng查找像素的值时,您都在创建图像。将它移到getPixel函数和嵌套循环之外,然后传入它。

通过这种方式,您不会将图像爆炸到内存中,查找像素,然后在函数退出时将垃圾收集器破坏,只会在下一个像素上再次执行此操作。