同时使用 Tesseract hocr 和 txt,或者将 Tesseracts hocr 转换为 txt

同时使用 Tesseract hocr 和 txt,或者将 Tesseracts hocr 转换为 txt

我一直在使用 Linux OCR 软件,我非常喜欢 Tesseract,尤其是与 gsan2pdf 结合使用时。Tesseract v3 或更高版本支持以 hocr 格式输出,并且 gscan2pdf 能够利用该格式创建可搜索的扫描文档 pdf。

但是,有时我也想获得纯文本版本。如上所述,对由 gscan2pdf 生成的可搜索 pdf 执行 pdftotext 并不是那么好,因为即使使用 -raw 选项,输出的布局也不能很好地复制原始物理布局。我可以在 gscan2pdf 中设置一个用户定义的命令,它将在原始扫描图像上调用 tesseract 而不使用 hocr 选项,这样就只生成纯文本,但是 ocr 对每个页面执行两次又非常耗时。有没有一种可行的方法可以将 hocr 转换为纯文本(布局与不使用 hocr 选项调用 tesseract 时生成的布局相同)或者有没有办法让 tesseract 同时输出纯文本和 hocr?

https://github.com/jbrinley/HocrConverter看起来很有希望,但对我来说不起作用。

答案1

<?php 
/**
 * Cli process that gets as 1st argument the output of tesseract ... hocr and dumps 
 * its text nodes
 * Usage: script.php in.tif.html out.txt
 */
$inFile = $argv[1];
$outFile = $argv[2];
$stream = file_get_contents($inFile);
$dom = DOMDocument::loadHTML($stream);
$out = array();
foreach ($dom->getElementsByTagName('p') as $tag) {
    $out[] = $tag->nodeValue;
}

file_put_contents($outFile, implode("\n", $out));

相关内容