-
-
Notifications
You must be signed in to change notification settings - Fork 427
/
detector.js
1104 lines (949 loc) · 33.1 KB
/
detector.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
// result should be similar to previou
// improve freka descriptors computation
import * as tf from '@tensorflow/tfjs';
import { FREAKPOINTS } from './freak.js';
import './kernels/webgl/index.js';
const PYRAMID_MIN_SIZE = 8;
const PYRAMID_MAX_OCTAVE = 5;
const LAPLACIAN_THRESHOLD = 3.0;
const LAPLACIAN_SQR_THRESHOLD = LAPLACIAN_THRESHOLD * LAPLACIAN_THRESHOLD;
const EDGE_THRESHOLD = 4.0;
const EDGE_HESSIAN_THRESHOLD = ((EDGE_THRESHOLD + 1) * (EDGE_THRESHOLD + 1) / EDGE_THRESHOLD);
const NUM_BUCKETS_PER_DIMENSION = 10;
const MAX_FEATURES_PER_BUCKET = 5;
const NUM_BUCKETS = NUM_BUCKETS_PER_DIMENSION * NUM_BUCKETS_PER_DIMENSION;
// total max feature points = NUM_BUCKETS * MAX_FEATURES_PER_BUCKET
const ORIENTATION_NUM_BINS = 36;
const ORIENTATION_SMOOTHING_ITERATIONS = 5;
const ORIENTATION_GAUSSIAN_EXPANSION_FACTOR = 3.0;
const ORIENTATION_REGION_EXPANSION_FACTOR = 1.5;
const FREAK_EXPANSION_FACTOR = 7.0;
const FREAK_CONPARISON_COUNT = (FREAKPOINTS.length - 1) * (FREAKPOINTS.length) / 2; // 666
class Detector {
constructor(width, height, debugMode = false) {
this.debugMode = debugMode;
this.width = width;
this.height = height;
let numOctaves = 0;
while (width >= PYRAMID_MIN_SIZE && height >= PYRAMID_MIN_SIZE) {
width /= 2;
height /= 2;
numOctaves++;
if (numOctaves === PYRAMID_MAX_OCTAVE) break;
}
this.numOctaves = numOctaves;
this.tensorCaches = {};
this.kernelCaches = {};
}
// used in compiler
detectImageData(imageData) {
const arr = new Uint8ClampedArray(4 * imageData.length);
for (let i = 0; i < imageData.length; i++) {
arr[4 * i] = imageData[i];
arr[4 * i + 1] = imageData[i];
arr[4 * i + 2] = imageData[i];
arr[4 * i + 3] = 255;
}
const img = new ImageData(arr, this.width, this.height);
return this.detect(img);
}
/**
*
* @param {tf.Tensor<tf.Rank>} inputImageT
* @returns
*/
detect(inputImageT) {
let debugExtra = null;
// Build gaussian pyramid images, two images per octave
/** @type {Array<Array<tf.Tensor<tf.Rank>>} */
const pyramidImagesT = [];
//console.log("Detector::Building pyramid Images...");
for (let i = 0; i < this.numOctaves; i++) {
let image1T;
let image2T;
if (i === 0) {
image1T = this._applyFilter(inputImageT);
} else {
image1T = this._downsampleBilinear(pyramidImagesT[i - 1][pyramidImagesT[i - 1].length - 1]);
}
image2T = this._applyFilter(image1T);
pyramidImagesT.push([image1T, image2T]);
}
//console.log("Detector::Building dog images...");
// Build difference-of-gaussian (dog) pyramid
/** @type {tf.Tensor<tf.Rank>[]} */
const dogPyramidImagesT = [];
for (let i = 0; i < this.numOctaves; i++) {
let dogImageT = this._differenceImageBinomial(pyramidImagesT[i][0], pyramidImagesT[i][1]);
dogPyramidImagesT.push(dogImageT);
}
// find local maximum/minimum
/** @type {tf.Tensor<tf.Rank>[]} */
const extremasResultsT = [];
for (let i = 1; i < this.numOctaves - 1; i++) {
const extremasResultT = this._buildExtremas(dogPyramidImagesT[i - 1], dogPyramidImagesT[i], dogPyramidImagesT[i + 1]);
extremasResultsT.push(extremasResultT);
}
// divide the input into N by N buckets, and for each bucket,
// collect the top 5 most significant extrema across extremas in all scale level
// result would be NUM_BUCKETS x NUM_FEATURES_PER_BUCKET extremas
const prunedExtremasList = this._applyPrune(extremasResultsT);
const prunedExtremasT = this._computeLocalization(prunedExtremasList, dogPyramidImagesT);
// compute the orientation angle for each pruned extremas
const extremaHistogramsT = this._computeOrientationHistograms(prunedExtremasT, pyramidImagesT);
const smoothedHistogramsT = this._smoothHistograms(extremaHistogramsT);
const extremaAnglesT = this._computeExtremaAngles(smoothedHistogramsT);
// to compute freak descriptors, we first find the pixel value of 37 freak points for each extrema
const extremaFreaksT = this._computeExtremaFreak(pyramidImagesT, prunedExtremasT, extremaAnglesT);
// compute the binary descriptors
const freakDescriptorsT = this._computeFreakDescriptors(extremaFreaksT);
const prunedExtremasArr = prunedExtremasT.arraySync();
const extremaAnglesArr = extremaAnglesT.arraySync();
const freakDescriptorsArr = freakDescriptorsT.arraySync();
if (this.debugMode) {
debugExtra = {
pyramidImages: pyramidImagesT.map((ts) => ts.map((t) => t.arraySync())),
dogPyramidImages: dogPyramidImagesT.map((t) => t ? t.arraySync() : null),
extremasResults: extremasResultsT.map((t) => t.arraySync()),
extremaAngles: extremaAnglesT.arraySync(),
prunedExtremas: prunedExtremasList,
localizedExtremas: prunedExtremasT.arraySync(),
}
}
pyramidImagesT.forEach((ts) => ts.forEach((t) => t.dispose()));
dogPyramidImagesT.forEach((t) => t && t.dispose());
extremasResultsT.forEach((t) => t.dispose());
prunedExtremasT.dispose();
extremaHistogramsT.dispose();
smoothedHistogramsT.dispose();
extremaAnglesT.dispose();
extremaFreaksT.dispose();
freakDescriptorsT.dispose();
const featurePoints = [];
for (let i = 0; i < prunedExtremasArr.length; i++) {
if (prunedExtremasArr[i][0] == 0) continue;
const descriptors = [];
for (let m = 0; m < freakDescriptorsArr[i].length; m += 4) {
const v1 = freakDescriptorsArr[i][m];
const v2 = freakDescriptorsArr[i][m + 1];
const v3 = freakDescriptorsArr[i][m + 2];
const v4 = freakDescriptorsArr[i][m + 3];
let combined = v1 * 16777216 + v2 * 65536 + v3 * 256 + v4;
//if (m === freakDescriptorsArr[i].length-4) { // last one, legacy reason
// combined /= 32;
//}
descriptors.push(combined);
}
const octave = prunedExtremasArr[i][1];
const y = prunedExtremasArr[i][2];
const x = prunedExtremasArr[i][3];
const originalX = x * Math.pow(2, octave) + Math.pow(2, (octave - 1)) - 0.5;
const originalY = y * Math.pow(2, octave) + Math.pow(2, (octave - 1)) - 0.5;
const scale = Math.pow(2, octave);
featurePoints.push({
maxima: prunedExtremasArr[i][0] > 0,
x: originalX,
y: originalY,
scale: scale,
angle: extremaAnglesArr[i],
descriptors: descriptors
});
}
//console.log("feature points", featurePoints);
//console.table(tf.memory());
return { featurePoints, debugExtra };
}
_computeFreakDescriptors(extremaFreaks) {
if (!this.tensorCaches.computeFreakDescriptors) {
const in1Arr = [];
const in2Arr = [];
for (let k1 = 0; k1 < extremaFreaks.shape[1]; k1++) {
for (let k2 = k1 + 1; k2 < extremaFreaks.shape[1]; k2++) {
in1Arr.push(k1);
in2Arr.push(k2);
}
}
const in1 = tf.tensor(in1Arr, [in1Arr.length]).cast('int32');
const in2 = tf.tensor(in2Arr, [in2Arr.length]).cast('int32');
this.tensorCaches.computeFreakDescriptors = {
positionT: tf.keep(tf.stack([in1, in2], 1))
}
}
const { positionT } = this.tensorCaches.computeFreakDescriptors;
// encode 8 bits into one number
// trying to encode 16 bits give wrong result in iOS. may integer precision issue
const descriptorCount = Math.ceil(FREAK_CONPARISON_COUNT / 8);
/*
if (!this.kernelCaches.computeFreakDescriptors) {
const kernel = {
variableNames: ['freak', 'p'],
outputShape: [extremaFreaks.shape[0], descriptorCount],
userCode: `
void main() {
ivec2 coords = getOutputCoords();
int featureIndex = coords[0];
int descIndex = coords[1] * 8;
int sum = 0;
for (int i = 0; i < 8; i++) {
if (descIndex + i >= ${FREAK_CONPARISON_COUNT}) {
continue;
}
int p1 = int(getP(descIndex + i, 0));
int p2 = int(getP(descIndex + i, 1));
float v1 = getFreak(featureIndex, p1);
float v2 = getFreak(featureIndex, p2);
if (v1 < v2 + 0.01) {
sum += int(pow(2.0, float(7 - i)));
}
}
setOutput(float(sum));
}
`
}
this.kernelCaches.computeFreakDescriptors = [kernel];
}
*/
return tf.tidy(() => {
//const [program] = this.kernelCaches.computeFreakDescriptors;
//return this._runWebGLProgram(program, [extremaFreaks, positionT], 'int32');
return tf.engine().runKernel('ComputeFreakDescriptors', { extremaFreaks, positionT });
});
}
_computeExtremaFreak(pyramidImagesT, prunedExtremas, prunedExtremasAngles) {
if (!this.tensorCaches._computeExtremaFreak) {
tf.tidy(() => {
const freakPoints = tf.tensor(FREAKPOINTS);
this.tensorCaches._computeExtremaFreak = {
freakPointsT: tf.keep(freakPoints),
};
});
}
const { freakPointsT } = this.tensorCaches._computeExtremaFreak;
const gaussianImagesT = [];
for (let i = 1; i < pyramidImagesT.length; i++) {
//gaussianImagesT.push(pyramidImagesT[i][0]);
gaussianImagesT.push(pyramidImagesT[i][1]); // better
}
/* if (!this.kernelCaches._computeExtremaFreak) {
const imageVariableNames = [];
for (let i = 1; i < pyramidImagesT.length; i++) {
imageVariableNames.push('image' + i);
}
let pixelsSubCodes = `float getPixel(int octave, int y, int x) {`;
for (let i = 1; i < pyramidImagesT.length; i++) {
pixelsSubCodes += `
if (octave == ${i}) {
return getImage${i}(y, x);
}
`
}
pixelsSubCodes += `}`;
const kernel = {
variableNames: [...imageVariableNames, 'extrema', 'angles', 'freakPoints'],
outputShape: [prunedExtremas.shape[0], FREAKPOINTS.length],
userCode: `
${pixelsSubCodes}
void main() {
ivec2 coords = getOutputCoords();
int featureIndex = coords[0];
int freakIndex = coords[1];
float freakSigma = getFreakPoints(freakIndex, 0);
float freakX = getFreakPoints(freakIndex, 1);
float freakY = getFreakPoints(freakIndex, 2);
int octave = int(getExtrema(featureIndex, 1));
float inputY = getExtrema(featureIndex, 2);
float inputX = getExtrema(featureIndex, 3);
float inputAngle = getAngles(featureIndex);
float cos = ${FREAK_EXPANSION_FACTOR}. * cos(inputAngle);
float sin = ${FREAK_EXPANSION_FACTOR}. * sin(inputAngle);
float yp = inputY + freakX * sin + freakY * cos;
float xp = inputX + freakX * cos + freakY * -sin;
int x0 = int(floor(xp));
int x1 = x0 + 1;
int y0 = int(floor(yp));
int y1 = y0 + 1;
float f1 = getPixel(octave, y0, x0);
float f2 = getPixel(octave, y0, x1);
float f3 = getPixel(octave, y1, x0);
float f4 = getPixel(octave, y1, x1);
float x1f = float(x1);
float y1f = float(y1);
float x0f = float(x0);
float y0f = float(y0);
// ratio for interpolation between four neighbouring points
float value = (x1f - xp) * (y1f - yp) * f1
+ (xp - x0f) * (y1f - yp) * f2
+ (x1f - xp) * (yp - y0f) * f3
+ (xp - x0f) * (yp - y0f) * f4;
setOutput(value);
}
`
}
this.kernelCaches._computeExtremaFreak = [kernel];
} */
return tf.tidy(() => {
/* const [program] = this.kernelCaches._computeExtremaFreak;
const result = this._compileAndRun(program, [...gaussianImagesT, prunedExtremas, prunedExtremasAngles, freakPointsT]);
return result; */
return tf.engine().runKernel('ComputeExtremaFreak', { gaussianImagesT, prunedExtremas, prunedExtremasAngles, freakPointsT, pyramidImagesLength: pyramidImagesT.length });
});
}
/**
*
* @param {tf.Tensor<tf.Rank>} histograms
* @returns
*/
_computeExtremaAngles(histograms) {
/* if (!this.kernelCaches.computeExtremaAngles) {
const kernel = {
variableNames: ['histogram'],
outputShape: [histograms.shape[0]],
userCode: `
void main() {
int featureIndex = getOutputCoords();
int maxIndex = 0;
for (int i = 1; i < ${ORIENTATION_NUM_BINS}; i++) {
if (getHistogram(featureIndex, i) > getHistogram(featureIndex, maxIndex)) {
maxIndex = i;
}
}
int prev = imod(maxIndex - 1 + ${ORIENTATION_NUM_BINS}, ${ORIENTATION_NUM_BINS});
int next = imod(maxIndex + 1, ${ORIENTATION_NUM_BINS});
**
* Fit a quatratic to 3 points. The system of equations is:
*
* y0 = A*x0^2 + B*x0 + C
* y1 = A*x1^2 + B*x1 + C
* y2 = A*x2^2 + B*x2 + C
*
* This system of equations is solved for A,B,C.
*
float p10 = float(maxIndex - 1);
float p11 = getHistogram(featureIndex, prev);
float p20 = float(maxIndex);
float p21 = getHistogram(featureIndex, maxIndex);
float p30 = float(maxIndex + 1);
float p31 = getHistogram(featureIndex, next);
float d1 = (p30-p20)*(p30-p10);
float d2 = (p10-p20)*(p30-p10);
float d3 = p10-p20;
// If any of the denominators are zero then, just use maxIndex.
float fbin = float(maxIndex);
if ( abs(d1) > 0.00001 && abs(d2) > 0.00001 && abs(d3) > 0.00001) {
float a = p10*p10;
float b = p20*p20;
// Solve for the coefficients A,B,C
float A = ((p31-p21)/d1)-((p11-p21)/d2);
float B = ((p11-p21)+(A*(b-a)))/d3;
float C = p11-(A*a)-(B*p10);
fbin = -B / (2. * A);
}
float an = 2.0 *${Math.PI} * (fbin + 0.5) / ${ORIENTATION_NUM_BINS}. - ${Math.PI};
setOutput(an);
}
`
}
this.kernelCaches.computeExtremaAngles = kernel;
} */
return tf.tidy(() => {
/* const program = this.kernelCaches.computeExtremaAngles;
return this._compileAndRun(program, [histograms]); */
return tf.engine().runKernel("ComputeExtremaAngles", { histograms });
});
}
// TODO: maybe can try just using average momentum, instead of histogram method. histogram might be overcomplicated
/**
*
* @param {tf.Tensor<tf.Rank>} prunedExtremasT
* @param {tf.Tensor<tf.Rank>[]} pyramidImagesT
* @returns
*/
_computeOrientationHistograms(prunedExtremasT, pyramidImagesT) {
const oneOver2PI = 0.159154943091895;
const gaussianImagesT = [];
for (let i = 1; i < pyramidImagesT.length; i++) {
gaussianImagesT.push(pyramidImagesT[i][1]);
}
if (!this.tensorCaches.orientationHistograms) {
tf.tidy(() => {
const gwScale = -1.0 / (2 * ORIENTATION_GAUSSIAN_EXPANSION_FACTOR * ORIENTATION_GAUSSIAN_EXPANSION_FACTOR);
const radius = ORIENTATION_GAUSSIAN_EXPANSION_FACTOR * ORIENTATION_REGION_EXPANSION_FACTOR;
const radiusCeil = Math.ceil(radius);
const radialProperties = [];
for (let y = -radiusCeil; y <= radiusCeil; y++) {
for (let x = -radiusCeil; x <= radiusCeil; x++) {
const distanceSquare = x * x + y * y;
// may just assign w = 1 will do, this could be over complicated.
if (distanceSquare <= radius * radius) {
const _x = distanceSquare * gwScale;
// fast expontenial approx
let w = (720 + _x * (720 + _x * (360 + _x * (120 + _x * (30 + _x * (6 + _x)))))) * 0.0013888888;
radialProperties.push([y, x, w]);
}
}
}
this.tensorCaches.orientationHistograms = {
radialPropertiesT: tf.keep(tf.tensor(radialProperties, [radialProperties.length, 3])),
}
});
}
const { radialPropertiesT } = this.tensorCaches.orientationHistograms;
/* if (!this.kernelCaches.computeOrientationHistograms) {
const imageVariableNames = [];
for (let i = 1; i < pyramidImagesT.length; i++) {
imageVariableNames.push('image' + i);
}
let kernel1SubCodes = `float getPixel(int octave, int y, int x) {`;
for (let i = 1; i < pyramidImagesT.length; i++) {
kernel1SubCodes += `
if (octave == ${i}) {
return getImage${i}(y, x);
}
`
}
kernel1SubCodes += `}`;
const kernel1 = {
variableNames: [...imageVariableNames, 'extrema', 'radial'],
outputShape: [prunedExtremasT.shape[0], radialPropertiesT.shape[0], 2], // last dimension: [fbin, magnitude]
userCode: `
${kernel1SubCodes}
void main() {
ivec3 coords = getOutputCoords();
int featureIndex = coords[0];
int radialIndex = coords[1];
int propertyIndex = coords[2];
int radialY = int(getRadial(radialIndex, 0));
int radialX = int(getRadial(radialIndex, 1));
float radialW = getRadial(radialIndex, 2);
int octave = int(getExtrema(featureIndex, 1));
int y = int(getExtrema(featureIndex, 2));
int x = int(getExtrema(featureIndex, 3));
int xp = x + radialX;
int yp = y + radialY;
float dy = getPixel(octave, yp+1, xp) - getPixel(octave, yp-1, xp);
float dx = getPixel(octave, yp, xp+1) - getPixel(octave, yp, xp-1);
if (propertyIndex == 0) {
// be careful that atan(0, 0) gives 1.57 instead of 0 (different from js), but doesn't matter here, coz magnitude is 0
float angle = atan(dy, dx) + ${Math.PI};
float fbin = angle * ${ORIENTATION_NUM_BINS}. * ${oneOver2PI};
setOutput(fbin);
return;
}
if (propertyIndex == 1) {
float mag = sqrt(dx * dx + dy * dy);
float magnitude = radialW * mag;
setOutput(magnitude);
return;
}
}
`
}
const kernel2 = {
variableNames: ['fbinMag'],
outputShape: [prunedExtremasT.shape[0], ORIENTATION_NUM_BINS],
userCode: `
void main() {
ivec2 coords = getOutputCoords();
int featureIndex = coords[0];
int binIndex = coords[1];
float sum = 0.;
for (int i = 0; i < ${radialPropertiesT.shape[0]}; i++) {
float fbin = getFbinMag(featureIndex, i, 0);
int bin = int(floor(fbin - 0.5));
int b1 = imod(bin + ${ORIENTATION_NUM_BINS}, ${ORIENTATION_NUM_BINS});
int b2 = imod(bin + 1 + ${ORIENTATION_NUM_BINS}, ${ORIENTATION_NUM_BINS});
if (b1 == binIndex || b2 == binIndex) {
float magnitude = getFbinMag(featureIndex, i, 1);
float w2 = fbin - float(bin) - 0.5;
float w1 = w2 * -1. + 1.;
if (b1 == binIndex) {
sum += w1 * magnitude;
}
if (b2 == binIndex) {
sum += w2 * magnitude;
}
}
}
setOutput(sum);
}
`
}
this.kernelCaches.computeOrientationHistograms = [kernel1, kernel2];
} */
return tf.tidy(() => {
/* const [program1, program2] = this.kernelCaches.computeOrientationHistograms;
const result1 = this._compileAndRun(program1, [...gaussianImagesT, prunedExtremasT, radialPropertiesT]);
const result2 = this._compileAndRun(program2, [result1]);
return result2;*/
return tf.engine().runKernel('ComputeOrientationHistograms', { gaussianImagesT, prunedExtremasT, radialPropertiesT, pyramidImagesLength: pyramidImagesT.length });
});
}
// The histogram is smoothed with a Gaussian, with sigma = 1
_smoothHistograms(histograms) {
/* if (!this.kernelCaches.smoothHistograms) {
const kernel = {
variableNames: ['histogram'],
outputShape: [histograms.shape[0], ORIENTATION_NUM_BINS],
userCode: `
void main() {
ivec2 coords = getOutputCoords();
int featureIndex = coords[0];
int binIndex = coords[1];
int prevBin = imod(binIndex - 1 + ${ORIENTATION_NUM_BINS}, ${ORIENTATION_NUM_BINS});
int nextBin = imod(binIndex + 1, ${ORIENTATION_NUM_BINS});
float result = 0.274068619061197 * getHistogram(featureIndex, prevBin) + 0.451862761877606 * getHistogram(featureIndex, binIndex) + 0.274068619061197 * getHistogram(featureIndex, nextBin);
setOutput(result);
}
`
}
this.kernelCaches.smoothHistograms = kernel;
} */
return tf.tidy(() => {
return tf.engine().runKernel("SmoothHistograms", { histograms });//
/* const program = this.kernelCaches.smoothHistograms;
for (let i = 0; i < ORIENTATION_SMOOTHING_ITERATIONS; i++) {
histograms = this._compileAndRun(program, [histograms]);
}
return histograms; */
});
}
/**
*
* @param {number[][]} prunedExtremasList
* @param {tf.Tensor<tf.Rank>[]} dogPyramidImagesT
* @returns
*/
_computeLocalization(prunedExtremasList, dogPyramidImagesT) {
/* if (!this.kernelCaches.computeLocalization) {
const dogVariableNames = [];
let dogSubCodes = `float getPixel(int octave, int y, int x) {`;
for (let i = 1; i < dogPyramidImagesT.length; i++) { // extrema starts from second octave
dogVariableNames.push('image' + i);
dogSubCodes += `
if (octave == ${i}) {
return getImage${i}(y, x);
}
`;
}
dogSubCodes += `}`;
const kernel = {
variableNames: [...dogVariableNames, 'extrema'],
outputShape: [prunedExtremasList.length, 3, 3], // 3x3 pixels around the extrema
userCode: `
${dogSubCodes}
void main() {
ivec3 coords = getOutputCoords();
int featureIndex = coords[0];
float score = getExtrema(featureIndex, 0);
if (score == 0.0) {
return;
}
int dy = coords[1]-1;
int dx = coords[2]-1;
int octave = int(getExtrema(featureIndex, 1));
int y = int(getExtrema(featureIndex, 2));
int x = int(getExtrema(featureIndex, 3));
setOutput(getPixel(octave, y+dy, x+dx));
}
`
}
this.kernelCaches.computeLocalization = [kernel];
} */
return tf.tidy(() => {
//const program = this.kernelCaches.computeLocalization[0];
//const prunedExtremasT = tf.tensor(prunedExtremasList, [prunedExtremasList.length, prunedExtremasList[0].length], 'int32');
const pixelsT = tf.engine().runKernel('ComputeLocalization', { prunedExtremasList, dogPyramidImagesT });//this._compileAndRun(program, [...dogPyramidImagesT.slice(1), prunedExtremasT]);
const pixels = pixelsT.arraySync();
const result = [];
for (let i = 0; i < pixels.length; i++) {
result.push([]);
for (let j = 0; j < pixels[i].length; j++) {
result[i].push([]);
}
}
const localizedExtremas = [];
for (let i = 0; i < prunedExtremasList.length; i++) {
localizedExtremas[i] = [
prunedExtremasList[i][0],
prunedExtremasList[i][1],
prunedExtremasList[i][2],
prunedExtremasList[i][3],
];
}
for (let i = 0; i < localizedExtremas.length; i++) {
if (localizedExtremas[i][0] === 0) {
continue;
}
const pixel = pixels[i];
const dx = 0.5 * (pixel[1][2] - pixel[1][0]);
const dy = 0.5 * (pixel[2][1] - pixel[0][1]);
const dxx = pixel[1][2] + pixel[1][0] - 2 * pixel[1][1];
const dyy = pixel[2][1] + pixel[0][1] - 2 * pixel[1][1];
const dxy = 0.25 * (pixel[0][0] + pixel[2][2] - pixel[0][2] - pixel[2][0]);
const det = dxx * dyy - dxy * dxy;
const ux = (dyy * -dx + -dxy * -dy) / det;
const uy = (-dxy * -dx + dxx * -dy) / det;
const newY = localizedExtremas[i][2] + uy;
const newX = localizedExtremas[i][3] + ux;
if (Math.abs(det) < 0.0001) {
continue;
}
localizedExtremas[i][2] = newY;
localizedExtremas[i][3] = newX;
}
return tf.tensor(localizedExtremas, [localizedExtremas.length, localizedExtremas[0].length], 'float32');
});
}
// faster to do it in CPU
// if we do in gpu, we probably need to use tf.topk(), which seems to be run in CPU anyway (no gpu operation for that)
// TODO: research adapative maximum supression method
/**
*
* @param {tf.Tensor<tf.Rank>[]} extremasResultsT
* @returns
*/
_applyPrune(extremasResultsT) {
const nBuckets = NUM_BUCKETS_PER_DIMENSION * NUM_BUCKETS_PER_DIMENSION;
const nFeatures = MAX_FEATURES_PER_BUCKET;
/*
if (!this.kernelCaches.applyPrune) {
const reductionKernels = [];
// to reduce to amount of data that need to sync back to CPU by 4 times, we apply this trick:
// the fact that there is not possible to have consecutive maximum/minimum, we can safe combine 4 pixels into 1
for (let k = 0; k < extremasResultsT.length; k++) {
const extremaHeight = extremasResultsT[k].shape[0];
const extremaWidth = extremasResultsT[k].shape[1];
const kernel = {
variableNames: ['extrema'],
outputShape: [Math.floor(extremaHeight/2), Math.floor(extremaWidth/2)],
userCode: `
void main() {
ivec2 coords = getOutputCoords();
int y = coords[0] * 2;
int x = coords[1] * 2;
float location = 0.0;
float values = getExtrema(y, x);
if (getExtrema(y+1, x) != 0.0) {
location = 1.0;
values = getExtrema(y+1, x);
}
else if (getExtrema(y, x+1) != 0.0) {
location = 2.0;
values = getExtrema(y, x+1);
}
else if (getExtrema(y+1, x+1) != 0.0) {
location = 3.0;
values = getExtrema(y+1, x+1);
}
if (values < 0.0) {
setOutput(location * -1000.0 + values);
} else {
setOutput(location * 1000.0 + values);
}
}
`
}
reductionKernels.push(kernel);
}
this.kernelCaches.applyPrune = {reductionKernels};
}
*/
// combine results into a tensor of:
// nBuckets x nFeatures x [score, octave, y, x]
const curAbsScores = [];
/** @type {number[][][]} */
const result = [];
for (let i = 0; i < nBuckets; i++) {
result.push([]);
curAbsScores.push([]);
for (let j = 0; j < nFeatures; j++) {
result[i].push([0, 0, 0, 0]);
curAbsScores[i].push(0);
}
}
tf.tidy(() => {
//const {reductionKernels} = this.kernelCaches.applyPrune;
for (let k = 0; k < extremasResultsT.length; k++) {
//const program = reductionKernels[k];
//const reducedT = this._compileAndRun(program, [extremasResultsT[k]]);
const reducedT = tf.engine().runKernel('ExtremaReduction', { extremasResultT: extremasResultsT[k] });
const octave = k + 1; // extrema starts from second octave
const reduced = reducedT.arraySync();
const height = reducedT.shape[0];
const width = reducedT.shape[1];
const bucketWidth = width * 2 / NUM_BUCKETS_PER_DIMENSION;
const bucketHeight = height * 2 / NUM_BUCKETS_PER_DIMENSION;
for (let j = 0; j < height; j++) {
for (let i = 0; i < width; i++) {
const encoded = reduced[j][i];
if (encoded == 0) continue;
const score = encoded % 1000;
const loc = Math.floor(Math.abs(encoded) / 1000);
const x = i * 2 + (loc === 2 || loc === 3 ? 1 : 0);
const y = j * 2 + (loc === 1 || loc === 3 ? 1 : 0);
const bucketX = Math.floor(x / bucketWidth);
const bucketY = Math.floor(y / bucketHeight);
const bucket = bucketY * NUM_BUCKETS_PER_DIMENSION + bucketX;
const absScore = Math.abs(score);
let tIndex = nFeatures;
while (tIndex >= 1 && absScore > curAbsScores[bucket][tIndex - 1]) {
tIndex -= 1;
}
if (tIndex < nFeatures) {
for (let t = nFeatures - 1; t >= tIndex + 1; t--) {
curAbsScores[bucket][t] = curAbsScores[bucket][t - 1];
result[bucket][t][0] = result[bucket][t - 1][0];
result[bucket][t][1] = result[bucket][t - 1][1];
result[bucket][t][2] = result[bucket][t - 1][2];
result[bucket][t][3] = result[bucket][t - 1][3];
}
curAbsScores[bucket][tIndex] = absScore;
result[bucket][tIndex][0] = score;
result[bucket][tIndex][1] = octave;
result[bucket][tIndex][2] = y;
result[bucket][tIndex][3] = x;
}
}//for j<height
}//for i<width
}
});
// combine all buckets into a single list
const list = [];
for (let i = 0; i < nBuckets; i++) {
for (let j = 0; j < nFeatures; j++) {
list.push(result[i][j]);
}
}
return list;
}
_buildExtremas(image0, image1, image2) {
/* const imageHeight = image1.shape[0];
const imageWidth = image1.shape[1];
const kernelKey = 'w' + imageWidth;
if (!this.kernelCaches.buildExtremas) {
this.kernelCaches.buildExtremas = {};
}
if (!this.kernelCaches.buildExtremas[kernelKey]) {
const kernel = {
variableNames: ['image0', 'image1', 'image2'],
outputShape: [imageHeight, imageWidth],
userCode: `
void main() {
ivec2 coords = getOutputCoords();
int y = coords[0];
int x = coords[1];
float value = getImage1(y, x);
// Step 1: find local maxima/minima
if (value * value < ${LAPLACIAN_SQR_THRESHOLD}.) {
setOutput(0.);
return;
}
if (y < ${FREAK_EXPANSION_FACTOR} || y > ${imageHeight - 1 - FREAK_EXPANSION_FACTOR}) {
setOutput(0.);
return;
}
if (x < ${FREAK_EXPANSION_FACTOR} || x > ${imageWidth - 1 - FREAK_EXPANSION_FACTOR}) {
setOutput(0.);
return;
}
bool isMax = true;
bool isMin = true;
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
float value0 = getImage0(y+dy, x+dx);
float value1 = getImage1(y+dy, x+dx);
float value2 = getImage2(y+dy, x+dx);
if (value < value0 || value < value1 || value < value2) {
isMax = false;
}
if (value > value0 || value > value1 || value > value2) {
isMin = false;
}
}
}
if (!isMax && !isMin) {
setOutput(0.);
return;
}
// compute edge score and reject based on threshold
float dxx = getImage1(y, x+1) + getImage1(y, x-1) - 2. * getImage1(y, x);
float dyy = getImage1(y+1, x) + getImage1(y-1, x) - 2. * getImage1(y, x);
float dxy = 0.25 * (getImage1(y-1,x-1) + getImage1(y+1,x+1) - getImage1(y-1,x+1) - getImage1(y+1,x-1));
float det = (dxx * dyy) - (dxy * dxy);
if (abs(det) < 0.0001) { // determinant undefined. no solution
setOutput(0.);
return;
}
float edgeScore = (dxx + dyy) * (dxx + dyy) / det;
if (abs(edgeScore) >= ${EDGE_HESSIAN_THRESHOLD} ) {
setOutput(0.);
return;
}
setOutput(getImage1(y,x));
}
`
};
this.kernelCaches.buildExtremas[kernelKey] = kernel;
} */
return tf.tidy(() => {
return tf.engine().runKernel('BuildExtremas', { image0, image1, image2 });
/* const program = this.kernelCaches.buildExtremas[kernelKey];
image0 = this._downsampleBilinear(image0);
image2 = this._upsampleBilinear(image2, image1); */
//this._compileAndRun(program, [image0, image1, image2]);
//return this._runWebGLProgram(program, [image0, image1, image2], 'float32');
});
}
/**
*
* @param {tf.Tensor<tf.Rank>} image1
* @param {tf.Tensor<tf.Rank>} image2
* @returns
*/
_differenceImageBinomial(image1, image2) {
return tf.tidy(() => {
return image1.sub(image2);
});
}
// 4th order binomail filter [1,4,6,4,1] X [1,4,6,4,1]
_applyFilter(image) {
/* const imageHeight = image.shape[0];
const imageWidth = image.shape[1];
const kernelKey = 'w' + imageWidth;
if (!this.kernelCaches.applyFilter) {
this.kernelCaches.applyFilter = {};
}
if (!this.kernelCaches.applyFilter[kernelKey]) {
const kernel1 = {
variableNames: ['p'],
outputShape: [imageHeight, imageWidth],
userCode: `
void main() {
ivec2 coords = getOutputCoords();
float sum = getP(coords[0], coords[1]-2);
sum += getP(coords[0], coords[1]-1) * 4.;
sum += getP(coords[0], coords[1]) * 6.;
sum += getP(coords[0], coords[1]+1) * 4.;
sum += getP(coords[0], coords[1]+2);
setOutput(sum);
}
`
};
const kernel2 = {
variableNames: ['p'],
outputShape: [imageHeight, imageWidth],
userCode: `
void main() {
ivec2 coords = getOutputCoords();
float sum = getP(coords[0]-2, coords[1]);
sum += getP(coords[0]-1, coords[1]) * 4.;
sum += getP(coords[0], coords[1]) * 6.;
sum += getP(coords[0]+1, coords[1]) * 4.;
sum += getP(coords[0]+2, coords[1]);
sum /= 256.;
setOutput(sum);
}
`
};
this.kernelCaches.applyFilter[kernelKey] = [kernel1, kernel2];
}
*/
return tf.tidy(() => {
/* const [program1, program2] = this.kernelCaches.applyFilter[kernelKey];
const result1 = this._compileAndRun(program1, [image]);
const result2 = this._compileAndRun(program2, [result1]);
return result2; */
return tf.engine().runKernel('BinomialFilter', { image });
});
}
/* _upsampleBilinear(image, targetImage) {
const imageHeight = image.shape[0];