本文转自:https://blog.csdn.net/justlpf/article/details/127900284 感谢分享
Tesseract
Tesseract-OCR支持中文识别,并且开源和提供全套的训练工具,是快速低成本开发的首选。而Tess4J则是Tesseract在Java
PC上的应用。在英文和数字识别中性能还是不错的,但是在中文识别中,无论速度还是识别率还是较弱,建议有条件的话,针对场景进行训练,会获得较好结果,本文仅对目前Tess4J的用法进行介绍
Tess4J官网:https://tess4j.sourceforge.net/
Github地址:https://github.com/tesseract-ocr/tessdata
使用
1、引入jar包
本人日志使用的log4j2日志包冲突所以排除掉logback
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>5.7.0</version>
<exclusions>
<exclusion>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.4.0</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>5.4.0</version>
</dependency>
2、获取语言库
Github上下载语言库并放入到指定位置
3、编写代码
首先解析http请求返回的验证码的加密信息并生成图片到本地
//fileName生成图片位置,secretKey验证码秘钥信息
public static Boolean createFile(String fileName,String secretKey){
FileOutputStream fout=null;
try{
fout = new FileOutputStream(fileName);
fout.write(Base64.getDecoder().decode(secretKey));
return Boolean.TRUE;
}catch (Exception ex){
return Boolean.FALSE;
}finally {
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
解析验证码
public static String executeTess4J(String imgUrl){
String ocrResult = "";
try{
ITesseract instance = new Tesseract();
instance.setLanguage("eng");//设置语言库
File imgDir = new File(imgUrl);
if(imgDir.exists()){
List<String> configList = new ArrayList<>();
configList.add("digits");//设置只提取数字
instance.setConfigs(configList);
instance.setOcrEngineMode(1); // 设置OCR引擎模式(OEM)
instance.setPageSegMode(6); // 设置图片分割模式(PSM)
instance.setDatapath("/data/xihongda-xxljob-gateway/");//设置训练库的位置
ocrResult = instance.doOCR(imgDir);//解析
}
}catch (TesseractException e){
e.printStackTrace();
}
return ocrResult;
}
Tesseract讲解
# Note
Tesseract引入训练模型的方法
根据自己的需要下载需要的模型文件,将traineddata文件放在
%TesseractOCR_HOME%\tessdata 目录(Tesseract安装目录)下就可以了。
tessdata下载地址:
https://github.com/tesseract-ocr/tessdata_best
tessdata_best可用来再训练字库
训练方法参考文档:
https://tesseract-ocr.github.io/tessdoc/tess4/TrainingTesseract-4.00.html
# 参数释义
## 自定义配置
config = r'-l chi_sim+eng --psm 6'
# 其它OCR选项:
# --tessdata-dir PATH:Specify the location of tessdata path.
# --user-words PATH:Specify the location of user words file.
# --user-patterns PATH:Specify the location of user patterns file.
# --dpi VALUE:Specify DPI for input image.
# -l LANG[+LANG]:Specify language(s) used for OCR.
# -c VAR=VALUE:Set value for config variables. Multiple -c arguments are allowed.
# --psm NUM:Specify page segmentation mode.
# --oem NUM:Specify OCR Engine mode.
text = pytesseract.image_to_string(Image.open(r'D:\workspace\tesseract-ocr\test.jpg'), config=config)
## ImageHelper
getScaledInstance 放大图片
getSubImage 截取图片
convertImageToBinary 转二进制
convertImageToGrayscale 将图像转换为灰度
invertImageColor 反转图像颜色
rotateImage 旋转影像
## 图片分割模式(PSM)
tesseract有13种图片分割模式(page segmentation mode,psm):
0 – Orientation and script detection (OSD) only. 方向及语言检测(Orientation and script detection,OSD)
1 – Automatic page segmentation with OSD. 自动图片分割
2 – Automatic page segmentation, but no OSD, or OCR. 自动图片分割,没有OSD和OCR
3 – Fully automatic page segmentation, but no OSD. (Default) 完全的自动图片分割,没有OSD
4 – Assume a single column of text of variable sizes. 假设有一列不同大小的文本
5 – Assume a single uniform block of vertically aligned text. 假设有一个垂直对齐的文本块
6 – Assume a single uniform block of text. 假设有一个对齐的文本块
7 – Treat the image as a single text line. 图片为单行文本
8 – Treat the image as a single word. 图片为单词
9 – Treat the image as a single word in a circle. 图片为圆形的单词
10 – Treat the image as a single character. 图片为单个字符
11 – Sparse text. Find as much text as possible in no particular order. 稀疏文本。查找尽可能多的文本,没有特定的顺序。
12 – Sparse text with OSD. OSD稀疏文本
13 – Raw line. Treat the image as a single text line, bypassing hacks that are Tesseract-specific. 原始行。将图像视为单个文本行。
## OCR引擎模式(OEM)
有4种OCR引擎模式:
0 – Legacy engine only.
1 – Neural nets LSTM engine only.
2 – Legacy + LSTM engines.
3 – Default, based on what is available.
## 方向及语言检测OSD
Tesseract支持方向及语言检测(Orientation and script detection,OSD) ,比如检测下面的图片:
![img.png](img/img.png)
### 检测方法:
osd = pytesseract.image_to_osd('osd-example.png',config='--psm 0 -c min_characters_to_try=5')
print(osd)
### 执行结果:
Page number: 0
Orientation in degrees: 90
Rotate: 270
Orientation confidence: 0.74
Script: Han
Script confidence: 0.83