用 Java 和 DL4J 实现验证码识别系统

在本文中,我们将用 Java 语言配合 DeepLearning4J 框架构建一个图像验证码识别系统,包括数据准备、模型搭建、训练和测试四个主要部分。


1. 环境准备

确保你已配置以下工具:

  • JDK 8 或以上
  • Maven
  • DL4J 依赖(加入到 pom.xml):

登录后复制

plain 复制代码
<dependencies>
    <dependency>
        <groupId>org.deeplearning4j</groupId>
        <artifactId>deeplearning4j-core</artifactId>
        <version>1.0.0-beta7</version>
    </dependency>
    <dependency>
        <groupId>org.nd4j</groupId>
        <artifactId>nd4j-native-platform</artifactId>
        <version>1.0.0-beta7</version>
  更多内容访问ttocr.com或联系1436423940
  </dependency>
</dependencies>

2. 生成验证码数据

验证码图片可以用 Python 生成后导入,也可以使用 Java 的图形库手动合成。在此我们假设你已经将类似 captcha_samples/A9KD_0.png 的图片准备好。


3. 加载数据集

使用 NativeImageLoader 读取并转换图像:
登录后复制

plain 复制代码
import org.datavec.image.loader.NativeImageLoader;
import org.nd4j.linalg.dataset.api.preprocessor.DataNormalization;
import org.nd4j.linalg.dataset.api.preprocessor.ImagePreProcessingScaler;
import org.nd4j.linalg.api.ndarray.INDArray;

public class CaptchaLoader {
    private final NativeImageLoader loader = new NativeImageLoader(60, 160, 3);
    private final DataNormalization scaler = new ImagePreProcessingScaler(0, 1);

    public INDArray loadImage(File imageFile) throws IOException {
        INDArray image = loader.asMatrix(imageFile);
        scaler.transform(image);
        return image;
    }
}

标签处理可以使用字符集映射:
登录后复制

plain 复制代码
String characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

int[] labelToIndices(String label) {
    int[] indices = new int[label.length()];
    for (int i = 0; i < label.length(); i++) {
        indices[i] = characters.indexOf(label.charAt(i));
    }
    return indices;
}

4. 构建 CNN 模型

登录后复制

plain 复制代码
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.layers.*;
import org.nd4j.linalg.lossfunctions.LossFunctions;

MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
    .updater(new Adam(0.001))
    .list()
    .layer(new ConvolutionLayer.Builder(5, 5).nIn(3).nOut(32).stride(1, 1).activation(Activation.RELU).build())
    .layer(new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX).kernelSize(2, 2).stride(2, 2).build())
    .layer(new ConvolutionLayer.Builder(3, 3).nOut(64).stride(1, 1).activation(Activation.RELU).build())
    .layer(new DenseLayer.Builder().nOut(256).activation(Activation.RELU).build())
    .layer(new OutputLayer.Builder(LossFunctions.LossFunction.MCXENT)
        .nOut(4 * 36).activation(Activation.SOFTMAX).build()) // 4字符,每个36种可能
    .setInputType(InputType.convolutional(60, 160, 3))
    .build();

MultiLayerNetwork model = new MultiLayerNetwork(conf);
model.init();

5. 模型训练

登录后复制

plain 复制代码
DataSetIterator trainIter = ... // 自定义加载器,包装图像和标签
model.fit(trainIter, 10); // 训练10个epoch

你可以实现 RecordReaderDataSetIterator 配合图像目录使用,或自定义 DataSetIterator


6. 测试识别

登录后复制

plain 复制代码
File testImage = new File("captcha_samples/A9KD_0.png");
INDArray image = loader.loadImage(testImage);
INDArray output = model.output(image);

int[] prediction = ... // 从 output 中取最大概率字符索引
String result = decodeIndices(prediction);
System.out.println("预测: " + result);
相关推荐
我命由我123454 小时前
CesiumJS 笔记 - 获取容器中心点、Cartesian3 clone 方法、修改 Cartesian3 对象的高度
前端·javascript·css·前端框架·html·html5·js
从零开始学习人工智能5 小时前
【踩坑实录】WSL2 解决 onnxruntime\-gpu ImportError: libcudart\.so\.13 无 CUDA13 运行库问题
python
Hopebearer_5 小时前
页面突然只剩 DOM?一次静态资源版本错配排查
前端·部署
东风破_6 小时前
ESLint 是什么?为什么你的项目需要它?
前端·后端·代码规范
嘻哈∠※6 小时前
0061基于 SpringBoot 的投稿与稿件处理系统设计与实现
java·spring boot·后端
WWJA王文举6 小时前
I²C通信完整流程详解:START、地址、ACK、数据、Repeated START和STOP一次讲透
c语言·开发语言
卷无止境6 小时前
在 awesome-fastapi 里,哪些库值得一看?
后端·python
ltl6 小时前
实时 OS 巡礼:VxWorks、QNX、Zephyr 与 PREEMPT_RT
linux
zhanghaha13146 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
我是谁??7 小时前
Ubuntu22.04更换清华源
linux·运维·服务器