LoginSignup
14
11

More than 5 years have passed since last update.

JS向けOCR Tesseract.jsのドキュメント和訳

Last updated at Posted at 2018-10-07

背景

スマホで撮影した英単語に対する和訳をしてくれる辞書を作りたくてOCRに触る。
撮影→英単語検出(OCR)→辞書検索/辞書登録
という処理をいちいちローカル環境に画像を保存することなく実現したいのとアンドロイドアプリの開発経験がないのでWebアプリケーションとして実現したい。そこでTesseractというOCRライブラリがJavascriptで簡単に使えると聞いて使ってみたいと思った。
取りあえずドキュメントの和訳を以下に示す。
筆者が今のところTesseract.jsをうまく動かせていないので、理解しきれていない所もあり、また誤訳、訳せなかった部分もあります、ご了承下さい。

以下和訳

ソース
※注意:筆者は英語が苦手なので、誤訳がありえます

Tesseract.js

Tesseract.jsは画像から数多の言語を検出するJavascriptのライブラリです。
対応言語と言語の略称はこちら

Tesseract.jsはスクリプトタグ、 webpack/Browserify、Node.jsと共に働きます。これらをインストールすると、ライブラリの使用は簡単で

sample.js
Tesseract.recognize(myImage)
       .progress(function  (p) { console.log('progress', p)    })
       .then(function (result) { console.log('result', result) })

とするだけです。
このAPIについてより詳しい処理についてはドキュメントをご確認下さい。

由来

Tesseract.jsはTesseract OCRエンジンをemscripten portでラップしたものになります

インストール

Tesseract.jsは
ローカル環境に落としたコピーかCDN経由で<script>タグから読み込み
npm経由でwebpack/Browserifyを
npm経由でNode.jsを
で読み込むことで利用することが出来ます。
このAPIについてより詳しい処理についてはドキュメントをご確認下さい。

<script/>

以下のようにすることでCDNを介して簡単にインクルードすることが出来ます

sample.html
<script src='https://cdn.rawgit.com/naptha/tesseract.js/1.0.10/dist/tesseract.js'></script>

スクリプトにインクルードした後は、Tesseractの変数はスクリプト全体で(globalで)定義されます!

依存

まず以下のどちらかをします。

> yarn add tesseract.js
> npm install tesseract.js --save

現在Tesseract.jsはv6.8.0以上のNode.jsを必要とします。

使い方

以下のどちらかで

var Tesseract = require('tesseract.js')
import Tesseract from 'tesseract.js'

ドキュメント

  • Tesseract.recognize
    • 簡単な例
    • より複雑な例
  • Tesseract.detect
  • ImageLike
  • TesseractJob
    • TesseractJob.progress
    • TesseractJob.then
    • TesseractJob.catch
    • TesseractJob.finally
  • Local Installation
    • corePath
    • workerPath
    • langPath
  • Contributing
    • Development
    • Building Static Files
    • Send us a Pull Request!

Tesseract.recognize(image: ImageLike[, options]) -> TesseractJob

画像のどこに、どのような文字があるかを解析します。

画像は十分に高解像度である必要があります。同じ画像でもrecognizeを呼ぶ前に拡大することで結果が改善されることもあり得ます。

  • imageはImageLikeオブジェクトです
  • optionは指定しないか、対応言語リストに含まれる短い言語コードか、以下の簡素なjsonオブジェクトを指定することが出来ます。

この関数はTesseractJob型を返します。この型のthenprogresscatchfinallyメソッドは結果に働きかけることが出来ます。

簡単な例

Tesseract.recognize(myImage)
.then(function(result){
    console.log(result)
})

より複雑な例

// 画像が’e’を含まないスペイン語だと知っていたとする:
Tesseract.recognize(myImage, {
    lang: 'spa',
    tessedit_char_blacklist: 'e'
})
.then(function(result){
    console.log(result)
})

Tesseract.detect(image: ImageLike) -> TesseractJob

画像が何語で書かれているかを解析します。

  • imageはImageLikeオブジェクトです。

この関数はTesseractJob型を返します。この型のthenprogresscatchfinallyメソッドは結果に働きかけることが出来ます。

Tesseract.detect(myImage)
.then(function(result){
    console.log(result)
})

ImageLike

主要なTesseract.jsの関数はimageパラメーターを持ちます。これは画像様なものではなくてはいけません。何が画像様と考えられるかについてはブラウザから実行するかNodeJSを経由するかによって異なります。

ブラウザの場合は

  • img video canvas要素
  • canvas.getContext('2d')によって返されるCanvasRenderingContext2Dオブジェクト
  • ファイルの選択かドラッグ&ドロップによるファイル
  • Blobオブジェクト
  • width、height、dataプロパティを持つImageDataインスタンス
  • 画像へのパスかURL(その画像はローカル環境にあるか、CORSによってアクセスできなければいけません)

Node.jsの場合は
- ローカル環境の画像へのパス
- PNGかJPEG形式のインスタンスのバッファー
- width、height、dataプロパティを持つImageDataインスタンス

TesseractJob

