PHP项目中如何使用Tesseract OCR?

wen PHP项目 4

本文目录导读:

PHP项目中如何使用Tesseract OCR?

  1. 方法一:通过exec()调用命令行(推荐)
  2. 方法二:使用PHP扩展(不推荐)
  3. 使用Composer包
  4. 图片预处理(提高识别率)
  5. 实用技巧
  6. 注意事项

在PHP项目中使用Tesseract OCR,主要有两种方式:

通过exec()调用命令行(推荐)

安装Tesseract

Ubuntu/Debian:

sudo apt-get update
sudo apt-get install tesseract-ocr
sudo apt-get install tesseract-ocr-chi-sim  # 中文语言包

macOS:

brew install tesseract
brew install tesseract-lang  # 安装所有语言包

Windows:

  • 下载安装程序:https://github.com/UB-Mannheim/tesseract/wiki
  • 添加到系统PATH环境变量

基础PHP代码示例

<?php
class OCRService {
    private $tesseractPath;
    private $language;
    public function __construct($tesseractPath = 'tesseract', $language = 'eng') {
        $this->tesseractPath = $tesseractPath;
        $this->language = $language;
    }
    public function recognize($imagePath) {
        if (!file_exists($imagePath)) {
            throw new Exception("图片文件不存在: " . $imagePath);
        }
        // 构建命令
        $cmd = sprintf(
            '%s %s stdout -l %s 2>/dev/null',
            escapeshellcmd($this->tesseractPath),
            escapeshellarg($imagePath),
            escapeshellarg($this->language)
        );
        // 执行命令
        $output = shell_exec($cmd);
        return trim($output);
    }
}
// 使用示例
try {
    $ocr = new OCRService('tesseract', 'eng+chi_sim'); // 英文+中文
    $result = $ocr->recognize('/path/to/image.png');
    echo "识别结果:\n" . $result;
} catch (Exception $e) {
    echo "错误:" . $e->getMessage();
}

高级用法示例

<?php
class AdvancedOCR {
    private $tesseractPath;
    public function __construct($tesseractPath = 'tesseract') {
        $this->tesseractPath = $tesseractPath;
    }
    /**
     * 识别图片中的文字
     */
    public function recognize($imagePath, $options = []) {
        $defaultOptions = [
            'language' => 'eng',
            'psm' => 3,         // 页面分割模式
            'oem' => 3,         // OCR引擎模式
        ];
        $options = array_merge($defaultOptions, $options);
        // 创建临时文件用于输出
        $tempOutput = tempnam(sys_get_temp_dir(), 'ocr_');
        // 构建命令
        $cmd = sprintf(
            '%s %s %s -l %s --psm %d --oem %d 2>&1',
            escapeshellcmd($this->tesseractPath),
            escapeshellarg($imagePath),
            escapeshellarg($tempOutput),
            escapeshellarg($options['language']),
            (int)$options['psm'],
            (int)$options['oem']
        );
        // 执行命令
        exec($cmd, $output, $returnCode);
        if ($returnCode !== 0) {
            throw new Exception("OCR识别失败: " . implode("\n", $output));
        }
        // 读取结果
        $result = file_get_contents($tempOutput . '.txt');
        // 清理临时文件
        @unlink($tempOutput);
        @unlink($tempOutput . '.txt');
        return trim($result);
    }
    /**
     * 获取支持的语��列表
     */
    public function getAvailableLanguages() {
        $cmd = $this->tesseractPath . ' --list-langs 2>&1';
        exec($cmd, $output);
        // 解析输出
        $languages = [];
        $start = false;
        foreach ($output as $line) {
            if (strpos($line, 'List of available languages') !== false) {
                $start = true;
                continue;
            }
            if ($start && trim($line)) {
                $languages[] = trim($line);
            }
        }
        return $languages;
    }
}
// 使用示例
$ocr = new AdvancedOCR();
// 基本使用
$text = $ocr->recognize('document.jpg', ['language' => 'chi_sim']);
echo "识别文字:\n" . $text;
// 不同的PSM模式
$text = $ocr->recognize('text_block.jpg', [
    'language' => 'eng',
    'psm' => 6    // 假设为统一的文本块
]);
// 获取可用语言
$languages = $ocr->getAvailableLanguages();
print_r($languages);

使用PHP扩展(不推荐)

安装扩展

# 通过PECL安装
pecl install tesseract
# 或者在php.ini中添加
extension=tesseract.so

使用示例

<?php
$tess = new TesseractOCR();
$tess->setImage('/path/to/image.png');
$tess->setLanguage('eng+chi_sim');
$text = $tess->run();
echo $text;

使用Composer包

composer require thiagoalessio/tesseract_ocr
<?php
require 'vendor/autoload.php';
use thiagoalessio\TesseractOCR\TesseractOCR;
$text = (new TesseractOCR('image.png'))
    ->lang('eng')
    ->run();
echo $text;

图片预处理(提高识别率)

<?php
class ImagePreprocessor {
    /**
     * 图片预处理,提高OCR识别率
     */
    public function preprocess($inputPath, $outputPath = null) {
        if ($outputPath === null) {
            $outputPath = $inputPath;
        }
        // 使用ImageMagick或GD库进行处理
        $image = new Imagick($inputPath);
        // 转换为灰度图
        $image->setImageType(Imagick::IMGTYPE_GRAYSCALE);
        // 调整对比度
        $image->contrastImage(true);
        // 二值化处理
        $image->thresholdImage(0.5 * Imagick::getQuantum());
        // 去除噪点
        $image->medianFilterImage(1);
        // 保存处理后的图片
        $image->writeImage($outputPath);
        $image->destroy();
        return $outputPath;
    }
}
// 使用
$processor = new ImagePreprocessor();
$processedImage = $processor->preprocess('original.jpg', 'processed.png');
$ocr = new OCRService();
$result = $ocr->recognize($processedImage);
echo $result;

实用技巧

批量处理

<?php
function batchOCR($directory) {
    $files = glob($directory . '/*.{png,jpg,jpeg,tiff}', GLOB_BRACE);
    $results = [];
    foreach ($files as $file) {
        $ocr = new OCRService();
        $results[basename($file)] = $ocr->recognize($file);
    }
    return $results;
}

配置不同的PSM模式

// PSM模式说明:
// 0: 方向和脚本检测 (OSD)
// 1: 自动页面分割
// 2: 自动页面分割,但没有OSD
// 3: 全自动页面分割(默认)
// 4: 单一文本列
// 5: 单一垂直文本块
// 6: 单一文本块
// 7: 单一文本行
// 8: 单一单词
// 9: 单一单词(圆形)
// 10: 单一字符
$text = $ocr->recognize('line_text.jpg', ['psm' => 7]); // 单行文本

注意事项

  1. 性能考虑:OCR处理可能消耗较多资源,建议使用队列系统处理大量图片
  2. 安全考虑:注意escapeshellarg()escapeshellcmd()的使用
  3. 依赖管理:确保服务器上安装了Tesseract
  4. 错误处理:总是做好异常处理
  5. 图片质量:清晰、高对比度的图片识别率更高

最简单和推荐的方式是方法一,直接调用命令行,配合Composer包使用效果更好。

抱歉,评论功能暂时关闭!