tesserocr 是 python 的一个 OCR 库,它是对 tesseract 作的一层 Python API 封装,因此他的核心是tesseract。html
tesseract 的安装见 http://www.javashuo.com/article/p-yfjbydij-mb.htmlpython
windows 下安装 tesserocr 是一个坑爹的事情,直接用 pip 安装是不能够的,会报错,只能用 .whl 的方式安装。听说 pip 的方式只能用于 Linux 系统,没验证过。git
whl 下载地址:https://github.com/simonflueckiger/tesserocr-windows_build/releasesgithub
网站中列出了 tesserocr 和 tesseract 版本的对应关系,选择对应的版本,不然会出现非预期字符。windows
安装 whl 测试
λ pip install tesserocr-2.4.0-cp36-cp36m-win_amd64.whl
脚本:网站
import tesserocr from PIL import Image img = Image.open('1.png') result = tesserocr.image_to_text(img) print(result)
遇到的坑:‘ui
若是依照官方文档,只安装了 tesserocr 的 .whl
文件,并尝试运行以下测试代码:spa
import tesserocr from PIL import Image img = Image.open('1.png') result = tesserocr.image_to_text(img) print(result)
便会获得以下错误提示:3d
Traceback (most recent call last): File "c:/Users/iwhal/Documents/GitHub/python_notes/notes_of_crawler/code_of_learn_is_ignored/test_of_tesserocr .py", line 4, in <module> print(tesserocr.image_to_text(image)) File "tesserocr.pyx", line 2401, in tesserocr._tesserocr.image_to_textRuntimeError: Failed to init API, possibly an invalid tessdata path:
Traceback 告诉咱们:tessdata 路径无效,没法初始化 API。
错误的缘由是:stand-alone packages 虽然包含了 Windows 下所需的全部库,但并是不包含语言数据文件(language data files)。而且数据文件须要被统一放置在 tessdata\
文件夹中,并置于 C:\Python36
内。
得到数据文件有以下两种方式:
方法一:按照下一节的方法安装 "tesseract-ocr-w64-setup-v4.0.0-beta.1.20180608.exe"(由于要与 tesserocr-2.2.2 匹配)。而后,将 C:\Program Files (x86)\Tesseract-OCR\
下的 tessdata\
文件夹复制到 C:\Python36\
下便可 。
方法二:无需安装 tesseract ,只需克隆 tesseract 仓库的主分支,而后将其中的 tessdata\
文件夹复制到 C:\Python36\
中。接下来,经过 tessdata_fast 仓库下载 eng.traineddata
语言文件,并放置于 C:\Python36\tessdata\
内便可。
可见,解决此问题的关键在于得到 tesseract 的 tessdata\
文件夹,并不必定要安装 tesseract ,但 tesseract 的版本必定要正确。
接下来尝试运行以前的代码:
import tesserocr from PIL import Image img = Image.open('1.png') result = tesserocr.image_to_text(img) print(result)