OCR (Optical Character Recognition,光学字符识别)是指电子设备(例如扫描仪或数码相机)检查纸上打印的字符,通过检测暗、亮的模式确定其形状,然后用字符识别方法将形状翻译成计算机文字的过程;即,针对印刷体字符,采用光学的方式将纸质文档中的文字转换成为黑白点阵的图像文件,并通过识别软件将图像中的文字转换成文本格式,供文字处理软件进一步编辑加工的技术。如何除错或利用辅助信息提高识别正确率,是OCR最重要的课题,ICR(Intelligent Character Recognition)的名词也因此而产生。衡量一个OCR系统性能好坏的主要指标有:拒识率、误识率、识别速度、用户界面的友好性,产品的稳定性,易用性及可行性等。
Tess4J是对google tesseract ocr的java库的一种实现
1.maven添加依赖
net.sourceforge.tess4j
tess4j
3.2.1
2.工具类编辑
/*** tesseract for java,ocr(Optical Character Recognition,光学字符识别)*工具类*@authorwind*/public class Tess4jUtils {
/***从图片中提取文字,默认设置英文字库,使用classpath目录下的训练库*@parampath*@return*/public static String readChar(String path){
// JNA Interface Mapping
ITesseract instance = new Tesseract();
// JNA Direct Mapping
// ITesseract instance = new Tesseract1();
File imageFile = new File(path);
//In case you don't have your own tessdata, let it also be extracted for you
//这样就能使用classpath目录下的训练库了
File tessDataFolder = LoadLibs.extractTessResources("tessdata");
//Set the tessdata path
instance.setDatapath(tessDataFolder.getAbsolutePath());
//英文库识别数字比较准确
instance.setLanguage(Const.ENG);
return getOCRText(instance, imageFile);
}
/***从图片中提取文字*@parampath图片路径*@paramdataPath训练库路径*@paramlanguage语言字库*@return*/public static String readChar(String path, String dataPath, String language){
File imageFile = new File(path);
ITesseract instance = new Tesseract();
instance.setDatapath(dataPath);
//英文库识别数字比较准确
instance.setLanguage(language);
return getOCRText(instance, imageFile);
}
/***识别图片文件中的文字*@paraminstance*@paramimageFile*@return*/private static String getOCRText(ITesseract instance, File imageFile){
String result = null;
try {
result = instance.doOCR(imageFile);
} catch (TesseractException e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
/*String path = "src/main/resources/image/text.png";
System.out.println(readChar(path));*/
String ch = "src/main/resources/image/ch.png";
System.out.println(readChar(ch, "src/main/resources", Const.CHI_SIM));
}
}
注释:中文结果不够准确,需要自己训练字库
具体训练字库,以及完整代码请移步https://github.com/followwwind/javautils