javascriptreactjstensorflow.jsface-api

Cannot read property 'length' of undefined in face-api.js react


import React, { useRef, useState, useEffect } from 'react';
import * as faceapi from 'face-api.js';


function App() {
  const videoRef = useRef(null);
  const canvasRef = useRef(null);
  useEffect(() => {
    const loadModels = async () => {
      try {
        const MODEL_URL = '/models'
        Promise.all([
          faceapi.nets.tinyFaceDetector.loadFromUri(MODEL_URL),
          faceapi.nets.faceLandmark68Net.loadFromUri(MODEL_URL),
          faceapi.nets.faceRecognitionNet.loadFromUri(MODEL_URL),
          faceapi.nets.faceExpressionNet.loadFromUri(MODEL_URL),
        ]).then(startVideo())
      } catch (error) {
        console.error(error)
      }

    }
    loadModels();

  }, [])
  const startVideo = async () => {
    try {
      let stream = null;
      stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
      videoRef.current.srcObject = stream;
    } catch (error) {
      console.error(error)
    }
  }

  const handleVideoOnPlay = () => {
    setInterval(async () => {
      const detections = await faceapi.
        detectAllFaces(videoRef.current, new faceapi.TinyFaceDetectorOptions())
        .withFaceLandmarks()
        .withFaceExpressions()
    }, 100)
  }
  return (
    <div className="App">
      <video ref={videoRef} autoPlay muted onPlay={handleVideoOnPlay} height={640} width={640} />
      <canvas ref={canvasRef} />
    </div>
  );
}

export default App;

Hi guys, this is my code, I followed a tutorial https://www.youtube.com/watch?v=EejpxMtDg8M

and I get this error message: enter image description here

does anyone know whats the problem? I did everything as followed and I have no idea whats wrong, thanks so much for the help!


Solution

  • The erorr was videoRef.current was null, just need to wrap it in

    if(videoRef.current){
    }