RoboFlow JS报错:输入图像张量形状与模型要求不匹配
问题排查与解决
核心问题分析
错误提示明确显示输入张量的形状不符合模型要求:
- 模型期望格式:
[1,3,640,640](批次维度 + 通道数 + 高度 + 宽度,即CHW) - 实际输入格式:
[1,640,640,3](批次维度 + 高度 + 宽度 + 通道数,即HWC)
同时代码里存在**未定义变量t4d**的问题,导致无法正确获取待检测图像。
修复步骤
1. 修正图像引用变量
把未定义的t4d替换为获取页面中id="image"的DOM元素:
const imgElement = document.getElementById('image'); model.detect(imgElement)
2. 调整张量通道顺序
针对形状不匹配问题,有两种直接解决方案:
方案一:利用Roboflow.js内置配置
在detect方法中传入配置参数,指定输入格式为通道在前:
model.detect(imgElement, { format: "channels_first" })
方案二:手动转换张量格式
如果内置配置不生效,可通过TensorFlow.js的transpose方法手动调整通道顺序:
roboflow.load({ model: '****', version: '**', }).then(model => { const imgElement = document.getElementById('image'); tf.tidy(() => { const inputTensor = tf.browser.fromPixels(imgElement) .resizeNearestNeighbor([640, 640]) // 调整尺寸到模型要求的640x640 .expandDims(0) // 添加批次维度 .transpose([0, 3, 1, 2]); // 将[1,640,640,3]转为[1,3,640,640] return model.execute({ images: inputTensor }); }).then(predictions => { // 后续处理逻辑不变 console.log(predictions); predictions.forEach(prediction => { const { class: className, bbox } = prediction; const { left, top, width, height } = bbox; const div = document.createElement('div'); div.innerHTML = className; div.style.border = '2px solid red'; div.style.position = 'absolute'; div.style.left = `${left}px`; div.style.top = `${top}px`; div.style.width = `${width}px`; div.style.height = `${height}px`; document.body.appendChild(div); }); }).catch(error => { console.error(error); }); })
完整修复后的代码
<!DOCTYPE html> <html> <head> <title>Adding Roboflow.js Modeli</title> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.15.0/dist/tf.js"></script> <script src="https://cdn.roboflow.com/0.2.20/roboflow.js"></script> </head> <body> <img id="image" src="images (10).jpg"> <script> roboflow.auth({ publishable_key: '************************' }); roboflow.load({ model: '****', version: '**', }).then(model => { const imgElement = document.getElementById('image'); // 使用内置配置修正通道顺序 model.detect(imgElement, { format: "channels_first" }).then(predictions => { console.log(predictions); predictions.forEach(prediction => { const { class: className, bbox } = prediction; const { left, top, width, height } = bbox; const div = document.createElement('div'); div.innerHTML = className; div.style.border = '2px solid red'; div.style.position = 'absolute'; div.style.left = `${left}px`; div.style.top = `${top}px`; div.style.width = `${width}px`; div.style.height = `${height}px`; document.body.appendChild(div); }); }).catch(error => { console.error(error); }); }).catch(error => { console.error(error); }); </script> </body> </html>
内容的提问来源于stack exchange,提问作者alibali
相关产品推荐
相关产品推荐

