TensorFlow.js单通道CNN模型适配摄像头3通道输入解决方案
解决方案
问题分析
你遇到的错误有两个核心原因:
- 模型输入要求4维张量(格式为
[批次大小, 高度, 宽度, 通道数]),但摄像头捕获的是3维张量[28,28,3] - 模型仅支持单颜色通道(灰度图),但摄像头输出的是3通道RGB图
不修改模型的适配方法
完全可以在不修改模型的前提下解决,TensorFlow.js提供了现成的API处理通道转换和维度扩展:
- 使用
tf.image.rgbToGrayscale()将3通道RGB图转为单通道灰度图 - 使用
tf.expandDims()为张量增加批次维度,满足模型的4维输入要求
修改后的代码
async function run() { const webcamElement = document.getElementById('webcam'); const model = await tf.loadLayersModel('./model/my-model.json'); const webcam = await tf.data.webcam(webcamElement,{ resizeWidth:28, resizeHeight:28 }); while (true) { const img = await webcam.capture(); // 1. 转灰度图(3通道→1通道) const grayscaleImg = tf.image.rgbToGrayscale(img); // 2. 增加批次维度(3维→4维,格式变为[1,28,28,1]) const inputTensor = grayscaleImg.expandDims(0); // 模型预测 const result = model.predict(inputTensor); // 提取预测结果(适配模型输出格式) const predictions = result.dataSync(); const predictedClass = predictions.indexOf(Math.max(...predictions)); const probability = Math.max(...predictions); document.getElementById('console').innerText = ` prediction: ${predictedClass} probability: ${probability.toFixed(4)} `; // 释放所有临时张量,避免内存泄漏 img.dispose(); grayscaleImg.dispose(); inputTensor.dispose(); result.dispose(); await tf.nextFrame(); } } document.addEventListener('DOMContentLoaded', run);
额外说明
- 原代码中
result[0].className和result[0].probability不符合模型实际输出格式,model.predict()返回的是张量,需要用dataSync()提取数值后处理 - 所有临时张量必须调用
dispose()释放,防止浏览器内存溢出
内容的提问来源于stack exchange,提问作者Jin Liu
相关产品推荐
相关产品推荐

