Android之Tesseract OCR tess-two的使用
我的開發環境:win10 Android studio 2.2 ndk 版本r12b 手機:Honor 5x
第一步:下載檔案
第二步:編譯出so檔案
首先開啟dos命令列 win+R 鍵,輸入cmd,回車。
切換到下載的專案目錄 例如:我下載的專案目錄如下:
如果沒有配置ndk的環境變數需要這樣編譯:
例如:我的ndk路徑:
編譯命令如下:
執行命令後:
會依次編譯armeabi armea-v7a arm64-v8a mips mips64 x86 x86——64 7種不同的so,編譯時間大約40分鐘。
編譯好的so會儲存在******\tess-two\libs目錄下
第三步:匯入so檔案和java原始碼
1.如果你沒有在build.gridle中重定向so目錄,將armeabi armeabi_v7a(一般這兩個就可以了)複製到專案的src\main\jniLibs目錄下(注意jniLibs的L是大寫)。
2.匯入java原始碼
複製com資料夾下面的所有檔案到你的專案src\main\java目錄下,這樣做的好處是:不符合你要求的地方可以修改,打成jar包的話,只能檢視原始碼不能修改。
我的教訓:之前從網上下載別人編譯好的so和jar遇到了很大的坑,所以希望我的讀者朋友們自己去編譯和配置開發環境。
第四部:配製語言包tessdata
將tessdata複製到手機內建儲存的根目錄下(當然其他目錄也可以,需要在程式碼中指定路徑)
第五部:簡單使用
private static final String TESSBASE_PATH = Environment.getExternalStorageDirectory() + File.separator; private static final String DEFAULT_LANGUAGE = "eng";//英文資料包 private static final String CHINESE_LANGUAGE = "chi_sim";//中文資料包 private static final String TAG = "TessTwoActivity"; TessBaseAPI baseApi = new TessBaseAPI(); baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE); Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/text.jpg"); baseApi.setImage(bitmaps[0]); final String outputText = baseApi.getUTF8Text(); Log.e(TAG, "識別結果:" + outputText );
至於TESSDATA_PATH為什麼只指向了 根目錄+“\”,可以從TessBaseAPI類的原始碼尋找答案,原始碼如下:
/**
* Initializes the Tesseract engine with the specified language model(s). Returns
* <code>true</code> on success.
*
* @see #init(String, String)
*
* @param datapath the parent directory of tessdata ending in a forward
* slash
* @param language an ISO 639-3 string representing the language(s)
* @param ocrEngineMode the OCR engine mode to be set
* @return <code>true</code> on success
*/
public boolean init(String datapath, String language, int ocrEngineMode) {
if (datapath == null)
throw new IllegalArgumentException("Data path must not be null!");
if (!datapath.endsWith(File.separator))
datapath += File.separator;
File datapathFile = new File(datapath);
if (!datapathFile.exists())
throw new IllegalArgumentException("Data path does not exist!");
// 答案就在這裡--------------------------
File tessdata = new File(datapath + "tessdata");
if (!tessdata.exists() || !tessdata.isDirectory())
throw new IllegalArgumentException("Data path must contain subfolder tessdata!");
//noinspection deprecation
if (ocrEngineMode != OEM_CUBE_ONLY) {
for (String languageCode : language.split("\\+")) {
if (!languageCode.startsWith("~")) {
File datafile = new File(tessdata + File.separator +
languageCode + ".traineddata");
if (!datafile.exists())
throw new IllegalArgumentException("Data file not found at " + datafile);
}
}
}
boolean success = nativeInitOem(mNativeData, datapath, language, ocrEngineMode);
if (success) {
mRecycled = false;
}
return success;
}
其他問題:
1.匯入tess-two使用過程中,可能一言不合就崩潰,崩潰一次找到原因解決或者try catch捕獲異常應給出Toast 或其他提示資訊。
推薦:
推薦一個githup上面的專案,簡單描述一下:
開啟攝像頭,然後螢幕觸控調整識別框的大小,點選拍照後識別文字,有點像有道詞典的攝像頭識別單詞。
參考: