Google Tesseract-OCR 文字識別

地址: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 效果很好。。。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容