tesseract库

1.简介

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

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

安装:
windows系统:
    在以下链接下载可执行文件,然后一顿点击下一步安装即可。(放在不需要权限的纯文本英文路径下)
    https://github.com/tesseract-ocr/
linux系统:
    可以在以下链接下载源码自行编译:
    https://github.com/tesseract-ocr/tesseract/wiki/Compiling
mac系统:
    用Homebrew即可方便安装:
    brew install tesseract

设置环境变量:
windows下要把tesseract.exe所在的路径添加到PATH环境变量中
linux和mac在安装的时候默认已经设置好了
'''
View Code

2.在终端下识别图片

#  -*-coding:utf8 -*-
import pytesseract
from PIL import Image

#加了路径,后面还要指定文件名
pytesseract.pytesseract.tesseract_cmd=r'D:\tesseract\Tesseract-OCR\tesseract.exe'
#打开a图片,这个识别的是英文
# image=Image.open('2.png')
# text=pytesseract.image_to_string(image)
# print(text)

#指定识别中文
img=Image.open(r'b.png')
text=pytesseract.image_to_string(img,lang='chi_sim')
print(text)
View Code

3.在代码下识别图片

#  -*-coding:utf8 -*-

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

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


def main():
    url = 'https://passport.lagou.com/vcode/create?from=register&refresh=1513082291955'
    while True:
        request.urlretrieve(url,'captcha.png')
        img=Image.open('captcha.png')
        text=pytesseract.image_to_string(img)
        print(text)
        time.sleep(10)


if __name__ == '__main__':
    main()
View Code

猜你喜欢

转载自www.cnblogs.com/xufengnian/p/10788210.html