使用 TensorFlow 和 CNN 实现验证码识别系统 - # 使用测试集评估模型 test_images = np

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力网站平台 👁️ 352 次阅读

在本文中,我们将使用 TensorFlow 和 卷积神经网络(CNN) 来实现一个验证码识别系统。该系统将通过处理验证码图像并训练神经网络模型,完成对验证码中的字符的自动识别。通过结合 TensorFlow 的深度学习能力和 CNN 的图像处理优势,我们能够有效地识别常见的数字和字母验证码。

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

bash更多内容访问ttocr.com或联系1436423940

pip install tensorflow opencv-python numpy pillow TensorFlow:深度学习框架,用于构建、训练和评估神经网络。 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) 通过图像预处理和字符提取,我们已经获得了验证码中的字符区域。接下来,我们将使用卷积神经网络(CNN)来训练模型,进行字符识别。CNN 是一种非常适合图像分类的深度学习模型,可以有效提取图像中的空间特征。

(1) 构建 CNN 模型 我们使用 Keras 和 TensorFlow 构建一个简单的卷积神经网络。该网络将包括卷积层、池化层和全连接层。

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

from tensorflow.keras.utils import to_categorical

# 假设我们已经准备好图像和标签 # images 是一个形状为 (num_samples, 28, 28, 1) 的数组,包含每个字符的图像 # labels 是一个形状为 (num_samples,) 的数组,包含每个字符的标签

# 数据归一化 images = images.astype('float32') / 255.0

# 标签独热编码 labels = to_categorical(labels, num_classes=36) 拼多多帮助力入口

# 训练模型 model.fit(images, 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)

# 评估模型 loss, accuracy = model.evaluate(test_images, test_labels, batch_size=32) print(f"Test Accuracy: {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)) 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}")

使用 TensorFlow 和 CNN 实现验证码识别系统

参考链接

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