-
Notifications
You must be signed in to change notification settings - Fork 15
/
gestrec.js
1276 lines (1145 loc) · 86.3 KB
/
gestrec.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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.gestrec = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
module.exports = {
Constants: require('./Constants'),
Gesture: require('./Gesture'),
GestureStore: require('./GestureStore'),
Instance: require('./Instance'),
InstanceLearner: require('./InstanceLearner'),
Learner: require('./Learner'),
OrientedBoundingBox: require('./OrientedBoundingBox'),
Point: require('./Point'),
Prediction: require('./Prediction'),
Rect: require('./Rect'),
Stroke: require('./Stroke'),
Utils: require('./Utils')
};
},{"./Constants":2,"./Gesture":3,"./GestureStore":4,"./Instance":5,"./InstanceLearner":6,"./Learner":7,"./OrientedBoundingBox":8,"./Point":9,"./Prediction":10,"./Rect":11,"./Stroke":12,"./Utils":13}],2:[function(require,module,exports){
/**
* Constants.
*/
module.exports = {
// ignore sequence information
SEQUENCE_INVARIANT: 1,
// when SEQUENCE_SENSITIVE is used, only single stroke gestures are currently allowed
SEQUENCE_SENSITIVE: 2,
// ORIENTATION_SENSITIVE and ORIENTATION_INVARIANT are only for SEQUENCE_SENSITIVE gestures
ORIENTATION_INVARIANT: 1,
// at most 2 directions can be recognized
ORIENTATION_SENSITIVE: 2,
// at most 4 directions can be recognized
ORIENTATION_SENSITIVE_4: 4,
// at most 8 directions can be recognized
ORIENTATION_SENSITIVE_8: 8,
SEQUENCE_SAMPLE_SIZE: 16,
PATCH_SAMPLE_SIZE: 16,
ORIENTATIONS: [
0,
(Math.PI / 4),
(Math.PI / 2),
(Math.PI * 3 / 4),
Math.PI,
-0,
(-Math.PI / 4),
(-Math.PI / 2),
(-Math.PI * 3 / 4),
-Math.PI
]
};
},{}],3:[function(require,module,exports){
var Rect = require('./Rect');
var Stroke = require('./Stroke');
/**
* A gesture is a hand-drawn shape on a touch screen. It can have one or multiple strokes.
* Each stroke is a sequence of timed points. A user-defined gesture can be recognized by
* a GestureLibrary.
*/
function Gesture(strokes) {
this.mBoundingBox = new Rect();
this.mGestureID = Gesture.GESTURE_ID_BASE + (++Gesture.GESTURE_COUNT);
this.mStrokes = [];
if (!strokes) return;
for (var i=0; i<strokes.length; ++i) {
this.addStroke(strokes[i]);
}
}
Gesture.GESTURE_ID_BASE = Date.now();
Gesture.GESTURE_COUNT = 0;
Gesture.prototype.clone = function() {
var gesture = new Gesture();
gesture.mBoundingBox.set(
this.mBoundingBox.left,
this.mBoundingBox.top,
this.mBoundingBox.right,
this.mBoundingBox.bottom
);
var count = this.mStrokes.length;
for (var i=0; i<count; ++i) {
var stroke = this.mStrokes[i];
gesture.mStrokes.push(stroke.clone());
}
return gesture;
};
/**
* @return all the strokes of the gesture
*/
Gesture.prototype.getStrokes = function() {
return this.mStrokes;
};
/**
* @return the number of strokes included by this gesture
*/
Gesture.prototype.getStrokesCount = function() {
return this.mStrokes.length;
};
/**
* Adds a stroke to the gesture.
*
* @param stroke
*/
Gesture.prototype.addStroke = function(stroke) {
this.mStrokes.push(stroke);
this.mBoundingBox.union(stroke.boundingBox);
};
/**
* Calculates the total length of the gesture. When there are multiple strokes in
* the gesture, this returns the sum of the lengths of all the strokes.
*
* @return the length of the gesture
*/
Gesture.prototype.getLength = function() {
var len = 0;
var strokes = this.mStrokes;
var count = strokes.length;
for (var i=0; i<count; ++i) {
len += strokes[i].length;
}
return len;
};
/**
* @return the bounding box of the gesture
*/
Gesture.prototype.getBoundingBox = function() {
return this.mBoundingBox;
};
/**
* Sets the id of the gesture.
*
* @param id
*/
Gesture.prototype.setID = function(id) {
this.mGestureID = id;
};
/**
* @return the id of the gesture
*/
Gesture.prototype.getID = function() {
return this.mGestureID;
};
// ---
Gesture.prototype.toJSON = function() {
var strokes = [];
var count = this.mStrokes.length;
for (var i=0; i<count; ++i) {
strokes.push(this.mStrokes[i].toJSON());
}
return strokes;
};
Gesture.fromJSON = function(json) {
var gesture = new Gesture();
for (var i=0; i<json.length; ++i) {
gesture.addStroke(Stroke.fromJSON(json[i]));
}
return gesture;
};
module.exports = Gesture;
},{"./Rect":11,"./Stroke":12}],4:[function(require,module,exports){
var Constants = require('./Constants');
var Gesture = require('./Gesture');
var Instance = require('./Instance');
var InstanceLearner = require('./InstanceLearner');
/**
* GestureStore maintains gesture examples and makes predictions on a new
* gesture.
*/
function GestureStore() {
this.mSequenceType = Constants.SEQUENCE_SENSITIVE;
this.mOrientationStyle = Constants.ORIENTATION_SENSITIVE_4;
this.mClassifier = new InstanceLearner();
this.mChanged = false;
this.mNamedGestures = {};
}
/**
* Specify how the gesture library will handle orientation.
* Use ORIENTATION_INVARIANT or ORIENTATION_SENSITIVE
*
* @param style
*/
GestureStore.prototype.setOrientationStyle = function(style) {
this.mOrientationStyle = style;
};
GestureStore.prototype.getOrientationStyle = function() {
return this.mOrientationStyle;
};
/**
* @param type SEQUENCE_INVARIANT or SEQUENCE_SENSITIVE
*/
GestureStore.prototype.setSequenceType = function(type) {
this.mSequenceType = type;
};
/**
* @return SEQUENCE_INVARIANT or SEQUENCE_SENSITIVE
*/
GestureStore.prototype.getSequenceType = function() {
return this.mSequenceType;
};
/**
* Get all the gesture entry names in the library
*
* @return a set of strings
*/
GestureStore.prototype.getGestureEntries = function() {
var names = [];
for (var name in this.mNamedGestures) {
names.push(name);
}
return names;
};
/**
* Recognize a gesture
*
* @param gesture the query
* @return a list of predictions of possible entries for a given gesture
*/
GestureStore.prototype.recognize = function(gesture) {
var instance = Instance.createInstance(
this.mSequenceType, this.mOrientationStyle, gesture, null);
return this.mClassifier.classify(
this.mSequenceType, this.mOrientationStyle, instance.vector);
};
/**
* Add a gesture for the entry
*
* @param entryName entry name
* @param gesture
*/
GestureStore.prototype.addGesture = function(entryName, gesture) {
if (entryName == null || entryName.length === 0) {
return;
}
gestures = this.mNamedGestures[entryName];
if (gestures == null) {
gestures = [];
this.mNamedGestures[entryName] = gestures;
}
gestures.push(gesture);
this.mClassifier.addInstance(Instance.createInstance(
this.mSequenceType, this.mOrientationStyle, gesture, entryName
));
this.mChanged = true;
};
/**
* Remove a gesture from the library. If there are no more gestures for the
* given entry, the gesture entry will be removed.
*
* @param entryName entry name
* @param gesture
*/
GestureStore.prototype.removeGesture = function(entryName, gesture) {
var gestures = this.mNamedGestures[entryName];
if (gestures == null) {
return;
}
var index = gestures.indexOf(gesture);
gestures.splice(index, 1);
// if there are no more samples, remove the entry automatically
if (gestures.length === 0) {
delete this.mNamedGestures[entryName];
}
this.mClassifier.removeInstance(gesture.getID());
this.mChanged = true;
};
/**
* Remove an entry of gestures
*
* @param entryName the entry name
*/
GestureStore.prototype.removeEntry = function(entryName) {
delete this.mNamedGestures[entryName];
this.mClassifier.removeInstances(entryName);
this.mChanged = true;
};
/**
* Get all the gestures of an entry
*
* @param entryName
* @return the list of gestures that is under this name
*/
GestureStore.prototype.getGestures = function(entryName) {
var gestures = this.mNamedGestures[entryName];
if (gestures != null) {
return gestures.slice();
} else {
return [];
}
};
GestureStore.prototype.hasChanged = function() {
return this.mChanged;
};
GestureStore.prototype.getLearner = function() {
return this.mClassifier;
};
// ---
GestureStore.prototype.toJSON = function() {
var o = {};
o.sequence = this.mSequenceType;
o.orientation = this.mOrientationStyle;
o.gestures = {};
for (var name in this.mNamedGestures) {
var gestures = this.mNamedGestures[name];
o.gestures[name] = gestures.map(function(g) { return g.toJSON(); });
}
return o;
};
GestureStore.fromJSON = function(json) {
var gs = new GestureStore();
gs.setSequenceType(json.sequence);
gs.setOrientationStyle(json.orientation);
for (var name in json.gestures) {
var gestures = json.gestures[name];
gestures.forEach(function(g) {
gs.addGesture(name, Gesture.fromJSON(g));
});
}
return gs;
};
module.exports = GestureStore;
},{"./Constants":2,"./Gesture":3,"./Instance":5,"./InstanceLearner":6}],5:[function(require,module,exports){
var Constants = require('./Constants');
var Utils = require('./Utils');
/**
* An instance represents a sample if the label is available or a query if the
* label is null.
*/
function Instance(id, sample, sampleName) {
this.id = id;
this.vector = sample;
this.label = sampleName;
}
Instance.prototype.normalize = function() {
var sample = this.vector;
var sum = 0;
var size = sample.length;
for (var i = 0; i < size; i++) {
sum += sample[i] * sample[i];
}
var magnitude = Math.sqrt(sum);
for (var i = 0; i < size; i++) {
sample[i] /= magnitude;
}
};
/**
* create a learning instance for a single stroke gesture
*
* @param gesture
* @param label
* @return the instance
*/
Instance.createInstance = function(sequenceType, orientationType, gesture, label) {
var pts;
var instance;
if (sequenceType === Constants.SEQUENCE_SENSITIVE) {
pts = Instance.temporalSampler(orientationType, gesture);
instance = new Instance(gesture.getID(), pts, label);
instance.normalize();
} else {
pts = Instance.spatialSampler(gesture);
instance = new Instance(gesture.getID(), pts, label);
}
return instance;
};
Instance.spatialSampler = function(gesture) {
return Utils.spatialSampling(gesture, Constants.PATCH_SAMPLE_SIZE, false);
};
Instance.temporalSampler = function(orientationType, gesture) {
var pts = Utils.temporalSampling(gesture.getStrokes()[0],
Constants.SEQUENCE_SAMPLE_SIZE);
var center = Utils.computeCentroid(pts);
var orientation = Math.atan2(pts[1] - center[1], pts[0] - center[0]);
var adjustment = -orientation;
if (orientationType != Constants.ORIENTATION_INVARIANT) {
var count = Constants.ORIENTATIONS.length;
for (var i = 0; i < count; i++) {
var delta = Constants.ORIENTATIONS[i] - orientation;
if (Math.abs(delta) < Math.abs(adjustment)) {
adjustment = delta;
}
}
}
Utils.translate(pts, -center[0], -center[1]);
Utils.rotate(pts, adjustment);
return pts;
};
module.exports = Instance;
},{"./Constants":2,"./Utils":13}],6:[function(require,module,exports){
var Prediction = require('./Prediction');
var Constants = require('./Constants');
var Learner = require('./Learner');
var Utils = require('./Utils');
/**
* An implementation of an instance-based learner
*/
function InstanceLearner() {
Learner.call(this);
}
InstanceLearner.prototype = new Learner();
InstanceLearner.compare = function(object1, object2) {
var score1 = object1.score;
var score2 = object2.score;
if (score1 > score2) {
return -1;
} else if (score1 < score2) {
return 1;
} else {
return 0;
}
};
InstanceLearner.prototype.classify = function(sequenceType, orientationType, vector) {
var predictions = [];
var instances = this.getInstances();
var count = instances.length;
var label2score = {};
for (var i=0; i<count; ++i) {
var sample = instances[i];
if (sample.vector.length != vector.length) {
continue;
}
var distance;
if (sequenceType == Constants.SEQUENCE_SENSITIVE) {
distance = Utils.minimumCosineDistance(sample.vector, vector, orientationType);
} else {
distance = Utils.squaredEuclideanDistance(sample.vector, vector);
}
var weight;
if (distance == 0) {
weight = Number.MAX_VALUE;
} else {
weight = 1 / distance;
}
var score = label2score[sample.label];
if (score == null || weight > score) {
label2score[sample.label] = weight;
}
}
for (var name in label2score) {
var score = label2score[name];
predictions.push(new Prediction(name, score));
}
return predictions.sort(InstanceLearner.compare);
};
module.exports = InstanceLearner;
},{"./Constants":2,"./Learner":7,"./Prediction":10,"./Utils":13}],7:[function(require,module,exports){
/**
* The abstract class of a gesture learner
*/
function Learner() {
this.mInstances = [];
}
/**
* Add an instance to the learner
*
* @param instance
*/
Learner.prototype.addInstance = function(instance) {
this.mInstances.push(instance);
};
/**
* Retrieve all the instances
*
* @return instances
*/
Learner.prototype.getInstances = function() {
return this.mInstances;
};
/**
* Remove an instance based on its id
*
* @param id
*/
Learner.prototype.removeInstance = function(id) {
instances = this.mInstances;
var count = instances.length;
for (var i = 0; i < count; i++) {
var instance = instances[i];
if (id === instance.id) {
instances.splice(i, 1);
return;
}
}
};
/**
* Remove all the instances of a category
*
* @param name the category name
*/
Learner.prototype.removeInstances = function(name) {
var toDelete = [];
var instances = this.mInstances;
var count = instances.length;
for (var i = 0; i < count; ++i) {
var instance = instances[i];
// the label can be null, as specified in Instance
if ((instance.label == null && name == null)
|| (instance.label != null && instance.label === name)) {
toDelete.push(i);
}
}
for (i=toDelete.length-1; i>=0; --i) {
instances.splice(toDelete[i], 1);
}
};
Learner.prototype.classify = function(sequenceType, orientationType, vector) {
};
module.exports = Learner;
},{}],8:[function(require,module,exports){
/**
* An oriented bounding box
*/
module.exports = function OrientedBoundingBox(angle, cx, cy, w, h) {
this.orientation = angle;
this.width = w;
this.height = h;
this.centerX = cx;
this.centerY = cy;
var ratio = w / h;
this.squareness = ratio > 1 ? (1/ratio) : ratio;
};
},{}],9:[function(require,module,exports){
/**
* A timed point of a gesture stroke. Multiple points form a stroke.
*/
module.exports = function Point(x, y, t) {
if (x instanceof Object) {
var o = x;
this.x = o.x;
this.y = o.y;
this.timestamp = o.t;
} else {
this.x = x;
this.y = y;
this.timestamp = t;
}
};
},{}],10:[function(require,module,exports){
function Prediction(label, predictionScore) {
this.name = label;
this.score = predictionScore;
}
Prediction.prototype.toString = function() {
return this.name;
};
module.exports = Prediction;
},{}],11:[function(require,module,exports){
/**
* Rectangle object.
*/
function Rect(l, t, r, b) {
this.set(l, t, r, b);
}
Rect.prototype.clone = function() {
return new Rect(this.left, this.top, this.right, this.bottom);
};
Rect.prototype.centerX = function() {
return (this.left + this.right) / 2;
};
Rect.prototype.centerY = function() {
return (this.top + this.bottom) / 2;
};
Rect.prototype.width = function() {
return this.right - this.left;
};
Rect.prototype.height = function() {
return this.bottom - this.top;
};
Rect.prototype.set = function(l, t, r, b) {
this.top = t;
this.left = l;
this.bottom = b;
this.right = r;
};
Rect.prototype.unionPoint = function(x, y) {
if (x < this.left) this.left = x;
if (x > this.right) this.right = x;
if (y < this.top) this.top = y;
if (y > this.bottom) this.bottom = y;
};
Rect.prototype.union = function(r) {
if (r.left < this.left) this.left = r.left;
if (r.right > this.right) this.right = r.right;
if (r.top < this.top) this.top = r.top;
if (r.bottom > this.bottom) this.bottom = r.bottom;
};
module.exports = Rect;
},{}],12:[function(require,module,exports){
var Rect = require('./Rect');
var Point = require('./Point');
/**
* A gesture stroke started on a touch down and ended on a touch up. A stroke
* consists of a sequence of timed points. One or multiple strokes form a gesture.
*/
function Stroke(points) {
if (points == null) return;
var count = points.length;
var tmpPoints = Array(count*2);
var times = Array(count);
var bx = null;
var len = 0;
var index = 0;
for (var i=0; i<count; ++i) {
var p = points[i];
tmpPoints[i*2] = p.x;
tmpPoints[i*2+1] = p.y;
times[index] = p.timestamp;
if (bx == null) {
bx = new Rect(p.x, p.y, p.x, p.y);
len = 0;
} else {
var dx = p.x - tmpPoints[(i - 1) * 2];
var dy = p.y - tmpPoints[(i -1) * 2 + 1];
len += Math.sqrt(dx*dx + dy*dy);
bx.unionPoint(p.x, p.y);
}
index++;
}
this.timestamps = times;
this.points = tmpPoints;
this.boundingBox = bx;
this.length = len;
}
Stroke.prototype.clone = function() {
var stroke = new Stroke();
stroke.boundingBox = this.boundingBox.clone();
stroke.length = this.length;
stroke.points = this.points.slice();
stroke.timestamps = this.timestamps.slice();
return stroke;
};
// ---
Stroke.prototype.toJSON = function() {
var points = [];
var count = this.points.length;
for (var i=0; i<count; i+=2) {
points.push({
x: this.points[i],
y: this.points[i+1],
t: this.timestamps[i>>1]
});
}
return points;
};
Stroke.fromJSON = function(json) {
var points = [];
for (var i=0; i<json.length; ++i) {
points.push(new Point(json[i]));
}
return new Stroke(points);
};
module.exports = Stroke;
},{"./Point":9,"./Rect":11}],13:[function(require,module,exports){
var OrientedBoundingBox = require('./OrientedBoundingBox');
/**
* Utility functions for gesture processing & analysis, including methods for:
* <ul>
* <li>feature extraction (e.g., samplers and those for calculating bounding
* boxes and gesture path lengths);
* <li>geometric transformation (e.g., translation, rotation and scaling);
* <li>gesture similarity comparison (e.g., calculating Euclidean or Cosine
* distances between two gestures).
* </ul>
*/
var Utils = {};
Utils.SCALING_THRESHOLD = 0.26;
Utils.NONUNIFORM_SCALE = Math.sqrt(2);
Utils.zeroes = function(n) {
var array = Array(n);
for (var i=0; i<n; ++i) array[i] = 0;
return array;
}
/**
* Samples the gesture spatially by rendering the gesture into a 2D
* grayscale bitmap. Scales the gesture to fit the size of the bitmap.
*
* @param gesture the gesture to be sampled
* @param bitmapSize the size of the bitmap
* @param keepAspectRatio if the scaling should keep the gesture's
* aspect ratio
*
* @return a bitmapSize x bitmapSize grayscale bitmap that is represented
* as a 1D array. The float at index i represents the grayscale
* value at pixel [i%bitmapSize, i/bitmapSize]
*/
Utils.spatialSampling = function(gesture, bitmapSize, keepAspectRatio) {
var targetPatchSize = bitmapSize - 1;
var sample = Utils.zeroes(bitmapSize * bitmapSize);
var rect = gesture.getBoundingBox();
var gestureWidth = rect.width();
var gestureHeight = rect.height();
var sx = targetPatchSize / gestureWidth;
var sy = targetPatchSize / gestureHeight;
var scale;
if (keepAspectRatio) {
scale = sx < sy ? sx : sy;
sx = scale;
sy = scale;
} else {
var aspectRatio = gestureWidth / gestureHeight;
if (aspectRatio > 1) {
aspectRation = 1 / aspectRatio;
}
if (aspectRatio < Utils.SCALING_THRESHOLD) {
scale = sx < sy ? sx : sy;
sx = scale;
sy = scale;
} else {
if (sx > sy) {
scale = sy * Utils.NONUNIFORM_SCALE;
if (scale < sx) { sx = scale; }
} else {
scale = sx * Utils.NONUNIFORM_SCALE;
if (scale < sy) { sy = scale; }
}
}
}
var preDx = -rect.centerX();
var preDy = -rect.centerY();
var postDx = targetPatchSize / 2;
var postDy = targetPatchSize / 2;
var strokes = gesture.getStrokes();
var count = strokes.length;
var size; // int
var xpos;
var ypos;
for (var index=0; index < count; index++) {
var stroke = strokes[index];
var strokepoints = stroke.points;
size = strokepoints.length;
var pts = Array(size);
for (var i=0; i < size; i += 2) {
pts[i] = (strokepoints[i] + preDx) * sx + postDx;
pts[i + 1] = (strokepoints[i + 1] + preDy) * sy + postDy;
}
var segmentEndX = -1;
var segmentEndY = -1;
for (var i=0; i < size; i += 2) {
var segmentStartX = pts[i] < 0 ? 0 : pts[i];
var segmentStartY = pts[i + 1] < 0 ? 0 : pts[i + 1];
if (segmentStartX > targetPatchSize) {
segmentStartX = targetPatchSize;
}
if (segmentStartY > targetPatchSize) {
segmentStartY = targetPatchSize;
}
Utils.plot(segmentStartX, segmentStartY, sample, bitmapSize);
if (segmentEndX != -1) {
// Evaluate horizontally
if (segmentEndX > segmentStartX) {
xpos = Math.ceil(segmentStartX);
var slope = (segmentEndY - segmentStartY) / (segmentEndX - segmentStartX);
while (xpos < segmentEndX) {
ypos = slope * (xpos - segmentStartX) + segmentStartY;
plot(xpos, ypos, sample, bitmapSize);
xpos++;
}
} else if (segmentEndX < segmentStartX) {
xpos = Math.ceil(segmentEndX);
var slope = (segmentEndY - segmentStartY) / (segmentEndX - segmentStartX);
while (xpos < segmentStartX) {
ypos = slope * (xpos - segmentStartX) + segmentStartY;
plot(xpos, ypos, sample, bitmapSize);
xpos++;
}
}
// Evaluate vertically
if (segmentEndY > segmentStartY) {
ypos = Math.ceil(segmentStartY);
var invertSlope = (segmentEndX - segmentStartX) / (segmentEndY - segmentStartY);
while (ypos < segmentEndY) {
xpos = invertSlope * (ypos - segmentStartY) + segmentStartX;
plot(xpos, ypos, sample, bitmapSize);
ypos++;
}
} else if (segmentEndY < segmentStartY) {
ypos = Math.ceil(segmentEndY);
var invertSlope = (segmentEndX - segmentStartX) / (segmentEndY - segmentStartY);
while (ypos < segmentStartY) {
xpos = invertSlope * (ypos - segmentStartY) + segmentStartX;
plot(xpos, ypos, sample, bitmapSize);
ypos++;
}
}
}
segmentEndX = segmentStartX;
segmentEndY = segmentStartY;
}
}
return sample;
};
Utils.plot = function(x, y, sample, sampleSize) {
x = x < 0 ? 0 : x;
y = y < 0 ? 0 : y;
var xFloor = Math.floor(x);
var xCeiling = Math.ceil(x);
var yFloor = Math.floor(y);
var yCeiling = Math.ceil(y);
// if it's an integer
if (x === xFloor && y === yFloor) {
var index = yCeiling * sampleSize + xCeiling;
if (sample[index] < 1) {
sample[index] = 1;
}
} else {
var xFloorSq = Math.pow(xFloor - x, 2);
var yFloorSq = Math.pow(yFloor - y, 2);
var xCeilingSq = Math.pow(xCeiling - x, 2);
var yCeilingSq = Math.pow(yCeiling - y, 2);
var topLeft = Math.sqrt(xFloorSq + yFloorSq);
var topRight = Math.sqrt(xCeilingSq + yFloorSq);
var btmLeft = Math.sqrt(xFloorSq + yCeilingSq);
var btmRight = Math.sqrt(xCeilingSq + yCeilingSq);
var sum = topLeft + topRight + btmLeft + btmRight;
var value = topLeft / sum;
var index = yFloor * sampleSize + xFloor;
if (value > sample[index]) {
sample[index] = value;
}
value = topRight / sum;
index = yFloor * sampleSize + xCeiling;
if (value > sample[index]) {
sample[index] = value;
}
value = btmLeft / sum;
index = yCeiling * sampleSize + xFloor;
if (value > sample[index]) {
sample[index] = value;
}
value = btmRight / sum;
index = yCeiling * sampleSize + xCeiling;
if (value > sample[index]) {
sample[index] = value;
}
}
};
/**
* Samples a stroke temporally into a given number of evenly-distributed
* points.
*
* @param stroke the gesture stroke to be sampled
* @param numPoints the number of points
* @return the sampled points in the form of [x1, y1, x2, y2, ..., xn, yn]
*/
Utils.temporalSampling = function(stroke, numPoints) {
var increment = stroke.length / (numPoints - 1);
var vectorLength = numPoints * 2;
var vector = Array(vectorLength);
var distanceSoFar = 0;
var pts = stroke.points;
var lstPointX = pts[0];
var lstPointY = pts[1];
var index = 0;
var currentPointX = Number.MIN_VALUE;
var currentPointY = Number.MIN_VALUE;
vector[index] = lstPointX;
index++;
vector[index] = lstPointY;
index++;
var i = 0;
var count = pts.length / 2;
while (i < count) {
if (currentPointX == Number.MIN_VALUE) {
i++;
if (i >= count) {
break;
}
currentPointX = pts[i * 2];
currentPointY = pts[i * 2 + 1];
}
var deltaX = currentPointX - lstPointX;
var deltaY = currentPointY - lstPointY;
var distance = Math.sqrt(deltaX*deltaX + deltaY*deltaY);
if (distanceSoFar + distance >= increment) {
var ratio = (increment - distanceSoFar) / distance;
var nx = lstPointX + ratio * deltaX;
var ny = lstPointY + ratio * deltaY;
vector[index] = nx;
index++;
vector[index] = ny;
index++;
lstPointX = nx;
lstPointY = ny;
distanceSoFar = 0;
} else {
lstPointX = currentPointX;
lstPointY = currentPointY;
currentPointX = Number.MIN_VALUE;
currentPointY = Number.MIN_VALUE;
distanceSoFar += distance;
}
}
for (i = index; i < vectorLength; i += 2) {
vector[i] = lstPointX;
vector[i + 1] = lstPointY;
}