1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
<!-- App.vue -->
<template>
<div class="demo scene flex">
<video class="video" autoplay ref="videoEle"></video>
<canvas width="300" height="160" ref="canvasEle" class="canvas"></canvas>
</div>
</template>
<script setup>
import { nextTick, onMounted, ref } from "vue";
import * as faceapi from "face-api.js";
const videoEle = ref();
const imgEle = ref();
const canvasEle = ref();
const minConfidenceFace = 0.5;
const faceapiOptions = new faceapi.SsdMobilenetv1Options({});
onMounted(() => {
init();
});
async function init() {
await loadNet();
await initCamera();
draw();
}
async function draw() {
const canvas = canvasEle.value.getContext("2d");
canvas.clearRect(0, 0, 300, 200);
canvas.drawImage(videoEle.value, 0, 0, 300, 200);
const detections = await faceapi
.detectAllFaces(videoEle.value)
.withFaceLandmarks()
.withFaceDescriptors();
if (!detections) {
return;
}
const resizeDetections = faceapi.resizeResults(detections, {
width: 300,
height: 160,
});
faceapi.draw.drawDetections(canvas, resizeDetections);
setTimeout(draw, 50);
// faceapi.draw.drawFaceLandmarks(canvas, resizeDetections);
// faceapi.draw.drawFaceExpressions(canvas, resizeDetections);
}
async function loadNet() {
const detectionNet = faceapi.nets.ssdMobilenetv1;
await detectionNet.load("/models");
await faceapi.loadFaceLandmarkModel("./models");
await faceapi.loadFaceExpressionModel("/models");
await faceapi.loadFaceDetectionModel("/models");
await faceapi.loadFaceRecognitionModel("/models");
console.log("loadNet");
return detectionNet;
}
async function initCamera(width = 300, height = 200) {
const cam = videoEle.value;
cam.width = width;
cam.height = height;
const stream = await navigator.mediaDevices.getUserMedia({
audio: false,
video: true,
});
cam.srcObject = stream;
return new Promise((resolve) => {
cam.onloadedmetadata = () => {
console.log("onloadedmetadata");
resolve(cam);
};
});
}
</script>
<style lang="scss">
.video {
width: 500px;
height: 300px;
}
.canvas {
width: 600px;
height: 300px;
}
.img {
width: 250px;
height: 300px;
}
</style>
|