爬虫(10-3)验证码图片识别

Tesseract

Tesseract是一个OCR库,目前由谷歌赞助。Tesseract是目前公认最优秀、最准确的开源OCR库。Tesseract具有很高的识别度,也具有很高的灵活性,他可以通过训练识别任何字体。

安装:
Windows系统:
在以下链接下载可执行文件,然后一顿点击下一步安装即可(放在不需要权限的纯英文路径下):
https://github.com/tesseract-ocr/

Linux系统:
可以在以下链接下载源码自行编译。
https://github.com/tesseract-ocr/tesseract/wiki/Compiling
或者在ubuntu下通过以下命令进行安装:
sudo apt install tesseract-ocr
设置环境变量: 安装完成后,如果想要在命令行中使用Tesseract,那么应该设置环境变量。Mac和Linux在安装的时候就默认已经设置好了。在Windows下把tesseract.exe所在的路径添加到PATH环境变量中。 还有一个环境变量需要设置的是,要把训练的数据文件路径也放到环境变量中。 在环境变量中,添加一个TESSDATA_PREFIX
=C:path_to_tesseractdata eseractdata。

命令行的使用:

如果想要在cmd下能够使用tesseract命令,那么需要把tesseract.exe所在的目录放到PATH环境变量中。然后使用命令:tesseract 图片路径 文件路径。
示例:

tesseract a.png a
那么就会识别出a.png中的图片,并且把文字写入到a.txt中。如果不想写入文件直接想显示在终端,那么不要加文件名就可以了。

Python中使用:

在Python代码中操作tesseract。需要安装一个库,叫做pytesseract。通过pip的方式即可安装:

pip install pytesseract
并且,需要读取图片,需要借助一个第三方库叫做PIL。通过pip list看下是否安装。如果没有安装,通过pip的方式安装:

pip install PIL
使用pytesseract将图片上的文字转换为文本文字的示例代码如下:
# 导入pytesseract库
import pytesseract
# 导入Image库
from PIL import Image
# 指定tesseract.exe所在的路径
pytesseract.pytesseract.tesseract_cmd = r'D:ProgramAppTesseractOCR	esseract.exe'
# 打开图片
image = Image.open("a.png")
# 调用image_to_string将图片转换为文字
text = pytesseract.image_to_string(image)
print(text)

用pytesseract处理拉勾网图形验证码:

import pytesseract
from urllib import request
from PIL import Image
import time


pytesseract.pytesseract.tesseract_cmd = r"D:ProgramAppTesseractOCR	esseract.exe"


while True:
    captchaUrl = "https://passport.lagou.com/vcode/create?from=register&refresh=1513081451891"
    request.urlretrieve(captchaUrl,'captcha.png')
    image = Image.open('captcha.png')
    text = pytesseract.image_to_string(image,lang='eng')
    print(text)
    time.sleep(2)
原文地址:https://www.cnblogs.com/topass123/p/13420191.html