验证码图片识别(使用Python和TensorFlow)

(一)选题背景
验证码(CAPTCHA)作为一种用来区分计算机和人类用户的技术,在日常的互联网应用中广泛存在。通常,验证码是通过图片、音频等方式向用户提供一组无法通过机器自动识别的文字或者符号,来防止自动化脚本对网站进行注册、登录、评论等操作。验证码的图片识别技术常常成为机器学习中的一个经典问题。

随着人工智能技术的发展,利用机器学习模型,尤其是卷积神经网络(CNN),对验证码进行识别,成为了提高验证码破解效率的热门方法。希望通过本课设,借助机器学习技术,尝试破解验证码,提高网页安全性。

(二)机器学习案例设计方案
本案例通过模拟生成含有噪声与干扰线的验证码图片,并对这些图片进行预处理、降噪和灰度化等操作,再使用卷积神经网络(CNN)进行训练和识别。模型的输入是经过处理的图片数据,输出是验证码的文本结果。

验证码图片生成: 使用Python中的PIL库生成包含干扰线和噪点的验证码图片。
数据预处理: 对生成的验证码图片进行降噪、灰度化等预处理,转化为机器可以识别的格式。
模型构建: 使用TensorFlow框架构建卷积神经网络模型,对处理后的验证码进行识别。
模型训练与测试: 利用训练集进行模型训练,使用测试集评估模型效果。
(三)机器学习实现步骤

  1. 导入相关库
    python

import random
import os
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import tensorflow as tf
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt
2. 生成验证码图片
我们首先需要定义生成验证码图片的函数,这些图片将含有干扰线、噪点,并使用随机字母和数字。

python

def get_random_color(is_light=True):
"""随机生成颜色"""
r = random.randint(0, 127) + int(is_light) * 128
g = random.randint(0, 127) + int(is_light) * 128
b = random.randint(0, 127) + int(is_light) * 128
return r, g, b

def get_random_char():
"""生成随机字符(数字或字母)"""
chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
return random.choice(chars)

def draw_noise(draw, width, height):
"""生成干扰线"""
for _ in range(5):
x1, y1 = random.randint(0, width), random.randint(0, height)
x2, y2 = random.randint(0, width), random.randint(0, height)
draw.line([x1, y1, x2, y2], fill=get_random_color(is_light=True))

def generate_captcha_image(width=80, height=30):
"""生成包含字母和干扰线的验证码图片"""
bg_color = get_random_color(is_light=True)
img = Image.new('RGB', (width, height), bg_color)
draw = ImageDraw.Draw(img)

# 随机生成字符并绘制
font = ImageFont.truetype("arial.ttf", 24)
captcha_text = ''.join([get_random_char() for _ in range(4)])
for i, char in enumerate(captcha_text):
    char_color = get_random_color(is_light=False)
    draw.text((15 + 18 * i, 5), char, font=font, fill=char_color)

# 添加干扰线和噪点
draw_noise(draw, width, height)

# 显示生成的验证码图片
img.show()
return img, captcha_text

测试验证码生成

generate_captcha_image()
3. 数据预处理
为了让模型能够更好地训练和识别验证码,我们需要对生成的图片进行一些预处理,主要包括:将图像转为灰度图像、归一化以及图像去噪。

python

def preprocess_image(image):
"""对验证码图片进行预处理"""
# 转为灰度图像
image = image.convert('L')

# 图像二值化(去除噪声,增强对比)
threshold = 160
for i in range(image.width):
    for j in range(image.height):
        pixel = image.getpixel((i, j))
        if pixel > threshold:
            image.putpixel((i, j), 255)
        else:
            image.putpixel((i, j), 0)

return np.array(image)

测试预处理

image, _ = generate_captcha_image()
processed_image = preprocess_image(image)
plt.imshow(processed_image, cmap='gray')
plt.show()
4. 构建卷积神经网络模型
使用卷积神经网络(CNN)来识别验证码。为了训练模型,我们首先构建一个适用于验证码识别的CNN模型。

python

def build_model(input_shape=(30, 80, 1), num_classes=10):
"""构建CNN模型"""
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=input_shape),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dense(num_classes, activation='softmax')
])
return model

测试构建模型

model = build_model()
model.summary()
5. 模型训练
定义训练数据集和目标标签,接着使用TensorFlow训练模型。

python

训练数据生成

def generate_train_data(num_samples=1000, width=80, height=30):
"""生成训练数据"""
X_train = []
y_train = []
for _ in range(num_samples):
img, captcha_text = generate_captcha_image(width, height)
processed_img = preprocess_image(img)
X_train.append(processed_img)
y_train.append([int(c) for c in captcha_text]) # 转为数字标签

X_train = np.array(X_train)
X_train = X_train.reshape((-1, height, width, 1)) / 255.0
y_train = np.array(y_train)
return X_train, y_train

生成训练数据

X_train, y_train = generate_train_data()

构建和训练模型

model = build_model(input_shape=(30, 80, 1), num_classes=10)
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

训练模型

model.fit(X_train, y_train, epochs=5, batch_size=32)
6. 模型评估与预测
训练完模型后,可以用它对新的验证码进行预测。

python
更多内容访问ttocr.com或联系1436423940
def predict_captcha(model, image, width=80, height=30):
"""对验证码图片进行预测"""
processed_img = preprocess_image(image)
processed_img = processed_img.reshape((1, height, width, 1)) / 255.0
prediction = model.predict(processed_img)
predicted_text = ''.join([str(np.argmax(prediction[0][i])) for i in range(4)])
return predicted_text

测试预测

image, actual_text = generate_captcha_image()
predicted_text = predict_captcha(model, image)
print(f"真实文本: {actual_text}, 预测文本: {predicted_text}")

posted @   ttocr、com  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示