使用 Keras 构建验证码识别系统

在本文中,我们将使用 Keras 和 卷积神经网络(CNN) 构建一个验证码识别系统。通过使用深度学习的强大能力,结合图像预处理技术,我们可以实现对数字或字母验证码的自动识别。Keras 是一个高层神经网络API,能够快速地构建和训练神经网络模型,适合快速开发和实验。

  1. 环境准备
    首先,确保你已经安装了所需的库:

bash
更多内容访问ttocr.com或联系1436423940
pip install tensorflow opencv-python numpy pillow
TensorFlow:提供Keras作为高层API,支持深度学习任务。
OpenCV:用于图像预处理(如图像加载、转换、二值化等)。
NumPy:用于数据处理。
Pillow:图像处理工具。
2. 数据集准备与图像预处理
验证码图像常常包含噪点、干扰线等,因此我们需要对图像进行一系列的预处理操作,以提高后续的识别效果。常见的预处理步骤包括:灰度化、二值化、去噪、字符切割等。

(1) 图像加载与预处理
首先,我们加载验证码图像并进行灰度化和二值化处理,以便后续进行字符分割。

python

import cv2
import numpy as np

def preprocess_image(img_path):
# 读取图像
img = cv2.imread(img_path)

# 转为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 二值化处理,使用 Otsu 的方法自动选择阈值
_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

# 高斯模糊去噪
blurred = cv2.GaussianBlur(binary, (5, 5), 0)

return blurred

示例图像路径

img_path = 'captcha_images/test1.png'
processed_img = preprocess_image(img_path)

显示处理后的图像

cv2.imshow('Processed Image', processed_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
(2) 提取字符区域
在验证码图像中,每个字符是由外部轮廓来区分的。我们可以使用 轮廓检测 来提取字符区域。

python

def extract_characters(processed_img):
contours, _ = cv2.findContours(processed_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
char_images = []
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
if w > 10 and h > 10: # 忽略小的噪点
char_img = processed_img[y:y+h, x:x+w]
char_images.append(char_img)

# 按照字符的从左到右顺序排序
char_images.sort(key=lambda x: x[0][0])  # 排序依据是字符的左上角 x 坐标
return char_images

提取字符区域

char_images = extract_characters(processed_img)

显示提取的字符

for i, char_img in enumerate(char_images):
cv2.imshow(f'Character {i+1}', char_img)
cv2.waitKey(0)

cv2.destroyAllWindows()
3. 构建卷积神经网络(CNN)
我们将使用 Keras 构建一个卷积神经网络(CNN)模型来对每个字符进行分类。Keras 提供了一个简单的接口,用于构建和训练神经网络。

(1) 构建 CNN 模型
python

from tensorflow.keras import layers, models

def build_cnn_model(input_shape=(28, 28, 1), num_classes=36):
model = models.Sequential()

# 卷积层1
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=input_shape))
model.add(layers.MaxPooling2D((2, 2)))

# 卷积层2
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))

# 卷积层3
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))

# 展平层
model.add(layers.Flatten())

# 全连接层
model.add(layers.Dense(128, activation='relu'))

# 输出层:假设字符集包含数字(0-9)和大写字母(A-Z)
model.add(layers.Dense(num_classes, activation='softmax'))

return model

构建模型

model = build_cnn_model(input_shape=(28, 28, 1), num_classes=36)
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

查看模型结构

model.summary()
(2) 数据准备与训练
对于训练,我们需要将图像数据归一化,并将标签转换为对应的整数标签。假设字符集包括 0-9 和 A-Z,总共 36 个字符。

python

import numpy as np
from tensorflow.keras.utils import to_categorical

假设你有训练图像和标签

train_images = np.array([cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) for img_path in train_image_paths])
train_labels = np.array(train_labels)

数据归一化

train_images = train_images.astype('float32') / 255.0
train_images = train_images.reshape(train_images.shape[0], 28, 28, 1)

标签转换为独热编码

train_labels = to_categorical(train_labels, num_classes=36)

训练模型

model.fit(train_images, train_labels, epochs=10, batch_size=32)
4. 模型评估与预测
训练完毕后,我们可以使用测试集来评估模型的性能,并对新的验证码图像进行预测。

(1) 评估模型
python

假设你有测试图像和标签

test_images = np.array([cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) for img_path in test_image_paths])
test_labels = np.array(test_labels)

数据归一化

test_images = test_images.astype('float32') / 255.0
test_images = test_images.reshape(test_images.shape[0], 28, 28, 1)

评估模型

test_loss, test_accuracy = model.evaluate(test_images, test_labels)
print(f"Test Accuracy: {test_accuracy * 100:.2f}%")
(2) 对验证码进行预测
在对模型进行训练和评估后,我们可以对新的验证码图像进行预测:

python

def predict_captcha(model, img_path, char_set="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (28, 28)) # 将图像调整为 28x28
img = img.astype('float32') / 255.0 # 归一化
img = np.expand_dims(img, axis=0) # 增加批次维度
img = np.expand_dims(img, axis=3) # 增加通道维度

# 预测
pred = model.predict(img)
predicted_char = char_set[np.argmax(pred)]

return predicted_char

对图像进行预测

captcha_image = 'captcha_images/test1.png'
predicted_label = predict_captcha(model, captcha_image)
print(f"Predicted CAPTCHA label: {predicted_label}")

posted @   ttocr、com  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示