一前提:python环境,系统:mac系统
1安装依赖包
安装pillow和tesseract
pip install pillow
brew install tesseract
pip install pytesseract
tesseract -v 查看版本
2下载中文字体包
下载地址:https://raw.githubusercontent.com/tesseract-ocr/tessdata/4.00/chi_sim.traineddata
字体包注意需要和tesseract版本保持一致。不一致可能会报错。
将下载的中文字体包放在安装目录下:
cp chi_sim.traineddata /usr/local/Cellar/tesseract/4.1.1/share/tessdata/
cp命令报错的话,命令前面加sudo
3命令行实现文字识别
中文识别(部分英文识别错误):tesseract 2.png 8 -l chi_sim
中英文识别:tesseract 2.png 8 -l chi_sim+eng
识别结果会存放在8.txt文件中
4python代码实现文字识别
from PIL import Image
import pytesseract
def erzhi(image):
# 模式L”为灰色图像,它的每个像素用8个bit表示,0表示黑,255表示白,其他数字表示不同的灰度。
Img = image.convert('L')
# 自定义灰度界限,大于这个值为黑色,小于这个值为白色
thresholdMax = 256
thresholdMin = 180
table = []
for i in range(256):
if (i < thresholdMax) & (i > thresholdMin):
table.append(0)
else:
table.append(1)
# 图片二值化
photo = Img.point(table, '1')
# photo.save("/vd/5-11.png")
return photo
if __name__ == '__main__':
path = '/vd/5.png'
image = Image.open(path)
photo = erzhi(image)
text = pytesseract.image_to_string(photo, lang='chi_sim+eng')
print(text)
5识别效果
示例图片:5.png
二值化后:(二值化提高识别率)5-11.png
识别效果:
6.常见问题
TESSDATA_PREFIX 环境变量问题
pytesseract.pytesseract.TesseractError: (1, 'Error opening data file /user/local/share/tessdata/chi_sim.traineddata Please make sure the TESSDATA_PREFIX environment variable is set to the parent directory of your "tessdata" directory. Failed loading language \'eng\' Tesseract couldn\'t load any languages! Could not initialize tesseract.')
解决办法:
1,win版本的网上查配置环境变量,mac 版本的试一下这个:
export TESSDATA_PREFIX=/usr/local/Cellar/tesseract/4.1.1/share/tessdata
2,检测chi_sim.traineddate下载版本与tesseract版本是否一致
3,注意依赖包的装载顺序,如果先装了pytesseract,再装tesseract时候,会提示已安装,试试重装一下
brew reinstall tesseract
二前提:python环境,系统:win系统
1安装pytesseract
清华镜像:https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/pytesseract/
2,安装ocr
tesseract-ocr-w64-setup-v4.0.0-beta.4.20180912
3.添加环境变量
path: C:\Program Files (x86)\Tesseract-OCR