python 提取图片中的文字(英文or中文)

785 阅读1分钟

前言

[参考链接](https://blog.csdn.net/qiushi_1990/article/details/78041375)
[python3.7下载链接](https://www.python.org/downloads/)
环境变量设置  C:\Python37;C:\Python37\Scripts;安装自带pip

依赖包:PIL和pytesseract
命令行安装依赖
pip install pytesseract
//这里因为PIL只支持python2.7,所以在此安装的是pillow。
pip install pillow
依赖于谷歌开源文字识别引擎 tesseract-ocr

安装tesseract-ocr3.02

[下载地址](http://jaist.dl.sourceforge.net/project/tesseract-ocr-alt/tesseract-ocr-setup-3.02.02.exe)

下载后直接安装,建议默认安装过程中的选项
原装的tesseract-ocr只支持英文识别,若要识别中文,那么就下载中文包
[中文包地址](https://codeload.github.com/tesseract-ocr/tessdata/zip/master)
chi_sim.traineddata为简体中文库,将该文件放至C:\Program Files (x86)\Tesseract-OCR\tessdata目录下

安装tesseract-ocr4.00

[下载地址](https://digi.bib.uni-mannheim.de/tesseract/tesseract-ocr-w64-setup-v4.0.0-beta.1.20180608.exe)
[中文包地址](https://raw.githubusercontent.com/tesseract-ocr/tessdata/4.00/chi_sim.traineddata)
新建系统变量:TESSDATA_PREFIX:C:\Program Files (x86)\Tesseract-OCR\tessdata

Linux Centos7 安装tesseract-ocr 3.04

[参考链接](https://www.cnblogs.com/arachis/p/OCR.html)
- 安装centos系统依赖
yum install -y automake autoconf libtool gcc gcc-c++ 
yum install -y libpng-devel libjpeg-devel libtiff-devel
- 安装leptonica

wget http://www.leptonica.org/source/leptonica-1.72.tar.gz
tar xvzf leptonica-1.72.tar.gz
cd leptonica-1.72/ 
./configure 
make && make install
- 安装tesseract-ocr

wget https://github.com/tesseract-ocr/tesseract/archive/3.04.zip
unzip 3.04.zip
cd tesseract-3.04/ 
./configure
make && make install 
sudo ldconfig
- 在https://github.com/tesseract-ocr/tessdata 下载对应语言的模型文件将模型文件移动到/usr/local/share/tessdata

直接运行

运行:tesseract 123.jpg result   tesseract test.jpg result -l chi_sim
会把123.jpg自动识别并转换为txt文件到result.txt

python执行代码

from PIL import Image
    import pytesseract
    #text=pytesseract.image_to_string(Image.open('denggao.jpeg'),lang='chi_sim')#中文识别
    text=pytesseract.image_to_string(Image.open('denggao.jpeg'),lang='eng')#英文
    print(text)

常见错误

1.命令行运行E:\pythonTest>tesseract test1.jpg result -l chi_sim
  报错如下,出现程序卡死现象
   actual_tessdata_num_entries_ <= TESSDATA_NUM_ENTRIES:Error:Assert failed:in file
    ..\..\ccutil\tessdatamanager.cpp, line 50
   
这是因为选择的testeract的版本与中文包chi_sim.traindata 不一致,要选择相对应的版本。
2.命令行运行:E:\pythonTest>tesseract test1.jpg result -l chi_sim
出现以下错误,
read_params_file: parameter not found: allow_blob_division
[解决办法参考](http://www.cnblogs.com/syqlp/p/5460971.html)
在chi_sim.traineddata文件目录下,使用命令行执行:

combine_tessdata -e chi_sim.traineddata chi_sim.config

执行完后,在目录下出现chi_sim.config的文件,打开该文件;
在allow_blob_division        F这一行的前面加#,注释掉

即:# allow_blob_division        F    

然后,在执行命令行:
combine_tessdata -o chi_sim.traineddata chi_sim.config

到此在使用 chi_sim.traineddata文件就不会报read_params_file: parameter not found: allow_blob_division