Android

A simplest OCR in android JUnit

2019-04-09  本文已影响0人  JaedenKil
androidTestImplementation 'com.rmtheis:tess-two:6.0.4'
# 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);
}
In my case, I'm working on English text recognition

Please refer to English related OCR file.

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
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.
Bitmap bmp = takeBmpScreenshot();
String recognition = getOCRResult(bmp);
上一篇 下一篇

猜你喜欢

热点阅读