forked from Im-Rises/emotion-recognition-website
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
219 lines (187 loc) · 5.72 KB
/
index.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
const video = document.getElementById("video");
const canvas = document.getElementById("canvas");
const canvasBuffer = document.getElementById("canvasBuffer");
const canvasFace = document.getElementById("canvasFace");
const results = document.getElementById("showEmotion");
const select = document.getElementById("select");
const change_camera = document.getElementById("change_camera");
let ctx = canvas.getContext("2d");
let ctxBuffer = canvasBuffer.getContext("2d");
let ctxFace = canvasFace.getContext("2d");
let modelForFaceDetection;
let modelForEmotionRecognition;
let currentEmotion = "";
let currentStream;
let frameIter = 0;
const emotions = [
"😡 angry : ",
"🤮 disgust : ",
"😨 fear : ",
"😄 happy : ",
"😐 neutral : ",
"😭 sad : ",
"😯 surprise : ",
];
const gotDevices = (mediaDevices) => {
select.innerHTML = "";
select.appendChild(document.createElement("option"));
let count = 1;
mediaDevices.forEach((mediaDevice) => {
if (mediaDevice.kind === "videoinput") {
const option = document.createElement("option");
option.value = mediaDevice.deviceId;
const label = mediaDevice.label || `Camera ${count++}`;
const textNode = document.createTextNode(label);
option.appendChild(textNode);
select.appendChild(option);
}
});
};
const stopMediaTracks = (stream) => {
stream.getTracks().forEach((track) => {
track.stop();
});
};
const setupCamera = async () => {
// Solution 1
navigator.mediaDevices
.getUserMedia({ video: true, audio: false })
.then(function (stream) {
video.srcObject = stream;
video.play();
})
.catch(function (err) {
console.log("An error occurred! " + err);
});
modelForFaceDetection = await blazeface.load();
modelForEmotionRecognition = await tf.loadLayersModel(
"https://raw.githubusercontent.com/Im-Rises/emotion-recognition-website/main/resnet50js_ferplus/model.json"
);
};
const getIndexOfMax = R.indexOf(Math.max);
const getBestEmotion = (pred) => emotions[getIndexOfMax(pred)];
const getPercentage = R.pipe(R.multiply(100), parseInt);
const getScoreInPercentage = R.map(getPercentage);
const getEmotionNearToItsScore = (listOfEmotions) => (pred) =>
R.transpose([listOfEmotions, pred]);
const getListOfEmotionsSorted = R.sortBy(R.prop(1));
const magnifyOnePrediction = R.pipe(
R.prepend("<p>"),
R.append(" %</p>"),
R.join("")
);
const magnifyResults = (listOfEmotions) =>
R.pipe(
getScoreInPercentage,
getEmotionNearToItsScore(listOfEmotions),
getListOfEmotionsSorted,
R.reverse,
R.map(magnifyOnePrediction),
R.join("")
);
const detectFaces = async () => {
const face = await modelForFaceDetection.estimateFaces(video, false);
if (face.length > 0) {
// save face to test_face_extract folder
let [x1, y1] = face[0].topLeft;
let [x2, y2] = face[0].bottomRight;
let width = x2 - x1;
let height = y2 - y1;
// Casts coordinates to ints
x1 = parseInt(x1);
y1 = parseInt(y1);
width = parseInt(width);
height = parseInt(height);
/*---------------------------------------------------------------------------*/
/* Set buffer */
// // Chrome
// ctxBuffer.reset();
//
// // Firefox
// ctxBuffer.rect(0, 0, canvas.width, canvas.height);
// All platforms
ctxBuffer.beginPath();
ctxBuffer.fillStyle = "rgba(0, 0, 0, 0)";
ctxBuffer.fillRect(0, 0, canvas.width, canvas.height);
ctxBuffer.stroke();
ctxBuffer.drawImage(video, 0, 0, canvas.width, canvas.height);
/*---------------------------------------------------------------------------*/
// Draw rectangle on buffer
ctxBuffer.lineWidth = "2";
ctxBuffer.strokeStyle = "red";
ctxBuffer.rect(x1, y1, width, height);
ctxBuffer.stroke();
//Swap buffers
ctx.drawImage(canvasBuffer, 0, 0, canvas.width, canvas.height);
ctxFace.drawImage(
canvas,
x1,
y1,
width,
height,
0,
0,
canvasFace.width,
canvasFace.height
);
let imageData = ctxFace.getImageData(
0,
0,
canvasFace.width,
canvasFace.height
); // w then h (screen axis)
frameIter++;
if (frameIter >= 10) {
// Check tensor memory leak start
tf.engine().startScope();
tf.tidy(() => {
//// Conversion to tensor4D and resize
let tfImage = tf.browser.fromPixels(imageData, 3).expandDims(0);
let prediction = Array.from(
modelForEmotionRecognition.predict(tfImage).dataSync()
);
currentEmotion = getBestEmotion(prediction);
results.innerHTML = magnifyResults(emotions)(prediction);
tfImage.dispose();
// tfResizedImage.dispose();
});
// Check tensor memory leak stop
tf.engine().endScope();
frameIter = 0;
}
} else {
// No swap buffers, copy video directly
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
}
};
navigator.mediaDevices.enumerateDevices().then(gotDevices);
change_camera.addEventListener("click", (event) => {
if (typeof currentStream !== "undefined") {
stopMediaTracks(currentStream);
}
const videoConstraints = {};
if (select.value === "") {
videoConstraints.facingMode = "environment";
} else {
videoConstraints.deviceId = { exact: select.value };
}
const constraints = {
video: videoConstraints,
audio: false,
};
navigator.mediaDevices
.getUserMedia(constraints)
.then((stream) => {
currentStream = stream;
video.srcObject = stream;
return navigator.mediaDevices.enumerateDevices();
})
.then(gotDevices)
.catch((error) => {
console.error(error);
});
});
setupCamera();
video.addEventListener("loadeddata", async () => {
setInterval(detectFaces, 100); //in ms
});