怎样创建Android OCR应用

By admin, 26 十二月, 2016

首先,我们需要有一个伟大的OCR开源软件——tesseract-oct。这个软件分两部分,一部分是源代码tesseract,另外一部分是语言数据tessdata。语言数据有上G的大小,git clone会比较吃力,建议用代理下载zip包。tesseract的FAQ文档是值得读一下的。

tesseract在Linux上编译运行不太困难。它本身有个Android的目录,但我还没有搞懂怎么用。网上搜到一个tess-two的项目帮助解决了在Android上使用tesseract的问题。

按照tess-two的build教程可以完成ndk项目的编译(但测试貌似是失败的)和Android工程的创建。

这时的tess-two是一个Android库,可供我们自己的Android库调用。过程大致如下:

  1. 创建一个基础的Android应用
  2. 把tess-two导入到我们刚创建的应用,参考:https://github.com/MagicMicky/FreemiumLibrary/wiki/Import-the-library-in-Android-Studio 
  3. 在local.properties里添加如下一行:
    ndk.dir=/Users/hgneng/software/android-ndk-r13b
  4. 重新build项目。如果有相关报错,可能需要在build.gradle里添加以下两行dependences
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.2'
classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1'

5. 把下面一行加到工程界面模块的build.gradle的dependencies里

compile project(':tess-two')

6. 之后就可以通过如下的代码引用OCR库了,参考:http://gaut.am/making-an-ocr-android-app-using-tesseract/

import com.googlecode.tesseract.android.TessBaseAPI;

。。。

TessBaseAPI baseApi = new TessBaseAPI();
// DATA_PATH = Path to the storage
// lang = for which the language data exists, usually "eng"
baseApi.init(DATA_PATH, lang);
// Eg. baseApi.init("/mnt/sdcard/tesseract/tessdata/eng.traineddata", "eng");
baseApi.setImage(bitmap);
String recognizedText = baseApi.getUTF8Text();
baseApi.end();

这里有一段旋转图片的代码,也许有用:

// _path = path to the image to be OCRed
ExifInterface exif = new ExifInterface(_path);
int exifOrientation = exif.getAttributeInt(
        ExifInterface.TAG_ORIENTATION,
        ExifInterface.ORIENTATION_NORMAL);

int rotate = 0;

switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
    rotate = 90;
    break;
case ExifInterface.ORIENTATION_ROTATE_180:
    rotate = 180;
    break;
case ExifInterface.ORIENTATION_ROTATE_270:
    rotate = 270;
    break;
}

if (rotate != 0) {
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    // Setting pre rotate
    Matrix mtx = new Matrix();
    mtx.preRotate(rotate);

    // Rotating Bitmap & convert to ARGB_8888, required by tess
    bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
}
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);

评论

Restricted HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <img src>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。
验证码
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
请输入"Drupal10"