Reputation: 1233
I am using face-api library. https://github.com/justadudewhohacks/face-api.js
I am trying to get a photo from the video when face-api recognizes face more than 0.5 and when the user happy more than 0.6. I find out how to get that info using face-api, but didn't know how to get a photo without user interaction and put it in some img element(base64 format of image).
Here is code example what I have till now:
<body>
<video id="video" width="720" height="560" autoplay muted></video>
<div id="screenshot">
<img src="" style="display: none">
<script>
const video = document.getElementById('video')
Promise.all([
faceapi.nets.tinyFaceDetector.loadFromUri('/face-api/models'),
faceapi.nets.faceLandmark68Net.loadFromUri('/face-api/models'),
faceapi.nets.faceRecognitionNet.loadFromUri('/face-api/models'),
faceapi.nets.faceExpressionNet.loadFromUri('/face-api/models')
]).then(startVideo)
function startVideo() {
navigator.getUserMedia(
{video: {}},
stream => video.srcObject = stream,
err => console.error(err)
)
}
video.addEventListener('play', () => {
const canvas = faceapi.createCanvasFromMedia(video)
document.body.append(canvas)
const displaySize = {width: video.width, height: video.height}
faceapi.matchDimensions(canvas, displaySize)
setInterval(async () => {
const detections = await faceapi.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks().withFaceExpressions()
const resizedDetections = faceapi.resizeResults(detections, displaySize)
canvas.getContext('2d').drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
if (resizedDetections.length > 0 && resizedDetections[0].detection.score > 0.7 && resizedDetections[0].expressions.happy > 0.5) {
//HERE I NEED TO TAKE IMAGE FROM PHOTO
}
}, 100)
})
</script>
Can anybody help me with that part?
you can find html version of it here:
Upvotes: 3
Views: 2333
Reputation: 1233
I find out a solution to this problem. I think someone will use it or help him to solve some problem or complete project :) I'll be glad if anybody uses it.
Add div with id screenshot
in form where you like to store images and add this code:
if (resizedDetections.length > 0 && resizedDetections[0].detection.score > 0.7 && resizedDetections[0].expressions.happy > 0.5) {
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0);
const img = document.createElement("img");
img.src = canvas.toDataURL('image/webp');
document.getElementById('screenshot').appendChild(img)
}
this will add an image on your form so you can use it for sending it to the server-side part of the project.
Upvotes: 3