gpt4 book ai didi

php - 使用 PHP 读取图像中的文本

转载 作者:行者123 更新时间:2023-12-02 09:02:24 24 4
gpt4 key购买 nike

我正在尝试读取此图像中的文本:

image

我想查看价格,例如EUR42721.92

我尝试了这些库:

  1. How to Create a PHP Captcha Decoder with PHP OCR Class: Recognize text & objects in graphical images - PHP Classes
  2. phpOCR: Optical Character Recognizer written in PHP

但它们不起作用。我怎样才能阅读文字?

最佳答案

试试这个(它对我有用):

$imagick = new Imagick($filePath);

$size = $imagick->getImageGeometry();
$width = $size['width'];
$height = $size['height'];
unset($size);

$textBottomPosition = $height-1;
$textRightPosition = $width;

$black = new ImagickPixel('#000000');
$gray = new ImagickPixel('#C0C0C0');

$textRight = 0;
$textLeft = 0;
$textBottom = 0;
$textTop = $height;

$foundGray = false;

for($x= 0; $x < $width; ++$x) {
for($y = 0; $y < $height; ++$y) {
$pixel = $imagick->getImagePixelColor($x, $y);
$color = $pixel->getColor();
// remove alpha component
$pixel->setColor('rgb(' . $color['r'] . ','
. $color['g'] . ','
. $color['b'] . ')');

// find the first gray pixel and ignore pixels below the gray
if( $pixel->isSimilar($gray, .25) ) {
$foundGray = true;
break;
}

// find the text boundaries
if( $foundGray && $pixel->isSimilar($black, .25) ) {
if( $textLeft === 0 ) {
$textLeft = $x;
} else {
$textRight = $x;
}

if( $y < $textTop ) {
$textTop = $y;
}

if( $y > $textBottom ) {
$textBottom = $y;
}
}
}
}

$textWidth = $textRight - $textLeft;
$textHeight = $textBottom - $textTop;
$imagick->cropImage($textWidth+10, $textHeight+10, $textLeft-5, $textTop-5);
$imagick->scaleImage($textWidth*10, $textHeight*10, true);

$textFilePath = tempnam('/temp', 'text-ocr-') . '.png';
$imagick->writeImage($textFilePath);

$text = str_replace(' ', '', shell_exec('gocr ' . escapeshellarg($textFilePath)));
unlink($textFilePath);
var_dump($text);

您需要安装 ImageMagick 扩展程序和 GOCR 才能运行它。如果您不能或不想安装 ImageMagick 扩展,我将向您发送一个 GD 版本,其中包含计算颜色距离的函数(它只是扩展的毕达哥拉斯定理)。

不要忘记设置 $filePath 值。

image parsing for cropping visualization

该图像显示它寻找灰色像素来更改 $foundGray 标志。之后,它从左侧和顶部查找第一个和最后一个像素。它使用一些填充来裁剪图像,调整生成的图像大小并将其保存到临时文件中。之后,就可以轻松使用 gocr(或任何其他 OCR 命令或库)。之后可以删除临时文件。

关于php - 使用 PHP 读取图像中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13643759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com