地址:https://github.com/rmtheis/tess-two
字庫下載地址:https://github.com/tesseract-ocr/tesseract/wiki/Data-Files
1:dependencies {
? ? implementation 'com.rmtheis:tess-two:9.0.0'
}
2:下載的字庫復(fù)制到項目assets里面

3:
/* mDataPath 是字庫在手機上的存儲位置*/
private String mDataPath = Environment.getExternalStorageDirectory().getAbsolutePath() +"/tessdata/";
private Bitmap bitmap;
private TextView textView;
private Handler mHandler=new Handler(){
@Override
? ? public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 0:
textView.setText(OCRresult);
imageView.setImageBitmap(bitmap);
break;
}
}
};
File parentfile =new File(mDataPath);
if (!parentfile.exists()){// 確保路徑存在
? ? parentfile.mkdir();
}
copyFiles();// 復(fù)制字庫到手機
String lang ="chi_sim+eng";// 使用簡體中文 + 英文檢測
final TessBaseAPI mTess =new TessBaseAPI();
mTess.init(Environment.getExternalStorageDirectory().getAbsolutePath(), lang);// 初始化,第一個參數(shù)為 mDataPath 的父目錄
final Long starttime = System.currentTimeMillis();// 檢測開始時間
new Thread(new Runnable() {
@Override
? ? public void run() {
// 獲取測試圖片
? ? ? ? bitmap = BitmapFactory.decodeResource(MainActivity.this.getResources(), R.drawable.text123123);
mTess.setImage(bitmap);
OCRresult =mTess.getUTF8Text();// 拿到字符串結(jié)果
? ? ? ? Long endtime = System.currentTimeMillis();// 檢測結(jié)束時間
? ? ? ? mHandler.sendEmptyMessage(0);
Log.e("test","檢測結(jié)果:"+OCRresult);
Log.e("test", (endtime -starttime)/1000 +" s");
}
}).start();
// 工具類
private void copyFiles() {
String[] datafilepaths =new String[]{mDataPath +"/chi_sim.traineddata",mDataPath +"/eng.traineddata",mDataPath +"/chi_sim_vert.traineddata"};// 拷兩個字庫過去
? ? for (String datafilepath : datafilepaths) {
copyFile(datafilepath);
}
}
private void copyFile(String datafilepath) {
try {
String filepath = datafilepath;
String[] filesegment = filepath.split(File.separator);
String filename = filesegment[(filesegment.length -1)];// 獲取字庫文件名
? ? ? ? AssetManager assetManager = getAssets();
InputStream instream = assetManager.open(filename);// 打開字庫文件
? ? ? ? OutputStream outstream =new FileOutputStream(filepath);
byte[] buffer =new byte[1024];
int read;
while ((read = instream.read(buffer)) != -1) {
outstream.write(buffer,0, read);
}
outstream.flush();
outstream.close();
instream.close();
File file =new File(filepath);
if (!file.exists()) {
throw new FileNotFoundException();
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
// 效果1 復(fù)雜圖片? 識別時間 14 s 效果不佳

// 效果2 簡單圖片 識別時間 1 s? 識別效果好

// 百度有免費的OCR 效果很好。。。