-
Notifications
You must be signed in to change notification settings - Fork 0
/
faceapiService.js
69 lines (51 loc) · 1.88 KB
/
faceapiService.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
const save = require("./utils/saveFile");
const path = require("path");
const tf = require("@tensorflow/tfjs-node");
const canvas = require("canvas");
const faceapi = require("@vladmandic/face-api/dist/face-api.node.js");
const modelPathRoot = "./models";
let optionsSSDMobileNet;
const { Canvas, Image, ImageData } = canvas;
faceapi.env.monkeyPatch({ Canvas, Image, ImageData });
async function image(file) {
const decoded = tf.node.decodeImage(file);
const casted = decoded.toFloat();
const result = casted.expandDims(0);
decoded.dispose();
casted.dispose();
return result;
}
async function detect(tensor) {
const result = await faceapi.detectAllFaces(tensor, optionsSSDMobileNet).withFaceLandmarks().withFaceExpressions();
console.log(result);
return result;
}
async function main(file, filename) {
console.log("FaceAPI single-process test");
await faceapi.tf.setBackend("tensorflow");
await faceapi.tf.enableProdMode();
await faceapi.tf.ENV.set("DEBUG", false);
await faceapi.tf.ready();
console.log("Loading FaceAPI models");
const modelPath = path.join(__dirname, modelPathRoot);
await faceapi.nets.ssdMobilenetv1.loadFromDisk(modelPath);
await faceapi.nets.faceExpressionNet.loadFromDisk(modelPath);
await faceapi.nets.faceLandmark68Net.loadFromDisk(modelPath);
optionsSSDMobileNet = new faceapi.SsdMobilenetv1Options({
minConfidence: 0.5,
});
const tensor = await image(file);
const result = await detect(tensor);
console.log("Detected faces:", result.length);
const canvasImg = await canvas.loadImage(file);
const out = await faceapi.createCanvasFromMedia(canvasImg);
faceapi.draw.drawDetections(out, result);
faceapi.draw.drawFaceExpressions(out, result);
save.saveFile(filename, out.toBuffer("image/jpeg"));
console.log(`done, saved results to ${filename}`);
tensor.dispose();
return result;
}
module.exports = {
detect: main,
};