PHPで画像から文字抽出(tesseract_ocr)

PHP

説明

画像抽出のプログラミングと言ったら、Pythonが思い浮かぶ方が多いと思いますが、phpでもできる方法を以下に記載していきます。(今回はpng画像を使用しています。抽出精度は微妙かもしれません。)

開発環境

php8.0
tesseract 4.0.0
Debian GNU/Linux 10
Composer version 2.1.6

環境の準備

①. ocrフォルダを作成し、「thiagoalessio/tesseract_ocr」や「tesseract-ocr」などをインストールしていきます。

root@hoge:/var/www/html# apt-get update -y
root@hoge:/var/www/html# mkdir ocr
root@hoge:/var/www/html# cd ocr/
root@hoge:/var/www/html/ocr# composer require thiagoalessio/tesseract_ocr
root@hoge:/var/www/html/ocr# apt-get install tesseract-ocr tesseract-ocr-jpn
root@hoge:/var/www/html/ocr# apt-get install tesseract-ocr-jpn-*
root@hoge:/var/www/html/ocr# apt-get install -y gimagereader

↓↓↓↓↓↓日本語化(念のため)↓↓↓↓
root@hoge:/var/www/html/ocr# env |grep LANG
root@hoge:/var/www/html/ocr# export LANG=C.UTF-8
root@hoge:/var/www/html/ocr# export LANGUAGE=en_US:
root@hoge:/var/www/html/ocr# env |grep LANG
LANGUAGE=en_US:
LANG=C.UTF-8

②. ocrフォルダの中に以下の画像「test.png」を入れる(漢字・数字の入ったサンプル画像で、特に意味はありません)

③. ocrフォルダの中に「ocr.php」ファイルを入れる

<?php

require_once __DIR__ . '/vendor/autoload.php';

use thiagoalessio\TesseractOCR\TesseractOCR;
echo (new TesseractOCR('test.png'))
    ->lang('eng', 'jpn')
    ->run();

実行

①. PHPで実行

root@hoge:/var/www/html/ocr# php ocr.php
名 古屋 市 121 人
日 進 市 1029 人

②. tesseractコマンドで実行

root@hoge:/var/www/html/ocr# tesseract test.png result -l jpn
Tesseract Open Source OCR Engine v4.0.0 with Leptonica
root@hoge:/var/www/html/ocr# cat result.txt
名古屋市 121人
日進市 1029人

うーん。phpで実行した結果より、コマンドで実行した行った結果を受け取った方が、文字抽出の精度は良いかもしれません。

以上です。

コメント

タイトルとURLをコピーしました