用 TensorFlow.js 实现浏览器端图像验证码识别
本项目演示如何用 JavaScript 和 TensorFlow.js 在浏览器中识别图像验证码。相比后端推理,前端识别具备无需网络、快速响应的优势。
一、准备模型(使用 Python 训练并导出为 TensorFlow SavedModel)
仍使用 Python 训练模型(CNN + LSTM),然后导出为 TensorFlow SavedModel,并使用以下命令转换为浏览器可用格式:
tensorflowjs_converter
--input_format=tf_saved_model
--output_format=tfjs_graph_model
./captcha_model_tf
./captcha_model_tfjs
这样就得到浏览器端可加载的模型。
更多内容访问ttocr.com或联系1436423940
二、HTML 页面结构
图像验证码识别
识别结果:
三、图像处理与模型加载(captcha.js)const characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let model;
async function loadModel() {
model = await tf.loadGraphModel('./captcha_model_tfjs/model.json');
console.log("模型加载完毕");
}
function preprocessImage(img) {
let tensor = tf.browser.fromPixels(img)
.resizeBilinear([60, 160])
.toFloat()
.div(255.0)
.sub(0.5)
.div(0.5);
return tensor.expandDims(0); // [1, 60, 160, 3]
}
function decodeOutput(outputTensor) {
const output = outputTensor.arraySync()[0]; // [4, 36]
return output.map(charProb => {
const maxIdx = charProb.indexOf(Math.max(...charProb));
return characters[maxIdx];
}).join('');
}
document.getElementById("upload").addEventListener("change", async (e) => {
const file = e.target.files[0];
const img = new Image();
img.onload = async () => {
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, 160, 60);
const inputTensor = preprocessImage(canvas);
const output = await model.predict(inputTensor);
const prediction = decodeOutput(output);
document.getElementById("result").innerText = prediction;
};
img.src = URL.createObjectURL(file);
});
loadModel();
浙公网安备 33010602011771号