教你如何在Mac下做OCR文字识别。支持m1 mac

1. 前景提要
最近想要用ocr文字识别做一点好玩的事情,虽然已经知道有百度OCR成熟的产品API,但是还是想自己通过tess4j做一个,毕竟生命在于折腾。
而百度OCR, 也并不是完全的免费的状态,如下图:
一个月有一千次的调用限制。

1.1 Tess4J
官网地址:Tess4J
Tess4J是一个对于Tesseract OCR API的Java JNA wrapper。也就是能让我们简单的调用Tesseract进行文字识别。而Tesseract 是一个光学字符识别引擎。支持多种操作系统,基于Apache许可证的自由软件,由Google赞助开发。 Tesseract被认为是最精准的开源光学字符识别引擎之一。
2. 安装Tesseract
2.1 Mac环境下
brew install tesseract
可能因为国内长城问题导致下载失败,建议更换镜像源,更换镜像源方法如下
2.2 更换mac brew镜像源
# 替换brew.git:
$ cd "$(brew --repo)"
# 清华大学:
$ git remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/brew.git
# 替换homebrew-core.git:
$ cd "$(brew --repo)/Library/Taps/homebrew/homebrew-core"
# 清华大学:
$ git remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-core.git
# 替换homebrew-bottles:
# 清华大学:
$ echo 'export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles' >> ~/.bash_profile
$ source ~/.bash_profile
# 应用生效:
$ brew update
等待安装完成之后,输入 tesseract -v 可以看到显示对应的版本信息

2.4 获取libtesseract.dylib信息
然后输入 brew list tesseract 记录对应 libtesseract.dylib的信息,之后demo的时候会用到
asher@AsherdeMBP homebrew-core % brew list tesseract
/opt/homebrew/Cellar/tesseract/5.0.1/bin/tesseract
/opt/homebrew/Cellar/tesseract/5.0.1/include/tesseract/ (12 files)
/opt/homebrew/Cellar/tesseract/5.0.1/lib/libtesseract.5.dylib
/opt/homebrew/Cellar/tesseract/5.0.1/lib/pkgconfig/tesseract.pc
/opt/homebrew/Cellar/tesseract/5.0.1/lib/ (2 other files)
/opt/homebrew/Cellar/tesseract/5.0.1/share/tessdata/ (35 files)
asher@AsherdeMBP homebrew-core %
2.5 下载tessdata文件
点击github地址 ,然后本地git clone一下进行下载,文件内容比较大,慢慢下载。
3. 新建demo工程进行测试
这里我准备了一张中文的图片,大家可以自取

3.1 新建一个maven工程

3.2 引入对应的Tess4J依赖
<!-- https://mvnrepository.com/artifact/net.sourceforge.tess4j/tess4j -->
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>5.1.1</version>
</dependency>
3.3 复制 libtesseract.dylib文件
回到步骤2.4, 打开对应的目录,比如我的就是
/opt/homebrew/Cellar/tesseract/5.0.1/lib
复制 libtesseract.5.dylib 文件到项目的 resources目录下,然后重命名为 libtesseract.dylib。
为什么不是直接复制 libtesseract.dylib ,因为那个是个软链接,就像windows中的快捷方式一样

3.3 编写测试代码
public static void main(String[] args) throws TesseractException {
ITesseract instance = new Tesseract(); // JNA Interface Mapping
instance.setDatapath("/Users/asher/gitWorkspace/tessdata"); // path to tessdata directory
instance.setLanguage("chi_sim");
String result = instance.doOCR(new File("/Users/asher/Desktop/temp/chi_temp.jpg"));
System.out.println(result);
}
当中的一些代码解释
- instance.setDatapath(String); 设置步骤2.5中下载tessdata文件的路径,当中包含了简体中文的训练数据
- instance.setLanguage(String);这个就是设置你要识别的文字是什么语言了
可以看到文字是能够被正确识别出来的
