使用python pytesseract库识别验证码中的文字,图片中的文本内容
运行环境 python3.6, PIL , pytesseract,
安装tesseract-ocr
原理
tesseract-ocr目前是谷歌维护的开源OCR识别引擎,python的pytessseract库本质是对tesseract-ocr的封装和调用,库本身不能进行识别,识别的工作都是tsseract光学字符识别引擎在干
环境搭建
运行环境:python3.6+PIL+pytesseract
依赖:tesseract-ocr,语言包
安装:
1.python库的安装用pip完成
2.下载tesseract-ocr-setup-3.02.02.exe并安装
3.下载相应的语言包,如中文包依赖chi_sim
环境搭建:
1.确认tesseract-oc的安装路径,默认:C:\Program Files (x86)\Tesseract-OCR
2.确认tesseract.exe和tessdata文件夹
3.在开发程序环境中,导入tesseract.exe执行文件
4.将tessdata文件夹复制在程序所在的目录中,保持平级
5.下载chi_sim.traineddata,复制在tessdata文件夹中,用来识别中文字符
程序环境搭建结束
附录:
1.tessdata 目录存放的是语言字库文件
测试识别验证码
from PIL import Image
import pytesseract
image=Image.open(imagePath) #打开识别的图片
cod=pytesseract.image_to_string(image,lang=’chi_sim’) #用pytesseract识别图片文字,lang指定语言包
print(cod) #打印识别的字符串
pytesseract.image_to_string参数设置
pytesseract.image_to_string(image,lang=’chi_sim’,config=’-psm 7′)
.image_to_string(
image #设置图片的路径或名
lang=” #指定解析文件的语言包
config=’-psm num’ #-psm为tesseract.orc解析图片的参数
)
tesseract常见问题
1.安装问题,提示make sure TESSDATA_PREFIX environment varialbe….
tesseract-oc安装完成后,默认会自动进行环境变量配置,在dos界面中输入tesseract,显示tesseract的help用法,安装成功
提示make sure TESSDATA_PREFIX environment varialbe,需要在环境变量中新建TESSDATA_PREFIX变量,地址为tesseract的安装路径
2.tesseract用法
直接在dos命令行使用: tesseract 图片名 输出文件名 [-l 字库文件] [-psm pagesegmode] [configfile]
结果在命令行所在路径或指定路径生成指定文件名的文本文件
==> tesseract 1.jpg 1.txt -l chi_sim+equ+eng
-l是指定使用的包:chi_sim是中文识别包,equ是数学公式包,eng是英文包
3.tesseract参数
tesseract imagename outputbase [-l 字库文件] [-psm pagesegmode] [configfile]
-l 为指定解析文本的语言包,如中文用 chi_sim,语言包路径在tessdata文件夹中,且后缀为.traineddata
-psm 7 psm为指定tesseract code.jpg图片是一行文本这个参数可以减少识别错误率. 默认为 3
configfile 参数值为tessdata\configs 和 tessdata\tessconfigs 目录下的文件名.
tesseract.orc help
Usage:tesseract imagename outputbase [-l lang] [-psm pagesegmode] [configfile…]
pagesegmode values are:
0 = Orientation and script detection (OSD) only.
1 = Automatic page segmentation with OSD.
2 = Automatic page segmentation, but no OSD, or OCR
3 = Fully automatic page segmentation, but no OSD. (Default)
4 = Assume a single column of text of variable sizes.
5 = Assume a single uniform block of vertically aligned text.
6 = Assume a single uniform block of text.
7 = Treat the image as a single text line.
8 = Treat the image as a single word.
9 = Treat the image as a single word in a circle.
10 = Treat the image as a single character.
-l lang and/or -psm pagesegmode must occur before anyconfigfile.
一些经验
1.可以将突破转换成灰度,对于图片较大的,可以使用缩略图,像素过高和过低,都影响准确 imgry = img.convert(‘L’) imgry.thumbnail(size=(1024,1024))