使用@tensorflow/tfjs-node运行人脸关键点检测时报不支持图像类型错误
问题原因
- 未移除Base64的Data URI前缀:你传入的base64串带有
data:image/jpeg;base64,头标识,直接转换为Buffer时,前缀会被编码进二进制数据中,导致tf.node.decodeImage无法识别到合法的图片文件头。 - tfjs依赖冲突:你同时安装了
@tensorflow/tfjs-node和@tensorflow/tfjs-node-gpu,两者底层绑定的二进制运算库不同,会引发加载异常,即使你仅导入了tfjs-node,也可能出现图片格式识别错误的问题。
解决方案
- 先处理Base64串,移除前缀后再转Buffer,同时指定解码通道适配模型输入要求:
try { const model = await faceLandmarksDetection.load( faceLandmarksDetection.SupportedPackages.mediapipeFacemesh ); // 移除data URI前缀 const pureBase64 = dataObj.data_url.replace(/^data:image\/\w+;base64,/, ''); const imgBuffer = Buffer.from(pureBase64, 'base64'); // 强制指定3通道解码,适配facemesh模型的RGB输入要求 const tensor = tf.node.decodeImage(imgBuffer, 3); console.log("Tensor ", tensor); const preds = await model.estimateFaces({ input: tensor, }); console.log(preds); // 用完及时释放张量显存 tensor.dispose(); } catch (err) { console.log(err); }
- 清理冲突依赖,仅保留对应版本的tfjs-node:
先执行卸载命令:npm uninstall @tensorflow/tfjs-node @tensorflow/tfjs-node-gpu- 若使用CPU运行:执行安装命令
npm i @tensorflow/tfjs-node - 若使用N卡GPU加速:执行安装命令
npm i @tensorflow/tfjs-node-gpu
- 若使用CPU运行:执行安装命令
内容的提问来源于stack exchange,提问作者hyprstack
相关产品推荐
相关产品推荐

