验证码的识别 -01 -图形验证码的识别

验证码的识别 -01 -图形验证码的识别

1. 准备工作

  • 1. 下载安装 tesseract 下载地址
  • 下载完成后双击,安装程序, 可以勾选Additional language data(download)选项来安装 OCR 识别支持的语言包,这样 OCR 便可以识别多国语言
  • 将tesseract 配置环境变量
  • 将tesseract的语言包添加到环境变量中,在环境变量中新建一个系统变量,变量名称为TESSDATA_PREFIX,tessdata是放置语言包的文件夹,一般在你安装tesseract的目录下,即tesseract的安装目录就是tessdata的父目录,把TESSDATA_PREFIX的值设置为它即可
  • pip安装tesserocr文件, 注意pip install tesserocr 在window系统上安装总是失败, 需要去github上下载 与我们安装的tesseract版本对应的 tesserocr 的 .whl文件,进行安装,

2. 获取验证码图片

import os
import requests
from uuid import uuid4
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://my.cnki.net/elibregister/commonRegister.aspx')
browser.implicitly_wait(2)
os.mkdir('picture')
for i in range(5):
    image =  browser.find_element_by_xpath('//*[@id="checkcode"]')
    image_url = image.get_attribute('src')
    image_content = requests.get(image_url).content
    image_path = os.path.join('picture', f'{uuid4()}.jpg')
    with open(image_path, 'wb') as f:
        f.write(image_content)
    image.click()
    browser.implicitly_wait(2)

3. 识别测试

import tesserocr
from PIL import Image

image = Image.open('picture/1.jpg')
result = tesserocr.image_to_text(image)  #将image对象转换为文字
print(result)

print(tesserocr.file_to_text('picture/1.jpg'))  #将文件对象转换为文字

4. 验证码处理

  转化为灰度图像和二值化处理

image = image.convert('L') #将图片转化为灰度图像
image.show()
image = image.convert('1') #将图片进行二值化处理
image.show()
我们还可以指定二值化的阈值, 上面的方法采用的是默认阈值127, 不过我们不能直接转化原图, 要将原图先转化为灰度图像, 然后再指定二值化阈值,
import tesserocr
from PIL import Image
image = Image.open('picture/2.jpg')
image = image.convert('L')
threshold = 105  #数值越小, 图片中的像素点越少, 空白越多
table = []
for i in range(256):
    if i  < threshold:
        table.append(0)
    else:
        table.append(1)
image = image.point(table,'1')
image.show()
result = tesserocr.image_to_text(image)

猜你喜欢

转载自www.cnblogs.com/zhangjian0092/p/11248712.html