美文网首页Android
A simplest OCR in android JUnit

A simplest OCR in android JUnit

作者: JaedenKil | 来源:发表于2019-04-09 16:28 被阅读0次
  • Implement com.rmtheis:tess-two
androidTestImplementation 'com.rmtheis:tess-two:6.0.4'
  • Take Bitmap screenshot
# In this case, I only need the top left corner of the screen
// private static UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
Bitmap takeBmpScreenshot() {
  Bitmap bmp = uiAutomation.takeScreenshot();
  return Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth() / 2, bmp.getHeight() / 2);
}
  • Download language data
In my case, I'm working on English text recognition

Please refer to English related OCR file.

  • Push related file to the target device:
Note
  1. File location MUST contains a tessdata subfolder.
// public class TessBaseAPI
File tessdata = new File(datapath + "tessdata");
if (!tessdata.exists() || !tessdata.isDirectory()) {
  throw new IllegalArgumentException("Data path must contain subfolder tessdata!");
}
  1. If the file is in the external storage, remember to request the permission.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
/sdcard/Temp/tessdata/eng.traineddata
  • Generate a method to return the recognized string from the bitmap
String getOCRResult(Bitmap bmp) {
  TessBaseAPI mTess = new TessBaseAPI();
  String data = "/sdcard/Temp/";
  mTess.init(data, "eng");
  mTess.setImage(bmp);
  return mTess.getUTF8Text();
}
Pay attention to mTess.init(data, "eng");.
  1. If you want to put the related file to /sdcard/Temp/, make a folder tessdata under /sdcard/Temp/, /sdcard/Temp/tessdata/.
    At last, put the file in that folder, /sdcard/Temp/tessdata/eng.traineddata.
    And the first parameter is /sdcard/Temp/.
  2. If targeted at English, the second parameter is eng.
  • Apply the method
Bitmap bmp = takeBmpScreenshot();
String recognition = getOCRResult(bmp);

相关文章

网友评论

    本文标题:A simplest OCR in android JUnit

    本文链接:https://www.haomeiwen.com/subject/kdciiqtx.html