python实现ocr识别:pytesseract

python常用pytesseract进行图片上的文字识别,即ocr识别,完整的代码比较简单,只要下面一行即可,但是实际使用时环境配置上容易出错。

from pil import image
import pytesseract
 
text = pytesseract.image_to_string(image.open('/users/alice/documents/develop/pythoncode/textinphoto.png'))
print(text)

因此使用前,需要先安装pillow和pytesseract依赖包。

然而运行时仍然报错,raise tesseractnotfounderror()
pytesseract.pytesseract.tesseractnotfounderror: tesseract is not installed or it’s not in your path

原因是因为未安装tesseract,然后使用pip3 install tesseract之后仍然提示错误,如图:

alicedembp:~ alice$ pip3 install tesseract
requirement already satisfied: tesseract in /library/frameworks/python.framework/versions/3.7/lib/python3.7/site-packages (0.1.3)
alicedembp:~ alice$ tesseract
-bash: tesseract: command not found

无法使用,往上找了很多教程,说是要使用brew安装,于是得以解决,步骤为:

  • 先安装brew
alicedembp:~ alice$ ruby -e "$(curl -fssl https://raw.githubusercontent.com/homebrew/install/master/install)"
  • 再使用brew安装leptonica
alicedembp:~ alice$ brew install leptonica
  • 使用brew安装tesseract
alicedembp:~ alice$ brew install tesseract
  • 安装成功,通过命令行tesseract -v的方式查看是否成功,出现版本号则为安装成功
alicedembp:~ alice$ tesseract
usage:
  tesseract --help | --help-extra | --version
  tesseract --list-langs
  tesseract imagename outputbase [options...] [configfile...]
 
ocr options:
  -l lang[+lang]        specify language(s) used for ocr.
note: these options must occur before any configfile.
 
single options:
  --help                show this help message.
  --help-extra          show extra help for advanced users.
  --version             show version information.
  --list-langs          list available languages for tesseract engine.
 
alicedembp:~ alice$ tesseract -v
tesseract 4.0.0
 leptonica-1.78.0
  libgif 5.1.4 : libjpeg 9c : libpng 1.6.36 : libtiff 4.0.10 : zlib 1.2.11 : libwebp 1.0.2 : libopenjp2 2.3.1
 found avx2
 found avx
 found sse

接下来就可以直接使用了,使用如下代码:

alicedembp:~ alice$ tesseract /users/alice/documents/develop/pythoncode/textinphoto.png /users/alice/documents/develop/pythoncode/output.txt

打开textinphoto.png的图片,将文字输出到output.txt,图片如下

运行成功,产生output.txt文档,里面的文本为图片中识别出的文字。

到此这篇关于python实现ocr识别之pytesseract案例详解的文章就介绍到这了,更多相关python ocr识别之pytesseract内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!