本demo是识别0-9十张数字图片的小例子
1.资源
将armeabi和armeabi-v7a拷贝到libs目录下,奖数据集(eng.traineddata)存放在src/main/assets目录下
2.布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:id="@+id/result"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="80px"
android:text="识别结果" />
<ImageView
android:id="@+id/image"
android:layout_width="300px"
android:layout_height="300px"
android:layout_marginTop="20dp"
android:src="@drawable/ic_launcher_background" />
</LinearLayout>
3.代码
public class MainActivity extends AppCompatActivity {
public static final String TAG = "MainActivity";
private ImageView image;
private TextView resultText;
/**
* TessBaseAPI初始化用到的第一个参数,是个目录。
*/
private static final String DATAPATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
/**
* 保存到SD卡中的完整文件名
*/
private static final String LANGUAGE_PATH = DATAPATH + File.separator + "tessdata" + File.separator + "eng.traineddata";
/**
* assets中的文件名
*/
private static final String DEFAULT_LANGUAGE_NAME = "eng.traineddata";
private static final String TEST_PICTURE_PATH = "mnt/sdcard/testdata";
public static Bitmap bitmap = null;
public static int picIndex = 0;
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0x01) {
String result = msg.getData().getString("key");
resultText.setText("识别完毕,结果为:" + result);
} else if (msg.what == 0x02) {
resultText.setText("识别失败");
}
if (bitmap != null) {
image.setImageBitmap(bitmap);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
copyToSD(LANGUAGE_PATH, DEFAULT_LANGUAGE_NAME);
initView();
testOcr();
}
/**
* 将assets中的识别库复制到SD卡中
*
* @param path 要存放在SD卡中的 完整的文件名。这里是"/storage/emulated/tessdata/chi_sim.traineddata"
* @param name assets中的文件名 这里是 "chi_sim.traineddata"
*/
public void copyToSD(final String path, final String name) {
Log.i(TAG, "copyToSD: " + path);
Log.i(TAG, "copyToSD: " + name);
//如果存在就删掉
File f = new File(path);
if (f.exists()) {
f.delete();
}
if (!f.exists()) {
File p = new File(f.getParent());
if (!p.exists()) {
p.mkdirs();
}
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream is = null;
OutputStream os = null;
try {
is = this.getAssets().open(name);
File file = new File(path);
os = new FileOutputStream(file);
byte[] bytes = new byte[2048];
int len = 0;
while ((len = is.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
os.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
if (os != null)
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void testOcr() {
new Thread(new ocrHandle()).start();
}
private void initView() {
image = (ImageView) findViewById(R.id.image);
resultText = (TextView) findViewById(R.id.result);
}
private class ocrHandle implements Runnable {
@Override
public void run() {
while (true) {
String path = TEST_PICTURE_PATH + File.separator + picIndex + ".png";
// 获取Bitmap
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap tmp = BitmapFactory.decodeFile(path, options);
bitmap = tmp;
// 开始调用Tess函数对图像进行识别
TessBaseAPI tessBaseAPI = new TessBaseAPI();
tessBaseAPI.setDebug(true);
tessBaseAPI.init(DATAPATH, "eng");
tessBaseAPI.setVariable(TessBaseAPI.VAR_CHAR_WHITELIST, "0123456789"); // 识别白名单
tessBaseAPI.setVariable(TessBaseAPI.VAR_CHAR_BLACKLIST, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()_+=-[]}{;:'\"\\|~`,./<>?"); // 识别黑名单
tessBaseAPI.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SINGLE_CHAR);//设置识别模式
tessBaseAPI.setImage(tmp); //设置需要识别图片的bitmap
String inspection = tessBaseAPI.getUTF8Text();
tessBaseAPI.end();
Message message = new Message();
if (inspection == null || inspection.isEmpty()) {
message.what = 0x02;
} else {
Bundle bundle = new Bundle();
bundle.putString("key", inspection);
message.what = 0x01;
message.setData(bundle);
}
mHandler.sendMessage(message);
picIndex++;
if (picIndex >= 11) {
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
4.AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
tools:ignore="ProtectedPermissions" />