图片验证码识别

图形验证码识别技术

阻碍我们爬虫的。有时候正是在登录或者请求一些数据时候的图形验证码。因此这里我们讲解一种能将图片翻译成文字的技术。将图片翻译成文字一般被称为光学文字识别(Optical Character Recognition),简写为OCR。实现OCR的库不是很多,特别是开源的。因为这块存在一定的技术壁垒(需要大量的数据、算法、机器学习、深度学习知识等),并且如果做好了具有很高的商业价值。因此开源的比较少。这里介绍一个比较优秀的图像识别开源库:Tesseract。

Tesseract

定义:Tesseract是一个将图像翻译成文字的OCR(光学文字识别,Optical Character Recognition),目前由谷歌赞助。Tesseract是目前公认最优秀、最准确的开源OCR库。Tesseract具有很高的识别度,也具有很高的灵活性,他可以通过训练识别任何字体

Windows系统安装

在以下链接下载可执行文件,https://github.com/tesseract-ocr/

在Python中调用Tesseract:

pip install pytesseract

在ubuntu下通过以下命令进行安装

sudo apt install tesseract-ocr

设置环境变量

安装完成后,如果想要在命令行中使用Tesseract,那么应该设置环境变量。Mac和Linux在安装的时候就默认已经设置好了。

在Windows下把tesseract.exe所在的路径添加到PATH环境变量中。

还有一个环境变量需要设置的是,要把训练的数据文件路径也放到环境变量中。

在环境变量中,添加一个

TESSDATA_PREFIX=D:\Tesseract-OCR\tessdata

进入cmd输入下面的命令查看版本,正常运行则安装成功

tesseract --version

在命令行中使用tesseract识别图像

tesseract 图片路径 文件路径

tesseractdemo.pnga

识别中文图像,需要下载语言安装包

URL地址:https://github.com/tesseract-ocr/tessdat

在代码中使用tesseract识别图像

import pytesseract

from PIL import Image

pytesseract.pytesseract.tesseract_cmd = r'D:\Tesseract-OCR\tesseract.exe'

tessdata_dir_config = r'--tessdata-dir "D:\Tesseract-OCR\tessdata"'

image = Image.open('demo.png')

print(pytesseract.image_to_string(image, lang='eng',  config=tessdata_dir_config))

pytesseract处理图形验证码

验证码URL:https://passport.lagou.com/vcode/create?from=register&refresh=1513081451891

打码云代码

import json

import requests

import base64

from io import BytesIO

from PIL import Image

from sys import version_info

def base64_api(uname, pwd,  img):

    img = img.convert('RGB')

    buffered = BytesIO()

    img.save(buffered, format="JPEG")

    if version_info.major >= 3:

        b64 = str(base64.b64encode(buffered.getvalue()), encoding='utf-8')

    else:

        b64 = str(base64.b64encode(buffered.getvalue()))

    data = {"username": uname, "password": pwd, "image": b64}

    result = json.loads(requests.post("http://api.ttshitu.com/base64", json=data).text)

    if result['success']:

        return result["data"]["result"]

    else:

        return result["message"]

    return ""

if __name__ == "__main__":

    img_path = "captcha.png"

    img = Image.open(img_path)

    result = base64_api(uname='', pwd='', img=img)

    print(result)

你可能感兴趣的:(图片验证码识别)