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

500 views Asked by At
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!

2

There are 2 answers

0
Alexander On BEST ANSWER

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

if(videoRef.current){
}
0
Benndip On

I found how to resolve this issue

when using faceapi.detectAllFaces , you should do it like this

const detections = await faceapi.detectAllFaces(videoRef.current).withFaceLandmarks().withFaceDescriptors().withFaceExpressions()

.withFaceDescriptors() must be included.

Take note it is .withFaceDescriptors() not .withFaceDescriptor()

The s should be added if you are detecting all faces and removed for one face