-
Notifications
You must be signed in to change notification settings - Fork 1
/
mimic.js
222 lines (187 loc) · 7.61 KB
/
mimic.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
220
221
222
// Mimic Me!
// Fun game where you need to express emojis being displayed
// --- Affectiva setup ---
// The affdex SDK Needs to create video and canvas elements in the DOM
var divRoot = $("#camera")[0]; // div node where we want to add these elements
var width = 640, height = 480; // camera image size
var faceMode = affdex.FaceDetectorMode.LARGE_FACES; // face mode parameter
// Initialize an Affectiva CameraDetector object
var detector = new affdex.CameraDetector(divRoot, width, height, faceMode);
// Enable detection of all Expressions, Emotions and Emojis classifiers.
detector.detectAllEmotions();
detector.detectAllExpressions();
detector.detectAllEmojis();
detector.detectAllAppearance();
// --- Utility values and functions ---
// Unicode values for all emojis Affectiva can detect
var emojis = [ 128528, 128515, 128524, 128527, 128521, 128535, 128539, 128540, 128542, 128545, 128563, 128561 ];
var code;
// Update target emoji being displayed by supplying a unicode value
function setTargetEmoji() {
code = emojis[Math.floor(Math.random()*emojis.length)];
console.log(code);
$("#target").html("&#" + code + ";");
}
// Convert a special character to its unicode value (can be 1 or 2 units long)
function toUnicode(c) {
if(c.length == 1)
return c.charCodeAt(0);
return ((((c.charCodeAt(0) - 0xD800) * 0x400) + (c.charCodeAt(1) - 0xDC00) + 0x10000));
}
// Update score being displayed
function setScore(correct) {
$("#score").html("Score: " + correct + " / " + 10);
}
// Display log messages and tracking results
function log(node_name, msg) {
$(node_name).append("<span>" + msg + "</span><br />")
}
function gameStart(canvas, img, face) {
var resultEmojiCode = toUnicode(face.emojis.dominantEmoji);
if(resultEmojiCode == code ) {
setScore(10);
alert("Correct");
setTimeout(setTargetEmoji,3000);
}
else {
setScore(Math.abs((resultEmojiCode - code)/4));
}
}
// --- Callback functions ---
// Start button
function onStart() {
if (detector && !detector.isRunning) {
$("#logs").html(""); // clear out previous log
detector.start(); // start detector
}
log('#logs', "Start button pressed");
$("#stop").removeAttr("disabled");
$("#reset").removeAttr("disabled");
setTargetEmoji();
}
// Stop button
function onStop() {
log('#logs', "Stop button pressed");
if (detector && detector.isRunning) {
detector.removeEventListener();
detector.stop(); // stop detector
$("#target").html("?");
}
setScore(0);
};
// Reset button
function onReset() {
log('#logs', "Reset button pressed");
if (detector && detector.isRunning) {
detector.reset();
$("#target").html("?");
}
$('#results').html(""); // clear out results
$("#logs").html(""); // clear out previous log
// TODO(optional): You can restart the game as well
// <your code here>
setScore(0);
};
// Add a callback to notify when camera access is allowed
detector.addEventListener("onWebcamConnectSuccess", function() {
log('#logs', "Webcam access allowed");
});
// Add a callback to notify when camera access is denied
detector.addEventListener("onWebcamConnectFailure", function() {
log('#logs', "webcam denied");
console.log("Webcam access denied");
});
// Add a callback to notify when detector is stopped
detector.addEventListener("onStopSuccess", function() {
log('#logs', "The detector reports stopped");
$("#results").html("");
});
// Add a callback to notify when the detector is initialized and ready for running
detector.addEventListener("onInitializeSuccess", function() {
log('#logs', "The detector reports initialized");
//Display canvas instead of video feed because we want to draw the feature points on it
$("#face_video_canvas").css("display", "block");
$("#face_video").css("display", "none");
// TODO(optional): Call a function to initialize the game, if needed
// <your code here>
});
// Add a callback to receive the results from processing an image
// NOTE: The faces object contains a list of the faces detected in the image,
// probabilities for different expressions, emotions and appearance metrics
detector.addEventListener("onImageResultsSuccess", function(faces, image, timestamp) {
var canvas = $('#face_video_canvas')[0];
if (!canvas)
return;
// Report how many faces were found
$('#results').html("");
log('#results', "Timestamp: " + timestamp.toFixed(2));
log('#results', "Number of faces found: " + faces.length);
if (faces.length > 0) {
// Report desired metrics
log('#results', "Appearance: " + JSON.stringify(faces[0].appearance));
log('#results', "Emotions: " + JSON.stringify(faces[0].emotions, function(key, val) {
return val.toFixed ? Number(val.toFixed(0)) : val;
}));
log('#results', "Expressions: " + JSON.stringify(faces[0].expressions, function(key, val) {
return val.toFixed ? Number(val.toFixed(0)) : val;
}));
log('#results', "Emoji: " + faces[0].emojis.dominantEmoji);
// Call functions to draw feature points and dominant emoji (for the first face only)
drawFeaturePoints(canvas, image, faces[0]);
drawEmoji(canvas, image, faces[0]);
// TODO: Call your function to run the game (define it first!)
// <your code here>
gameStart(canvas, image, faces[0]);
}
});
// --- Custom functions ---
// Draw the detected facial feature points on the image
function drawFeaturePoints(canvas, img, face) {
// Obtain a 2D context object to draw on the canvas
var ctx = canvas.getContext('2d');
// TODO: Set the stroke and/or fill style you want for each feature point marker
// See: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D#Fill_and_stroke_styles
// <your code here>
ctx.fillStyle = '#ffffff';
ctx.strokeStyle = '#ffffff';
// Loop over each feature point in the face
for (var id in face.featurePoints) {
var featurePoint = face.featurePoints[id];
// TODO: Draw feature point, e.g. as a circle using ctx.arc()
// See: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/arc
// <your code here>
ctx.beginPath();
ctx.arc(featurePoint.x,featurePoint.y,2.5,0,2 * Math.PI);
ctx.stroke();
}
}
// Draw the dominant emoji on the image
function drawEmoji(canvas, img, face) {
// Obtain a 2D context object to draw on the canvas
var ctx = canvas.getContext('2d');
// TODO: Set the font and style you want for the emoji
// <your code here>
ctx.font = '48px serif';
// TODO: Draw it using ctx.strokeText() or fillText()
// See: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillText
// TIP: Pick a particular feature point as an anchor so that the emoji sticks to your face
// <your code here>
var x=0,y=0,c=0;
for(var i in face.featurePoints) {
var featurePoint = face.featurePoints[i];
x = Math.max(featurePoint.x);
y = Math.max(featurePoint.y);
}
ctx.fillText(face.emojis.dominantEmoji,x+30,y);
}
// TODO: Define any variables and functions to implement the Mimic Me! game mechanics
// NOTE:
// - Remember to call your update function from the "onImageResultsSuccess" event handler above
// - You can use setTargetEmoji() and setScore() functions to update the respective elements
// - You will have to pass in emojis as unicode values, e.g. setTargetEmoji(128578) for a simple smiley
// - Unicode values for all emojis recognized by Affectiva are provided above in the list 'emojis'
// - To check for a match, you can convert the dominant emoji to unicode using the toUnicode() function
// Optional:
// - Define an initialization/reset function, and call it from the "onInitializeSuccess" event handler above
// - Define a game reset function (same as init?), and call it from the onReset() function above
// <your code here>