用 Node.js 和 TensorFlow.js 实现图像验证码识别
本示例展示如何在 Node.js 环境中加载训练好的 TensorFlow 模型,并对图像验证码进行识别。
一、环境准备
- 安装依赖
npm init -y
npm install @tensorflow/tfjs-node jimp
@tensorflow/tfjs-node: TensorFlow.js 的 Node.js 后端(速度快)。
jimp: 图像读取与处理库。
二、模型准备(来自 Python)
你需要先用 TensorFlow/Keras 在 Python 中训练模型并导出 .json + .bin 格式,或使用 SavedModel 导出后转换为 TF.js 格式:
更多内容访问ttocr.com或联系1436423940
安装转换器
npm install -g tensorflowjs_converter
转换模型
tensorflowjs_converter --input_format=tf_saved_model ./saved_model ./tfjs_model
三、加载图像并处理为 Tensor
const tf = require('@tensorflow/tfjs-node');
const Jimp = require('jimp');
async function loadImageAsTensor(path) {
const image = await Jimp.read(path);
image.resize(160, 60);
const { data, width, height } = image.bitmap;
const buffer = new Float32Array(width * height * 3);
for (let i = 0; i < width * height; i++) {
const idx = i * 4;
buffer[i * 3] = (data[idx] / 255 - 0.5) / 0.5;
buffer[i * 3 + 1] = (data[idx + 1] / 255 - 0.5) / 0.5;
buffer[i * 3 + 2] = (data[idx + 2] / 255 - 0.5) / 0.5;
}
return tf.tensor4d(buffer, [1, 60, 160, 3]);
}
四、模型加载与预测
async function predictCaptcha(imagePath) {
const model = await tf.loadLayersModel('file://./tfjs_model/model.json');
const input = await loadImageAsTensor(imagePath);
const output = model.predict(input); // [1, 4, 36]
const outputData = output.arraySync()[0]; // [4, 36]
const characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let result = '';
for (let i = 0; i < 4; i++) {
const maxIndex = outputData[i].indexOf(Math.max(...outputData[i]));
result += characters[maxIndex];
}
console.log(识别结果: ${result});
}
predictCaptcha('./captcha_samples/A3B9_0.png');
浙公网安备 33010602011771号