环境
1.mac os
2.android studio 3.1.3
3.tess-two 8.0.0
下载地址: https://github.com/rmtheis/tess-two
tesseract地址:https://github.com/tesseract-ocr/tesseract
注:tesseract没有提供详细的android接口,这里使用tess-two
1.build.gradle引入tess-two
dependencies {
implementation 'com.rmtheis:tess-two:8.0.0'
}
2.导入识别库 *.traineddata
3.加载识别库
package cn.xylink.ocr.image.cn.xylink.ocr.image.config;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import com.googlecode.tesseract.android.TessBaseAPI;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import cn.xylink.ocr.image.R;
/**
* @author hecj
*/
public class TessBaseAPIFactory {
static TessBaseAPI tessApi;
static String datapath= Environment.getExternalStorageDirectory().getAbsolutePath()+ "/tesseract";
static final String DEFAULT_LANGUAGE = "xylinkfont";
public static TessBaseAPI getTessBaseAPIInstance(Context context){
try {
tessApi = new TessBaseAPI();
File dir = new File(datapath);
tessApi.setDebug(true);
if (!dir.exists()) {
dir.mkdirs();
}
File tessdatadir = new File(datapath+"/tessdata");
if(!tessdatadir.exists()){
tessdatadir.mkdirs();
}
InputStream input = context.getResources().openRawResource(R.raw.xylinkfont);
File file = new File(dir+"/tessdata", "xylinkfont.traineddata");
FileOutputStream output = new FileOutputStream(file);
byte[] buff = new byte[1024];
int len = 0;
while ((len = input.read(buff)) != -1) {
output.write(buff, 0, len);
}
input.close();
output.close();
boolean success = tessApi.init(datapath, DEFAULT_LANGUAGE);
if (success) {
Log.i("tess", "load Tesseract OCR Engine successfully...");
} else {
Log.i("tess", "WARNING:could not initialize Tesseract data...");
}
} catch (Exception ex){
ex.printStackTrace();
}
return tessApi;
}
}
使用:
/**
* 识别
*/
private void ocr (){
String resultText = "";
try {
Bitmap bitmap =((BitmapDrawable) ((ImageView) imageView).getDrawable()).getBitmap();
TessBaseAPI tessApi = TessBaseAPIFactory.getTessBaseAPIInstance(context);
tessApi.setImage(bitmap);
// 识别结果
resultText = tessApi.getUTF8Text();
tessApi.end();
}catch (Exception ex){
Log.e("tess",ex.getMessage());
ex.printStackTrace();
}finally {
text.setText("识别结果:"+resultText);
}
}