I've implemented face detection using face-api.js. Everything is working properly but the problem I faced is that the face detection process for weak devices can be trouble and cause lags because of the main thread.
The approach that came to my mind was to implement the face detection process inside a Web Worker.
I'm passing the video element to face-api.js for live detection. So, I need to access the DOM to select the video element and pass it to the API.
faceApi.worker.js
import * as faceApi from 'face-api.js' // Used worker-loader
const video = document.getElementById('live-video') // 2nd approach
const processVideo = video => {
faceApi.detectSingleFace(video, new faceApi.TinyFaceDetectorOptions())
.then(detection => postMessage(!!detection))
.then(() => requestionAnimationFrame(() => processVideo()))
}
onmessage = e => {
faceApi.nets.tinyFaceDetector.loadfromUri('/auth/models')
.then(() => e.data.addEventListener('play', () => processVideo(e.data)))
}
1st approach
const video = document.getElementById('live-video')
const worker = new Worker('/faceApi.worker.js')
worker.postMessage(video)
Error: DOMException: Failed to execute 'postMessage' on 'Worker': HTMLVideoElement object could not be cloned.
2nd approach
Selecting the video element inside the worker instead of passing it to the worker.
const video = document.getElementById('live-video')
Error: faceApi.worker.js:2 Uncaught ReferenceError: document is not defined at onmessage
Q: How do I access the DOM in order to select the video element?
There might be other ways to achieve it, any helps would be appreciated.