Reputation: 510
Good afternoon SO Community,
I've been working on a project that calls for some optical character recognition. I am trying to keep the project light and portable, so installing third party programs won't be an option here.
Anyways, I decided to write my own OCR in PHP, but it loops through the image EXTREMELY slow. The way I'm currently doing it, is two nested for loops. I'm trying to loop through a given image (In this case, the image is a PNG. 263x55 pixels), and write the rgba to a text file. (Format: 'rgba(0, 0, 0, 0)'). The alpha is between 0 and 127 since it is using PHP.
My code works, but is very slow, and the image really isn't that large. Can you think of any way I could speed this up?
Thanks in advance,
Tim
<?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;
}
?>
Upvotes: 0
Views: 568
Reputation: 869
Your issue is that you are creating the image every time you lookup the value of a pixel by having imagecreatefrompng
inside your getPixel function. Move this outside your getPixel function and nested loops, and pass it in instead.
This way you do not carry the overhead of exploding the image into memory, looking up a pixel, then having that work destroyed by the garbage collector as the function exits, only to do it all over again next pixel.
Upvotes: 1