TesseractJobはrecognizedetectの返り値で、ES6でよく見られるように、thencatchメソッドを持ちます。更にfinallyメソッドも持ち、これによりジョブの途中で中断できます。重大な相違点としてこれらのメソッドは新たなオブジェクトではなく、jobオブジェクトへの参照を返します。

典型例.js
Tesseract.recognize(myImage)
    .progress(message => console.log(message))
    .catch(err => console.error(err))
    .then(result => console.log(result))
    .finally(resultOrError => console.log(resultOrError))
これと同じです
var job1 = Tesseract.recognize(myImage);
job1.progress(message => console.log(message));
job1.catch(err => console.error(err));
job1.then(result => console.log(result));
job1.finally(resultOrError => console.log(resultOrError));

TesseractJob.progress(callback: function) -> TesseractJob

ジョブが進行したときに呼ばれるコールック関数をセットすることができます。
callback is a function with the signature callback(progress) where progress is a json object.(翻訳できず)

Tesseract.recognize(myImage)
    .progress(function(message){console.log('progress is: ', message)})

結果の例
progress is: {loaded_lang_model: "eng", from_cache: true}
progress is: {initialized_with_lang: "eng"}
progress is: {set_variable: Object}
progress is: {set_variable: Object}
progress is: {recognized: 0}
progress is: {recognized: 0.3}
progress is: {recognized: 0.6}
progress is: {recognized: 0.9}
progress is: {recognized: 1}

TesseractJob.then(callback: function) -> TesseractJob

ジョブが完全に完了したときに呼ばれるコールバック関数をセットします。
callback is a function with the signature callback(result) where result is a json object.(翻訳できず)

Tesseract.recognize(myImage)
    .then(function(result){console.log('result is: ', result)})

結果の例
result is: {
blocks: Array[1]
confidence: 87
html: "<div class='ocr_page' id='page_1' ..."
lines: Array[3]
oem: "DEFAULT"
paragraphs: Array[1]
psm: "SINGLE_BLOCK"
symbols: Array[33]
text: "Hello World↵from beyond↵the Cosmic Void↵↵"
version: "3.04.00"
words: Array[7]
}

TesseractJob.catch(callback: function) -> TesseractJob

ジョブの失敗時に実行されるコールバック関数をセットします。
callback is a function with the signature callback(error) where error is a json object.(翻訳できず)

TesseractJob.finally(callback: function) -> TesseractJob

ジョブの成否に関わらず実行されるコールバック関数をセットします。
callback is a function with the signature callback(resultOrError) where resultOrError is a json object.(翻訳できず)

ローカル環境へのインストール

ブラウザの場合、tesseract.jsはシンプルな方法でAPI層を提供します。これは内部的にリクエストのハンドルのためにWebWorkerを開きます。このWebWorkerはEmscriptenによって作られたCDNにホストされているtesseract.js-coreを読み込みます。そしてそれは他のCDNから動的にlanguageファイルを読み込みます。
それゆえCDNからtesseract.jsを読み込むことが進められます。
しかしどうしても自身のローカルファイルから読み込む必要がある場合はTesseract.create関数を使うことでworker、language、coreのパスを指定することが出来ます。

window.Tesseract = Tesseract.create({
    workerPath: '/path/to/worker.js',
    langPath: 'https://cdn.rawgit.com/naptha/tessdata/gh-pages/3.02/',
    corePath: 'https://cdn.rawgit.com/naptha/tesseract.js-core/0.1.0/index.js',
})

corePath

core libraryの場所を指定する文字列です。https://cdn.rawgit.com/naptha/tesseract.js-core/master/index.jsがデフォルトです。

workerPath

tesseract.worker.jsファイルの場所を指定します。異なるファイルを使いたい場合はTesseract.recognize Tesseract.detectを呼び出す前に設定します。

langPath

tesseract言語ファイルの場所を指定します。
言語ファイルのURLは以下の式で計算されます。
langPath + langCode + '.traineddata.gz'
異なる言語ファイルを使いたい場合はTesseract.recognize Tesseract.detectを呼び出す前に設定します。

貢献

開発

tesseract.jsの開発のコピーを実行するためには、まずはこのようにクローンします

> git clone https://github.com/naptha/tesseract.js.git

その後に以下のようにしてcd tesseract.js && npm install && npm startをします。

> cd tesseract.js
> npm install && npm start

  ... a bunch of npm stuff ...

  Starting up http-server, serving ./
  Available on:
    http://127.0.0.1:7355
    http://[your ip]:7355

その後お好みのブラウザでhttp://localhost:7355/examples/file-input/demo.htmlを開きます。(localhostはhogehoge?)
devServerはソースフォルダ内のファイルを変更したら自動的にtesseract.js tesseract.worker.jsを更新します。

静的ファイル(static file)の構築

開発の手順に従ってクローンしてnpm installを実行したのち、以下のコマンドで配布物フォルダ(dist folder)静的ライブラリに構築することが出来ます。

> npm run build

Pull Requestを送ってね!

Thanks(^^)

和訳は以上になります

14
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
11