toNetInput 函数出错 - 预期媒体的类型为 HTMLCanvasElement、HTMLImageElement、HTMLVideoElement 或 tf.Tensor3D

作者: SamLorenzoSanc创建于 2025年2月15日更新于 2025年3月27日

我在尝试在具有 node-canvas 生成的 canvas 的 Node.js 环境中使用 face-api.js 时遇到了错误。错误发生在将 canvas 传递给 toNetInput 函数时。错误消息如下: `Error: toNetInput - expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id at /path/to/node_modules/face-api.js/build/commonjs/dom/toNetInput.js:38:35 ...` 我使用 node-canvas 加载图像,调整大小,然后使用 node-canvas 包中的 createCanvas 创建 canvas。canvas (localCanvas) 已经创建并绘制完毕,但是当我尝试通过 toNetInput 函数将其传递给 face-api.js 时,就出现了上述错误。 `export const loginFacial = async (req, res) => { try { const { username } = req.body; if (!req.file) { return res.status(400).json({ message: 'No file uploaded' }); } const user = await User.findOne({ username }); if (!user) { return res.status(404).json({ message: 'User not found' }); } if (!user.faceId || user.faceId.length === 0) { return res.status(400).json({ message: 'No face ID stored for user' }); } await loadFaceApiModels(); const img = await loadImage(req.file.path); const MAX_WIDTH = 640; const MAX_HEIGHT = 480; const scale = Math.min(MAX_WIDTH / img.width, MAX_HEIGHT / img.height); const newWidth = img.width * scale; const newHeight = img.height * scale; const localCanvas = createCanvas(newWidth, newHeight); const ctx = localCanvas.getContext('2d'); ctx.drawImage(img, 0, 0, newWidth, newHeight); const input = await faceapi.toNetInput(localCanvas); console.log('Input para face-api.js:', input); // Check the input being passed const detections = await faceapi.detectSingleFace(input, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks().withFaceDescriptor(); if (!detections) { return res.status(401).json({ message: 'No face detected' }); } const storedFaceDescriptor = new Float32Array(user.faceId); const faceMatcher = new faceapi.FaceMatcher([storedFaceDescriptor]); const bestMatch = faceMatcher.findBestMatch(detections.descriptor); if (bestMatch.distance < 0.6) { const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' }); return res.json({ token }); } else { return res.status(401).json({ message: 'Face authentication failed' }); } } catch (error) { console.error('Error in loginFacial:', error); res.status(500).json({ message: 'Internal Server Error' }); } };` 我直接将 localCanvas (由 node-canvas 生成) 传递给 face-api.js,通过 faceapi.toNetInput(localCanvas)。尽管 localCanvas 是一个有效的 node-canvas 画布对象,但错误表明 face-api.js 并不接受它作为有效输入。toNetInput 函数似乎期望一个标准的 HTMLCanvasElement、HTMLImageElement 或

内容来源: justadudewhohacks/face-api.js