forked from Snap-Engineering-Academy-2021/ml5-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript_faceapi.js
102 lines (88 loc) · 2.27 KB
/
script_faceapi.js
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
96
97
98
99
100
101
102
let faceapi;
let video;
let detections;
// by default all options are set to true
const detection_options = {
withLandmarks: true,
withDescriptors: false,
};
function setup() {
createCanvas(640, 480);
// load up your video
video = createCapture(VIDEO);
video.size(width, height);
// video.hide(); // Hide the video element, and just show the canvas
faceapi = ml5.faceApi(video, detection_options, modelReady);
textAlign(RIGHT);
// Hide the video element, and just show the canvas
video.hide();
}
function modelReady() {
console.log("ready!");
console.log(faceapi);
faceapi.detect(gotResults);
}
function gotResults(err, result) {
if (err) {
console.log(err);
return;
}
// console.log(result)
detections = result;
// background(220);
background(255);
image(video, 0, 0, width, height);
if (detections) {
if (detections.length > 0) {
// console.log(detections)
drawBox(detections);
drawLandmarks(detections);
}
}
faceapi.detect(gotResults);
}
function drawBox(detections) {
for (let i = 0; i < detections.length; i++) {
const alignedRect = detections[i].alignedRect;
const x = alignedRect._box._x;
const y = alignedRect._box._y;
const boxWidth = alignedRect._box._width;
const boxHeight = alignedRect._box._height;
noFill();
stroke(161, 95, 251);
strokeWeight(2);
rect(x, y, boxWidth, boxHeight);
}
}
function drawLandmarks(detections) {
noFill();
stroke(161, 95, 251);
strokeWeight(2);
for (let i = 0; i < detections.length; i++) {
const mouth = detections[i].parts.mouth;
const nose = detections[i].parts.nose;
const leftEye = detections[i].parts.leftEye;
const rightEye = detections[i].parts.rightEye;
const rightEyeBrow = detections[i].parts.rightEyeBrow;
const leftEyeBrow = detections[i].parts.leftEyeBrow;
drawPart(mouth, true);
drawPart(nose, false);
drawPart(leftEye, true);
drawPart(leftEyeBrow, false);
drawPart(rightEye, true);
drawPart(rightEyeBrow, false);
}
}
function drawPart(feature, closed) {
beginShape();
for (let i = 0; i < feature.length; i++) {
const x = feature[i]._x;
const y = feature[i]._y;
vertex(x, y);
}
if (closed === true) {
endShape(CLOSE);
} else {
endShape();
}
}