Python3 pytesseract识别简单的验证码

安装tesseract并添加到系统PATH
Python3 pytesseract识别简单的验证码,JPEG格式,验证码样式如下:
在这里插入图片描述 在这里插入图片描述 在这里插入图片描述

此验证码比较简单,因此简单二值化处理,然后使用pytesseract识别即可达到不错的识别率。

# -*- coding: utf-8 -*-
from PIL import Image
import pytesseract

class Captcha:
    def __init__(self):
        pass
    # 识别图片验证码,并返回验证码的字符串
    def get_captcha_str(self, img_path):
        """
        识别验证码
            :param self:
            :param img_path: 图片地址
        """
        # 使用Image打开该图片
        image = Image.open(img_path)
        # 二值化处理,这个阈值为R=18,G=16,B=18 低于阀值为黑色 否则为白色
        pix = image.load()  # 转换为像素
        for y in range(image.size[1]):
            for x in range(image.size[0]):
                if pix[x, y][0] < 18 or pix[x, y][1] < 16 \
                or pix[x, y][2] < 18:
                    pix[x, y] = (0, 0, 0)
                else:
                    pix[x, y] = (255, 255, 255)
        # 显示该图片,实际使用中请注释
        image.show()
        # 开始识别
        captcha_str = pytesseract.image_to_string(image)
        # 去除空格
        captcha_str = captcha_str.replace(' ', '')
        # 去除非英文字符
        captcha_str = filter(str.isalpha, captcha_str)
        captcha_str = str(''.join(list(captcha_str)))
        # 返回前四个字符
        return captcha_str[0:4]

captcha = Captcha()
captcha_str = captcha.get_captcha_str('./captcha.jpeg')
print(captcha_str)

猜你喜欢

转载自blog.csdn.net/u010974701/article/details/88594378