-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgestures.js
431 lines (333 loc) · 10.8 KB
/
gestures.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//@ts-check
/**
* Exists to provide a reference/abstraction to the ml5.js Gesture Recognition system
*/
class Gestures {
static handpose; //holds the ml5.handpose detector
static video; //holds the video feed
static predictions; //gets updated with a list of predictions
static handDetected;//whether a hand is detected or not
static classifier; //holds the neural network that identifies handpose data
static status; //state of the gesture identifier
static showVideoFeed = false;
static annotations;
static palmBase;
static thumbBase;
static indexFingerBase;
static middleFingerBase;
static ringFingerBase;
static pinkyBase;
//static mirrorHandpose = false;
static initialize(){//these variables are further refreshed in the loop below
Gestures.handpose = handpose;
Gestures.video = video;
Gestures.predictions = predictions;
Gestures.handDetected = handDetected;
Gestures.classifier = classifier;
Gestures.status = status;
init(); //defer to below
}
static update(){
upd(); //defer to below
}
/*
static mirrorVideo(){
Gestures.mirrorHandpose = !Gestures.mirrorHandpose;
//const options = {
//flipHorizontal: Gestures.mirrorHandpose
//}
//@ts-ignore
//handpose = ml5.handpose(video, options, modelReady);
//handpose.options.flipHorizontal = true;
}
*/
}
var handpose;
var video;
var predictions = [];
var classifier;
var status = "loading";
var handDetected = false;
function init() {
textSize(24);
video = createCapture(VIDEO);
video.size(width, height);
const optionsHandpose = {
flipHorizontal: true,
detectionConfidence: 0.7
}
// @ts-ignore
handpose = ml5.handpose(video, optionsHandpose, modelReady);
// This sets up an event that fills the global variable "predictions"
// with an array every time new hand poses are detected
handpose.on("predict", (results) => {
// do something with the results
if(results.length!=0){
handDetected=true;
predictions = results;
} else {
handDetected=false;
}
});
//hide by default
video.hide();
let options = {
task: "classification",
//debug: true,
};
// @ts-ignore
classifier = ml5.neuralNetwork(options); //finally initialize the neural network
}
function modelReady() {
console.log("Model ready!");
beginLoadData();
}
function beginLoadData(){
//this will error out if the file doesn't exist but that's fine
loadedData = loadJSON("saved.json", loaded);
}
function loaded(){
for(var i in loadedData)
data.push(loadedData [i]);
console.log("Loaded data");
trainData();
}
function trainData(){
for (let item of data) {
let inputs = item.positions;
let outputs = [ item.label ];
classifier.addData(inputs, outputs);
}
classifier.normalizeData();
classifier.train({ epochs: 200 }, finishedTraining);
}
function upd() {
background(0);
Gestures.showVideoFeed = showVideoCheckbox.checked();
//handDetected = false;//will be set to true by gotResults() if so
//update references to landmarks
if(predictions!=null&&predictions.length!=0){
Gestures.annotations = predictions[0].annotations;
Gestures.palmBase = Gestures.annotations.palmBase[0];
Gestures.thumbBase = Gestures.annotations.thumb[0];
Gestures.indexFingerBase = Gestures.annotations.indexFinger[0];
Gestures.middleFingerBase = Gestures.annotations.middleFinger[0];
Gestures.ringFingerBase = Gestures.annotations.ringFinger[0];
Gestures.pinkyBase = Gestures.annotations.pinky[0];
}
//console.log(deltaTime + "ms; FPS:"+(1000/deltaTime).toFixed(1)); //DEBUG show fps
drawAndUpdateKeypoints();//draw the landmarks
/*if(status != "ready"){
push();
stroke('#00FF12');
fill('#00FF12');
statusText("Not yet ready to detect...");
pop();
} else*/ if(predictions.length>0 && status=="ready"){
let prediction = predictions[0];
classifier.classify(predictionToData(prediction, "FOOBAR").positions, gotResults);
} /*else {
push();
stroke('#00FF12');
fill('#00FF12');
statusText("Waiting to detect a hand...");
pop();
}
*/
//refresh static variables
Gestures.handpose = handpose;
Gestures.video = video;
Gestures.predictions = predictions;
Gestures.classifier = classifier;
Gestures.status = status;
Gestures.handDetected = handDetected;
}
let drawPoints = false;
// draw ellipses over the detected keypoints and update static variables (for debug purposes)
function drawAndUpdateKeypoints() {
if(!drawPoints) return;
if(predictions.length > 0) {
const prediction = predictions[0];
//draw each landmark
for (let i = 0; i < prediction.landmarks.length; i += 1) {
const keypoint = prediction.landmarks[i];
fill(0, 255, 0);
noStroke();
ellipse(keypoint[0], keypoint[1], 10, 10);
}
push();
stroke(color(255,255,255));
let annotations = predictions[0].annotations;
//console.log(annotations);
//draw lines between aech annotation landmarks
for(let i = 0; i < annotations.thumb.length; i++){
let landmark = annotations.thumb[i];
if(i!=annotations.thumb.length-1){
let nextLandmark = annotations.thumb[i+1];
line(landmark[0], landmark[1], nextLandmark[0], nextLandmark[1]);
}
}
for(let i = 0; i < annotations.indexFinger.length; i++){
let landmark = annotations.indexFinger[i];
if(i!=annotations.indexFinger.length-1){
let nextLandmark = annotations.indexFinger[i+1];
line(landmark[0], landmark[1], nextLandmark[0], nextLandmark[1]);
}
}
for(let i = 0; i < annotations.middleFinger.length; i++){
let landmark = annotations.middleFinger[i];
if(i!=annotations.middleFinger.length-1){
let nextLandmark = annotations.middleFinger[i+1];
line(landmark[0], landmark[1], nextLandmark[0], nextLandmark[1]);
}
}
for(let i = 0; i < annotations.ringFinger.length; i++){
let landmark = annotations.ringFinger[i];
if(i!=annotations.ringFinger.length-1){
let nextLandmark = annotations.ringFinger[i+1];
line(landmark[0], landmark[1], nextLandmark[0], nextLandmark[1]);
}
}
for(let i = 0; i < annotations.pinky.length; i++){
let landmark = annotations.pinky[i];
if(i!=annotations.pinky.length-1){
let nextLandmark = annotations.pinky[i+1];
line(landmark[0], landmark[1], nextLandmark[0], nextLandmark[1]);
}
}
let palmBase = annotations.palmBase[0];
let thumbBase = annotations.thumb[0];
let indexFingerBase = annotations.indexFinger[0];
let middleFingerBase = annotations.middleFinger[0];
let ringFingerBase = annotations.ringFinger[0];
let pinkyBase = annotations.pinky[0];
//connect palm base to pinky base and thumb base
line(palmBase[0], palmBase[1], thumbBase[0], thumbBase[1]);
line(palmBase[0], palmBase[1], pinkyBase[0], pinkyBase[1]);
line(pinkyBase[0], pinkyBase[1], ringFingerBase[0], ringFingerBase[1]);
line(ringFingerBase[0], ringFingerBase[1], middleFingerBase[0], middleFingerBase[1]);
line(middleFingerBase[0], middleFingerBase[1], indexFingerBase[0], indexFingerBase[1]);
line(indexFingerBase[0], indexFingerBase[1], thumbBase[0], thumbBase[1]);
let indexFingerTip = annotations.indexFinger[3];
let connection = createVector(indexFingerTip[0]-indexFingerBase[0], indexFingerTip[1]-indexFingerBase[1]);
}
}
let data = [];
let loadedData;
//for training data; not used in gameplay
function keyPressed(){
if (key=='x'){
if(data.length==0){
console.log("nothing to save!");
} else {
console.log("saved to JSON");
saveJSON(data, "saved.json");
}
return;
} else if (key=='l'){
beginLoadData()
return;
} else if (key=='t'){
if(data.length==0){
console.log("nothing to train!");
return;
}
trainData()
return;
}
if(predictions.length <= 0){
console.log("No predictions!");
return;
}
let prediction = predictions[0];
if(key=='c'){
console.log(prediction);
} else if (key=='b'){
console.log("Classified as block");
data.push(predictionToData(prediction, "block"));
} else if (key=='s'){
console.log("Classified as shoot");
data.push(predictionToData(prediction, "shoot"));
} else if (key=='o'){
console.log("Classified as ok");
data.push(predictionToData(prediction, "ok"));
} else if (key=='y'){
console.log("Classified as peace");
data.push(predictionToData(prediction, "peace"));
}else if (key=='z'){
console.log("Deleted last prediction");
data.pop();
} else if (key=='p'){
if(status!="ready"){
console.log("Not ready to predict!");
} else {
classifier.classify(predictionToData(prediction, "FOOBAR").positions, gotResults);
}
}
}
function finishedTraining() {
console.log("Finished training");
status = "ready";
}
function gotResults(error, results) {
if(results==null) return;
if(results.length==0) return;
let prediction = results[0].label;
if(World.instance!=null)
World.instance.player.receiveGesture(prediction);
//console.log(JSON.stringify(results, null, 2));
return;//the below is for debugging
push();
stroke('#303831');
fill('#00FF12');
/*
if(prediction=="thumbsUp"){
statusText("Detected: thumbs UP");
} else if (prediction=="thumbsDown"){
statusText("Detected: thumbs DOWN");
}
*/
if(prediction=="thumbsUp"){
statusText("Detected: thumbs UP");
} else if (prediction=="thumbsDown"){
statusText("Detected: thumbs DOWN");
} else if (prediction=="shoot"){
statusText("Detected: shoot");
} else if (prediction=="block"){
statusText("Detected: block");
}
pop();
}
//const changeCooldown=500;
const changeCooldown=1000;
let lastTimeTextChanged=0;
let lastText;
function statusText(string){
//console.log(millis() - lastTimeTextChanged);
if(millis() - lastTimeTextChanged > changeCooldown){
text(string, 10, 30);
lastTimeTextChanged = millis();
//console.log("TEXT CHANGED");
lastText = string;
} else {
if(lastText!=null)
text(lastText, 10, 30);
}
}
//flattens the landmark positions into just one array
function predictionToData(prediction, _label){
let positions = [];
for(let i = 0; i < 21; i++){
//console.log(prediction.landmarks);
let landmark = prediction.landmarks[i];
for(let j = 0; j < 3; j++){
let pos = landmark[j];
positions.push(pos);
}
}
let newData = {
positions: positions,
label: _label
};
return newData;
}