1.OCR简介
OCR (Optical Character Recognition,光学字符识别)是指电子设备(例如扫描仪或数码相机)检查纸上打印的字符,通过检测暗、亮的模式确定其形状,然后用字符识别方法将形状翻译成计算机文字的过程;
2.Tesseract简介
Tesseract是Ray Smith于1985到1995年间在惠普布里斯托实验室开发的一个OCR引擎,曾经在1995 UNLV精确度测试中名列前茅。但1996年后基本停止了开发。2006年,Google邀请Smith加盟,重启该项目。目前项目的许可证是Apache 2.0。该项目目前支持Windows、Linux和Mac OS等主流平台。但作为一个引擎,它只提供命令行工具。
现阶段的Tesseract由Google负责维护,是最好的开源OCR Engine之一,并且支持中文。
主页地址:https://github.com/tesseract-ocr
在Tesseract的主页中,我们可以下载到Tesseract的源码及语言包,常用的语言包为
3.Tess-two
因为Tesseract使用C++实现的,在Android中不能直接使用,需要封装JavaAPI才能在Android平台中进行调用,这里我们直接使用TessTwo项目,tess-two是TesseraToolsForAndroid的一个git分支,使用简单,切集成了leptonica,在使用之前需要先从git上下载源码进行编译。
3.1.1 项目地址
Tess-two在git上地址为:https://github.com/rmtheis/tess-two
3.1.2 使用
在你的Android项目中,修改**build.gradle** 文件,添加如下依赖,即可使用了
1dependencies { 2 implementation 'com.rmtheis:tess-two:9.0.0' 3}
Android 代码如下:
1import android.graphics.Bitmap; 2import android.graphics.BitmapFactory; 3import android.os.Environment; 4import android.os.SystemClock; 5import android.util.Log; 6 7import com.googlecode.tesseract.android.TessBaseAPI; 8 9import java.io.File; 10import java.io.FileNotFoundException; 11import java.io.IOException; 12 13/** 14 * ocr 识别截图文本 15 * 16 */ 17public class Imagett { 18 private static String TAG = "IMAGETT"; 19 private static final String DEFAULT_LANGUAGE = "chi_sim"; 20 private static String text; 21 22 /** 23 * 24 * @param imageFile 识别的图片文件 25 * @param language 识别的语言 chi_sim : 中文, eng:英文 26 * @param refresh 是否重新获取图片 27 * @return 28 */ 29 public static String imageToText(final String imageFile, final String language, boolean refresh){ //language :简体中文 chi_sim, 英文 eng 30 if (!refresh){ 31 try { 32 return MyFile.readFile(CONST.TESSDATA + File.separator + "text.txt"); //文件读取操作 33 } catch (IOException e) { 34 e.printStackTrace(); 35 } 36 } 37 Thread t = new Thread(new Runnable() { 38 @Override 39 public void run() { 40 Bitmap bitmap = BitmapFactory.decodeFile(imageFile); 41 TessBaseAPI tessBaseAPI = new TessBaseAPI(); 42 tessBaseAPI.init(CONST.LOGPATH, language); 43 tessBaseAPI.setImage(bitmap); 44 text = tessBaseAPI.getUTF8Text(); 45// logUtil.i(TAG, "run: text " + System.currentTimeMillis() + text); 46 //识别的文本内容写入的文件中 47 try { 48 MyFile.writeFile(CONST.TESSDATA + File.separator + "text.txt", text, false); //文件写操作 49 } catch (FileNotFoundException e) { 50 e.printStackTrace(); 51 } 52 53 tessBaseAPI.end(); 54 } 55 }); 56 t.start(); 57 //等待识别完成 58 while (t.isAlive()){ 59 SystemClock.sleep(100); 60 } 61 return text; 62 } 63 }
实现的功能,将指定图片内的文字识别后输出的txt文件内