A simplest OCR in android JUnit
2019-04-09 本文已影响0人
JaedenKil
- 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
- 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!");
}
- 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");
.
- 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/
.- If targeted at English, the second parameter is
eng
.
- Apply the method
Bitmap bmp = takeBmpScreenshot();
String recognition = getOCRResult(bmp);