LoginSignup
87
89

More than 3 years have passed since last update.

【Swift】文字認識ライブラリ、TesseractOCR for iOSを試してみた

Last updated at Posted at 2015-04-23

TesseractOCR for iOSとは

画像から文字を認識してくれるライブラリです。

こんな感じ
11158157_830800740338331_858441146_n.jpg

CocoaPodから利用できるのも美味しいです。
TesseractOCR for iOS
https://cocoapods.org/?q=tess

サンプルをgithubにあげましたので、参考にしてみてください。
https://github.com/ktanaka117/TesseractTestWithSwift

導入手順

1.プロジェクトファイルを作ってPodのインストール

Podfileの中身はこんな感じです。

platform :ios, '7.0'
pod 'TesseractOCRiOS', '~> 4.0.0'

2.言語データファイルをプロジェクトにimportする

ここのリストから使用したい言語データファイルをダウンロードします。
https://code.google.com/p/tesseract-ocr/downloads/list

ダウンロードしたファイルの中にtessdataというディレクトリがあるはずなので、それを以下の画像のようにimportしてください。
スクリーンショット 2015-04-23 15.31.55.png

3.文字の入ったテスト用の画像をimportする

今回はこの画像を使いました。
test.png

4.BridgingHeaderを用意する

BridgingHeaderファイルを作成して、そのファイルの中でG8Tesseract.hをimportします。
スクリーンショット 2015-04-23 15.39.19.png

5.コードを書く

ViewController.swiftを書き換えていきます。

import UIKit

class ViewController: UIViewController, G8TesseractDelegate {

    var imageView: UIImageView = UIImageView()
    var label: UILabel = UILabel()

    let image = UIImage(named: "OCR-Sample-Japanese")

    override func viewDidLoad() {
        super.viewDidLoad()

        imageView.frame = CGRectMake(0, 0, self.view.frame.size.width, 300)
        imageView.contentMode = UIViewContentMode.ScaleAspectFit
        imageView.image = UIImage(named: "OCR-Sample-Japanese")

        label.frame = CGRectMake(0, 300,  self.view.frame.size.width, 200)
        label.lineBreakMode = NSLineBreakMode.ByCharWrapping
        label.numberOfLines = 0
        label.text = "Analyzing..."

        self.view.addSubview(imageView)
        self.view.addSubview(label)

        analyze()
    }

    func analyze() {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
            var tesseract = G8Tesseract(language: "jpn")
            tesseract.delegate = self
            tesseract.image = self.image
            tesseract.recognize()

            self.label.text = tesseract.recognizedText

            println(tesseract.recognizedText)
        })
    }

    func shouldCancelImageRecognitionForTesseract(tesseract: G8Tesseract!) -> Bool {
        return false; // return true if you need to interrupt tesseract before it finishes
    }
}

6. 出来上がり

11158157_830800740338331_858441146_n.jpg

7.オマケ

tesseract.image = self.imageで文字認識させる画像をセットしていますが、ここに入れる画像をCIFilterなどで白黒にしたり、境界線を明確にしてやったりして補正すると以下の画像のように認識率が上がったりします。

11180154_830800750338330_1805428783_n.jpg

参考サイト

iOSで手軽に文字認識
http://blog.isana.net/2014/08/ios.html

iOS で OCR
http://iti.hatenablog.jp/entry/2014/08/08/091819

87
89
1

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
87
89