通过pytesseract识别验证码

准备工作:

1.使用国内源安装库pytesseract
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pytesseract
2.安装tesseract
自己下载安装包吧

from PIL import Image
import pytesseract
import os

def get_all_path():
    start = r"E:\hhh\soft\中国知网验证码"
    lis = os.listdir(start)
    path = [start+os.sep+name for name in lis]
    return path
    
def get_ma(path):
    image = Image.open(path)
    text = pytesseract.image_to_string(image)
    return text
    
def open_code(): 
    num = 0
    all_path = get_all_path()
    for path in all_path:
        right = path.split("\\")[-1].replace(".jpg", "")
        ma = get_ma(path)
        if(right == ma):
            print("正确为:{},机器识别为:{},结果正确".format(right, ma))
            num += 1
        else:
            print("正确为:{},机器识别为:{},结果错误".format(right, ma)) 
    print("最终成功率为%.4f" % (num/len(all_path)))
    
open_code()
设置阈值,转灰度图像,二值化
from PIL import Image
import pytesseract
import os

def get_all_path():
    start = r"E:\hhh\soft\中国知网验证码"
    lis = os.listdir(start)
    path = [start+os.sep+name for name in lis]
    return path

def set_threshold():
    threshold = 127  #阈值
    table=[]
    for i in range(256):
        if i<threshold:
            table.append(0)
        else:
            table.append(1)
    return table
        
def get_ma2(path):
    image = Image.open(path)
    image = image.convert("L")    # 转换为灰度图像
    table = set_threshold()
    newImage = image.point(table,'1')   #二值化
    text = pytesseract.image_to_string(newImage)
    return text

def open_code2(): 
    num = 0
    all_path = get_all_path()
    for path in all_path:
        right = path.split("\\")[-1].replace(".jpg", "")
        ma = get_ma2(path)
        if(right == ma):
            print("正确为:{},机器识别为:{},结果正确".format(right, ma))
            num += 1
        else:
            print("正确为:{},机器识别为:{},结果错误".format(right, ma)) 
    print("最终成功率为%.4f" % (num/len(all_path)))
    
open_code2()
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hao难懂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值