python网络爬虫之识别数字验证码

代码记录一下,嚯嚯嚯,0182被我提取出来啦

我们需要对这个图片验证码进行解析。

通过上图,我们可以发现,如果只是简单地进行灰度化处理,验证码地识别度并不和高,不能准确地识别出来。识别出来的是0LS?,与我们的0182还有很大的差距。因此,我们可以通过图片二值化、线性降噪或者利用 Tesseract 进行验证码识别,来提高验证码的识别准确度。

通过进一步的代码改进,验证码的识别有了很大的提高,识别出了0102,虽然正确的是0182,只有一个0和8的差距,但是我们仍然需要进一步地加强和改进代码。

通过代码的进一步改进,验证码被准确识别成0812!!成功啦!

def GrayImage(img):
    '''
    功能:图像灰度化
    '''
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # 转化为灰度图
    return img

def Binarisation(img):
    '''
    将图片二值化
    img:待处理的图像
    阈值:其值对识别率影响巨大,可根据验证码图片的具体情况将 125 改为其他值
    '''
    _, img = cv2.threshold(img, 125, 255, cv2.THRESH_BINARY)
    return img

def denoise_line(img, threshold):
    '''
    功能:线降
    '''
    h, w = img.shape[:2]
    for y in range(1, w - 1):  # 要去掉四条边线
        for x in range(1, h - 1):
            count = 0
            if img[x, y - 1] > threshold:
                count = count + 1
            if img[x, y + 1] > threshold:
                count = count + 1
            if img[x - 1, y] > threshold:
                count = count + 1
            if img[x + 1, y] > threshold:
                count = count + 1
            if img[x - 1, y - 1] > threshold:
                count = count + 1
            if img[x - 1, y + 1] > threshold:
                count = count + 1
            if img[x + 1, y + 1] > threshold:
                count = count + 1
            if img[x + 1, y - 1] > threshold:
                count = count + 1
            if count >= 6:
                img[x, y] = 255
    return img

# 读取验证码图片
image_path = 'D:\img.jpg'  # 替换为你保存的验证码图片路径
image = cv2.imread(image_path)

# 图像处理
gray = GrayImage(image)
binary = Binarisation(gray)
denoised = denoise_line(binary, 125)

# 使用 pytesseract 解析文本
text = pytesseract.image_to_string(denoised, config='--psm 6')

# 过滤非数字字符
digits = ''.join(filter(str.isdigit, text))

# 输出解析结果
print("验证码:", digits)
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值