-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.js
2373 lines (2371 loc) · 110 KB
/
main.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
/**
* Class that keeps track of image buffers
* By reusing previously used buffers the garbage collection is almost completely removed
* which removes any spikes during processing
*/
var BufferManager = /** @class */ (function () {
function BufferManager() {
this.floatBuffers = {};
this.uint8Buffers = {};
}
BufferManager.prototype.getFloatBuffer = function (length) {
var availableBuffers = this.floatBuffers[length];
if (typeof availableBuffers === "undefined") {
availableBuffers = [];
this.floatBuffers[length] = availableBuffers;
}
if (availableBuffers.length > 0) {
return availableBuffers.pop();
}
else {
console.log("Creating new float32 buffer" + new Error().stack);
return new Float32Array(length);
}
};
BufferManager.prototype.releaseFloatBuffer = function (buffer) {
this.floatBuffers[buffer.length].push(buffer);
// console.log("Releasing buffer of length " + buffer.length + ", there are " + this.floatBuffers[buffer.length].length + " buffers available");
};
BufferManager.prototype.getUInt8Buffer = function (length) {
// console.log("Getting buffer of length " + length);
var availableBuffers = this.uint8Buffers[length];
if (typeof availableBuffers === "undefined") {
availableBuffers = [];
this.uint8Buffers[length] = availableBuffers;
}
if (availableBuffers.length > 0) {
// console.log("Reusing buffer");
return availableBuffers.pop();
}
else {
console.log("Creating new Uint8 buffer" + new Error().stack);
return new Uint8Array(length);
}
};
BufferManager.prototype.releaseUInt8Buffer = function (buffer) {
this.uint8Buffers[buffer.length].push(buffer);
// console.log("Releasing buffer of length " + buffer.length + ", there are " + this.uint8Buffers[buffer.length].length + " buffers available");
};
BufferManager.getInstance = function () {
if (BufferManager.instance == null)
BufferManager.instance = new BufferManager();
return BufferManager.instance;
};
BufferManager.instance = null;
return BufferManager;
}());
var GUI = /** @class */ (function () {
function GUI() {
}
GUI.main = function () {
// create the smaller and full canvases only once
GUI.smallCanvas = document.createElement("canvas");
GUI.fullCanvas = document.createElement("canvas");
GUI.lastFullCanvasImage = document.createElement("canvas");
var video = document.querySelector("#videoElement");
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;
if (navigator.getUserMedia) {
var constraints_1 = {
video: { facingMode: { exact: "environment" }, width: { exact: 1920 }, height: { exact: 1080 } },
audio: false
};
// get webcam feed if available
navigator.getUserMedia(constraints_1, function (stream) { return GUI.handleVideo(video, stream); }, function () {
// try without facing mode
constraints_1 = {
video: true,
audio: false
};
navigator.getUserMedia(constraints_1, function (stream) { return GUI.handleVideo(video, stream); }, function (err) {
alert("Unable to initialize video: " + JSON.stringify(err));
});
});
}
document.getElementById("toggleDebug").onclick = function (ev) {
GUI.debug = !GUI.debug;
document.getElementById("debugstuff").style.display = GUI.debug ? "block" : "none";
};
document.getElementById("videoContainer").onclick = function (ev) {
GUI.isPaused = !GUI.isPaused;
};
document.getElementById("output").onclick = function (ev) {
if (GUI.isWorkingOnOCR)
return;
if (GUI.lastExtractResult == null)
return;
GUI.isWorkingOnOCR = true;
var targetCanvas = document.createElement("canvas");
var warpResult = Algorithm.warpExtractedResultAndPrepareForOCR(GUI.lastFullCanvasImage, targetCanvas, GUI.lastExtractResult, GUI.warpSettings, GUI.debug);
//document.body.appendChild(targetCanvas);
var job = Tesseract.recognize(targetCanvas, {
lang: 'eng',
}).progress(function (message) {
try {
document.getElementById("barOCR").value = message.progress;
}
catch (e) {
}
}).catch(function (err) { return console.error(err); })
.then(function (result) { return document.getElementById("txtOutput").textContent = result.text; })
.finally(function (resultOrError) {
GUI.isWorkingOnOCR = false;
});
};
};
GUI.handleVideo = function (video, stream) {
// if found attach feed to video element
video.srcObject = stream;
window.setInterval(function () {
if (GUI.isWorkingOnOCR || GUI.isPaused)
return;
if (video.videoWidth != 0 && video.videoHeight != 0) {
// have the video overlay match the video input
document.getElementById("videoContainer").style.height = video.videoHeight;
document.getElementById("videoContainer").style.width = video.videoWidth;
if (document.getElementById("videoOverlay").width != video.videoWidth)
document.getElementById("videoOverlay").width = video.videoWidth;
if (document.getElementById("videoOverlay").height != video.videoHeight)
document.getElementById("videoOverlay").height = video.videoHeight;
// draw the video to the canvases
GUI.updateCanvases(video, GUI.extractSettings);
var targetCanvas = document.getElementById("output");
var extractResult = Algorithm.extractBiggestRectangularArea(GUI.extractSettings, GUI.smallCanvas, GUI.debug);
if (extractResult.success) {
// keep the result so it can be applied for OCR later
GUI.lastExtractResult = extractResult;
if (GUI.lastFullCanvasImage.width != GUI.fullCanvas.width ||
GUI.lastFullCanvasImage.height != GUI.fullCanvas.height) {
GUI.lastFullCanvasImage.width = GUI.fullCanvas.width;
GUI.lastFullCanvasImage.height = GUI.fullCanvas.height;
}
GUI.lastFullCanvasImage.getContext("2d").drawImage(GUI.fullCanvas, 0, 0, GUI.fullCanvas.width, GUI.fullCanvas.height);
GUI.drawExtractedResultOnOverlay(extractResult);
var warpResult = void 0;
if (document.getElementById("chkHighRes").checked) {
warpResult = Algorithm.warpExtractedResultAndPrepareForOCR(GUI.fullCanvas, targetCanvas, extractResult, GUI.warpSettings, GUI.debug);
}
else {
// warp the smaller canvas to the output. When the OCR process is started the cached lastFullCanvasImage will be used
// to warp & threshold for better quality
warpResult = Algorithm.warpExtractedResultAndPrepareForOCR(GUI.smallCanvas, targetCanvas, extractResult, GUI.warpSettings, GUI.debug);
}
document.getElementById("txt").innerHTML = extractResult.timing.concat(warpResult.timing).join("<br/>");
}
else
document.getElementById("txt").innerHTML = extractResult.timing.join("<br/>");
}
}, 10);
};
GUI.updateCanvases = function (video, settings) {
var w = video.videoWidth;
var h = video.videoHeight;
if (w > settings.contourSearchingWidth) {
w = settings.contourSearchingWidth;
h = Math.floor(video.videoHeight / video.videoWidth * settings.contourSearchingWidth);
}
if (GUI.smallCanvas.width != w || GUI.smallCanvas.height != h) {
GUI.smallCanvas.width = w;
GUI.smallCanvas.height = h;
}
var ctx = GUI.smallCanvas.getContext("2d");
ctx.drawImage(video, 0, 0, GUI.smallCanvas.width, GUI.smallCanvas.height);
var multiplier = 1;
if (GUI.fullCanvas.width != video.videoWidth * multiplier || GUI.fullCanvas.height != video.videoHeight * multiplier) {
GUI.fullCanvas.width = video.videoWidth * multiplier;
GUI.fullCanvas.height = video.videoHeight * multiplier;
}
var fullCtx = GUI.fullCanvas.getContext("2d");
fullCtx.drawImage(video, 0, 0, GUI.fullCanvas.width, GUI.fullCanvas.height);
};
GUI.drawExtractedResultOnOverlay = function (extractResult) {
var overlay = document.getElementById("videoOverlay");
var overlayCtx = overlay.getContext("2d");
overlayCtx.clearRect(0, 0, overlay.width, overlay.height);
overlayCtx.strokeStyle = "red";
overlayCtx.lineWidth = 2;
overlayCtx.beginPath();
overlayCtx.moveTo(extractResult.leftTop[0] * overlay.width, extractResult.leftTop[1] * overlay.height);
overlayCtx.lineTo(extractResult.rightTop[0] * overlay.width, extractResult.rightTop[1] * overlay.height);
overlayCtx.lineTo(extractResult.rightBottom[0] * overlay.width, extractResult.rightBottom[1] * overlay.height);
overlayCtx.lineTo(extractResult.leftBottom[0] * overlay.width, extractResult.leftBottom[1] * overlay.height);
overlayCtx.lineTo(extractResult.leftTop[0] * overlay.width, extractResult.leftTop[1] * overlay.height);
overlayCtx.stroke();
};
GUI.saveToCanvas = function (elementId, grayscale, width, height) {
var debugCanvas = document.getElementById(elementId);
debugCanvas.width = width;
debugCanvas.height = height;
var ctx = debugCanvas.getContext("2d");
var srcData = ctx.getImageData(0, 0, width, height);
var dataIdx = 0;
for (var idx = 0; idx < grayscale.length; idx++) {
srcData.data[dataIdx] = grayscale[idx];
srcData.data[dataIdx + 1] = grayscale[idx];
srcData.data[dataIdx + 2] = grayscale[idx];
srcData.data[dataIdx + 3] = 255;
dataIdx += 4;
}
ctx.putImageData(srcData, 0, 0);
};
GUI.drawHistogram = function (elementId, grayscale, width, height) {
var hist = new Array(256);
for (var i = 0; i < 256; i++)
hist[i] = 0;
var max = Number.MIN_VALUE;
for (var idx = 0; idx < grayscale.length; idx++) {
hist[grayscale[idx]]++;
if (max < hist[grayscale[idx]])
max = hist[grayscale[idx]];
}
var histCanvas = document.getElementById(elementId);
var ctx = histCanvas.getContext("2d");
ctx.fillStyle = "white";
ctx.fillRect(0, 0, 256, 256);
//ctx.translate(-0.5, -0.5);
ctx.fillStyle = "black";
for (var i = 0; i < 256; i++) {
var h = hist[i] / max * 256;
ctx.fillRect(i, 256 - h, 1, h);
}
};
GUI.isWorkingOnOCR = false;
GUI.isPaused = false;
GUI.debug = false;
GUI.lastExtractResult = null;
GUI.extractSettings = {
contourSearchingWidth: 320,
enhanceContrastFactor: 1.5,
cannyThresholdSigmaMultiplier: 1,
borderPadding: 5,
// the area of the contour / the area of the hull of the contour. The better the contour approximates
// a convex polygon the higher the ratio. A rectangle is convex so it should be pretty high
contourAreaToHullAreaMinimumRatio: 0.7,
// the minimum area the contour should be, percentage wise on the image (1/8*w * 1/8*h ==> 1/64)
contourMininumAreaPercentage: 1 / 64,
// to have a valid contour the start and end should be close together as a rectangle is closed
// this is the percentage of the max(width,height) that is allowed as distance between the start and end
// lower is more strict but could remove desired contours
contourStartAndEndPointsMaximumDistancePercentage: 0.1,
// the minimum angle there has to be between consecutive points of the contour
// this disqualifies any contours with very sharp jaggy edges
contourPointsMinimumAngleBetweenPoints: 80,
removeCannyClustersSmallerThan: 5,
removeCannyEdgesCloseToDiagonal: false,
};
GUI.warpSettings = {
nickThresholdWindowSize: 19,
nickThresholdK: -0.1
};
return GUI;
}());
var Algorithm;
(function (Algorithm) {
var ExtractResult = /** @class */ (function () {
function ExtractResult() {
this.leftTop = null;
this.rightTop = null;
this.leftBottom = null;
this.rightBottom = null;
this.success = false;
this.timing = [];
}
return ExtractResult;
}());
Algorithm.ExtractResult = ExtractResult;
var WarpAndPrepareResult = /** @class */ (function () {
function WarpAndPrepareResult() {
this.timing = [];
}
return WarpAndPrepareResult;
}());
Algorithm.WarpAndPrepareResult = WarpAndPrepareResult;
/**
* Searches for the biggest rectangular-like contour in the image and returns the 4 corners if found
*/
function extractBiggestRectangularArea(settings, canvas, debug) {
var ctx = canvas.getContext("2d");
var w = canvas.width;
var h = canvas.height;
var srcData = ctx.getImageData(0, 0, w, h);
var result = new ExtractResult();
//let grayscale = new Uint8Array(srcData.width *srcData.height);
var grayscale = BufferManager.getInstance().getUInt8Buffer(srcData.width * srcData.height);
result.timing.push(doTime("Grayscale", function () {
var dataIdx = 0;
for (var idx = 0; idx < grayscale.length; idx++) {
grayscale[idx] = (srcData.data[dataIdx] + srcData.data[dataIdx + 1] + srcData.data[dataIdx + 2]) / 3;
dataIdx += 4;
}
}, false));
//stretchHistogram(grayscale, srcData.width, srcData.height);
result.timing.push(doTime("Enhance contrast", function () {
ImageOps.enhanceContrast(grayscale, settings.enhanceContrastFactor);
}, false));
var gaussian;
result.timing.push(doTime("Gaussian blur", function () {
/* grayscale = applyKernel3x3([
1 / 16, 1 / 8, 1 / 16,
1 / 8, 1 / 4, 1 / 8,
1 / 16, 1 / 8, 1 / 16], grayscale, srcData.width, srcData.height);
grayscale = applyKernel3x3([
1 / 16, 1 / 8, 1 / 16,
1 / 8, 1 / 4, 1 / 8,
1 / 16, 1 / 8, 1 / 16], grayscale, srcData.width, srcData.height);
*/
var gauss = [0.06136, 0.24477, 0.38774, 0.24477, 0.06136];
gaussian = ConvolutionOps.applySeparableKernel5x5(gauss, gauss, grayscale, srcData.width, srcData.height);
BufferManager.getInstance().releaseUInt8Buffer(grayscale);
grayscale = gaussian;
// grayscale = applyKernel3x3([1/9, 1/9, 1/9, 1/9,1/9,1/9, 1/9, 1/9, 1/9], grayscale, srcData.width, srcData.height);
}, false));
var cannyLowerThreshold;
var cannyHigherThreshold;
result.timing.push(doTime("Median", function () {
var med = ImageOps.median(grayscale);
var sigma = settings.cannyThresholdSigmaMultiplier * 0.33;
cannyLowerThreshold = Math.max(0, (1 - sigma) * med);
cannyHigherThreshold = Math.min(255, (1 + sigma) * med);
}, false));
if (debug) {
GUI.saveToCanvas("preCanny", grayscale, srcData.width, srcData.height);
GUI.drawHistogram("histogram", grayscale, srcData.width, srcData.height);
}
result.timing.push(doTime("Canny", function () {
var canny = Canny.applyCanny(settings.borderPadding, grayscale, srcData.width, srcData.height, cannyLowerThreshold, cannyHigherThreshold, settings.removeCannyClustersSmallerThan, settings.removeCannyEdgesCloseToDiagonal);
BufferManager.getInstance().releaseUInt8Buffer(grayscale);
grayscale = canny;
}, false));
if (debug)
GUI.saveToCanvas("postCanny", grayscale, srcData.width, srcData.height);
result.timing.push(doTime("Remove border", function () {
removeBorder(settings.borderPadding, grayscale, srcData.width, srcData.height);
}, false));
result.timing.push(doTime("Dilate & erode", function () {
/*grayscale = dilate(grayscale, srcData.width, srcData.height);
grayscale = dilate(grayscale, srcData.width, srcData.height);
grayscale = dilate(grayscale, srcData.width, srcData.height);
grayscale = dilate(grayscale, srcData.width, srcData.height);
grayscale = erode(grayscale, srcData.width, srcData.height);
grayscale = erode(grayscale, srcData.width, srcData.height);
grayscale = erode(grayscale, srcData.width, srcData.height);
grayscale = erode(grayscale, srcData.width, srcData.height);*/
var dilated = MorphologicalOps.dilateFast(grayscale, srcData.width, srcData.height, 9, srcData.width, srcData.height); //MorphologicalOps.dilate4Fast(grayscale, srcData.width, srcData.height);
BufferManager.getInstance().releaseUInt8Buffer(grayscale);
grayscale = dilated;
var eroded = MorphologicalOps.erodeFast(grayscale, srcData.width, srcData.height, 9, srcData.width, srcData.height);
BufferManager.getInstance().releaseUInt8Buffer(grayscale);
grayscale = eroded;
}, false));
if (debug)
GUI.saveToCanvas("morph", grayscale, srcData.width, srcData.height);
var allContours;
result.timing.push(doTime("Trace contours", function () {
// start from the center of the image and spiral around clockwise to find contour
// starting points. That way the contours that are most relevant will be hit from the inside
// and because it tracks the visited pixels and directions the outside of the contour that merges with the noise
// of the environment won't be considered
allContours = ContourOps.traceContours(settings.borderPadding, grayscale, srcData.width, srcData.height);
}, false));
if (debug) {
GUI.saveToCanvas("contourResult", grayscale, srcData.width, srcData.height);
}
// release the buffer, not needed anymore
BufferManager.getInstance().releaseUInt8Buffer(grayscale);
grayscale = null;
var bestContour = null;
var bestContourHull = null;
var bestContourCorners = null;
result.timing.push(doTime("Find best contour", function () {
var width = srcData.width;
var height = srcData.height;
var result = findBestContour(allContours, width, height, settings);
bestContour = result.contour;
bestContourHull = result.hull;
bestContourCorners = result.corners;
}, false));
if (debug) {
var cIdx = 0;
var colors = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 0], [0, 255, 255], [255, 0, 255]];
var contourResult = document.getElementById("contourResult");
var ctx_1 = contourResult.getContext("2d");
for (var _i = 0, allContours_1 = allContours; _i < allContours_1.length; _i++) {
var contour = allContours_1[_i];
var c = colors[cIdx++ % colors.length];
ctx_1.strokeStyle = "rgb(" + c[0] + ", " + c[1] + ", " + c[2];
ctx_1.lineWidth = 1;
ctx_1.beginPath();
var x0 = contour[0] % srcData.width;
var y0 = Math.floor(contour[0] / srcData.width);
ctx_1.moveTo(x0, y0);
var oldx = x0;
var oldy = y0;
for (var i = 1; i < contour.length; i++) {
var x = contour[i] % srcData.width;
var y = Math.floor(contour[i] / srcData.width);
oldx = x;
oldy = y;
ctx_1.lineTo(x, y);
}
ctx_1.stroke();
}
}
if (bestContour != null) {
//console.warn(bestContour);
if (debug) {
var contourResult = document.getElementById("contourResult");
var ctx_2 = contourResult.getContext("2d");
var cIdx = 0;
var color = [255, 0, 0];
ctx_2.strokeStyle = "rgb(" + color[0] + ", " + color[1] + ", " + color[2];
ctx_2.lineWidth = 2;
ctx_2.beginPath();
var x0 = bestContour[0] % srcData.width;
var y0 = Math.floor(bestContour[0] / srcData.width);
ctx_2.moveTo(x0, y0);
var oldx = x0;
var oldy = y0;
for (var i = 1; i < bestContour.length; i++) {
var x = bestContour[i] % srcData.width;
var y = Math.floor(bestContour[i] / srcData.width);
oldx = x;
oldy = y;
ctx_2.lineTo(x, y);
}
ctx_2.stroke();
ctx_2.fillStyle = "rgb(" + color[0] + ", " + color[1] + ", " + color[2];
for (var i = 0; i < bestContourHull.length; i++) {
var x = bestContourHull[i] % srcData.width;
var y = Math.floor(bestContourHull[i] / srcData.width);
ctx_2.beginPath();
ctx_2.arc(x, y, 3, 0, Math.PI * 2, false);
ctx_2.fill();
}
// draw starting point
ctx_2.fillStyle = "gray";
ctx_2.beginPath();
ctx_2.arc(x0, y0, 5, 0, Math.PI * 2, false);
ctx_2.fill();
// draw end point
ctx_2.fillStyle = "#FFAA00";
ctx_2.beginPath();
ctx_2.arc(oldx, oldy, 3, 0, Math.PI * 2, false);
ctx_2.fill();
// draw the center of the polygon
var center_1 = ContourOps.centerOfPolygon(bestContour, srcData.width);
var centerX_1 = center_1 % srcData.width;
var centerY_1 = Math.floor(center_1 / srcData.width);
ctx_2.fillStyle = "#55AA55";
ctx_2.beginPath();
ctx_2.arc(centerX_1, centerY_1, 5, 0, Math.PI * 2, false);
ctx_2.fill();
// draw the corners that were found
for (var i = 0; i < bestContourCorners.length; i++) {
var x = bestContourCorners[i] % srcData.width;
var y = Math.floor(bestContourCorners[i] / srcData.width);
ctx_2.strokeStyle = "#55AA55";
ctx_2.beginPath();
ctx_2.lineWidth = 1;
ctx_2.moveTo(centerX_1, centerY_1);
ctx_2.lineTo(x, y);
ctx_2.stroke();
}
}
var center = ContourOps.centerOfPolygon(bestContour, srcData.width);
var centerX = center % srcData.width;
var centerY = Math.floor(center / srcData.width);
// classify the 4 corners into the separate quadrants
var leftTop = null;
var rightTop = null;
var leftBottom = null;
var rightBottom = null;
for (var i = 0; i < bestContourCorners.length; i++) {
var x = bestContourCorners[i] % srcData.width;
var y = Math.floor(bestContourCorners[i] / srcData.width);
if (x <= centerX && y <= centerY)
leftTop = [x / srcData.width, y / srcData.height];
else if (x > centerX && y <= centerY)
rightTop = [x / srcData.width, y / srcData.height];
else if (x <= centerX && y > centerY)
leftBottom = [x / srcData.width, y / srcData.height];
else
rightBottom = [x / srcData.width, y / srcData.height];
}
if (leftTop != null && rightTop != null && leftBottom != null && rightBottom != null) {
result.leftTop = leftTop;
result.leftBottom = leftBottom;
result.rightTop = rightTop;
result.rightBottom = rightBottom;
result.success = true;
}
}
return result;
}
Algorithm.extractBiggestRectangularArea = extractBiggestRectangularArea;
/**
* Removes the border of the image, setting it to black
*/
function removeBorder(padding, grayscale, width, height) {
var idx = 0;
for (var i = 0; i < padding * width; i++) {
grayscale[idx] = 0;
idx++;
}
for (var y = padding; y < height - padding; y++) {
for (var x = 0; x < padding; x++) {
grayscale[idx] = 0;
idx++;
}
idx += width - 2 * padding;
for (var x = 0; x < padding; x++) {
grayscale[idx] = 0;
idx++;
}
}
for (var i = 0; i < padding * width; i++) {
grayscale[idx] = 0;
idx++;
}
}
/**
* Try to find the biggest area contour but constrained to the settings, such as not too close to the border of the image,
* have a minimum area, must be somewhat closed, must be close to convex, has to have 4 corners, etc.
*/
function findBestContour(allContours, width, height, settings) {
var bestContour = null;
var bestContourHull = null;
var bestContourCorners = null;
var maxArea = Number.MIN_VALUE;
for (var _i = 0, allContours_2 = allContours; _i < allContours_2.length; _i++) {
var rawContour = allContours_2[_i];
var hull = ContourOps.convexHull(rawContour, width);
var area = Math.abs(ContourOps.polygonArea(rawContour, width));
var hullarea = Math.abs(ContourOps.polygonArea(hull, width));
var closeToBorderPointCount = 0;
for (var i = 0; i < rawContour.length; i++) {
var x = rawContour[i] % width;
var y = Math.floor(rawContour[i] / width);
if (x <= settings.borderPadding + 1 || x >= width - settings.borderPadding - 1 || y <= settings.borderPadding + 1 || y >= height - settings.borderPadding - 1)
closeToBorderPointCount++;
}
// todo put the close to border count in settings
if (closeToBorderPointCount < 100) { // make sure that nothing encroaches the border because then the contour is a significant chunk of full image, which is not what it usually is
if (area / hullarea > settings.contourAreaToHullAreaMinimumRatio) {
if (Math.abs(area) > width * height * settings.contourMininumAreaPercentage) {
var x0 = rawContour[0] % width;
var y0 = Math.floor(rawContour[0] / width);
var xlast = rawContour[rawContour.length - 1] % width;
var ylast = Math.floor(rawContour[rawContour.length - 1] / width);
var dist = Math.abs(x0 - xlast) + Math.abs(y0 - ylast);
if (dist < settings.contourStartAndEndPointsMaximumDistancePercentage * Math.max(width, height)) {
// check if angles between prevP - curP and curP - nextP are > 60°
var angles = ContourOps.innerAnglesOfPolygon(hull, width);
// and all angles are always >= 80°
if (angles.filter(function (a) { return a < settings.contourPointsMinimumAngleBetweenPoints || a > 360 - settings.contourPointsMinimumAngleBetweenPoints; }).length == 0) {
var cornerPoints = ContourOps.findCorners(rawContour, width);
if (cornerPoints.length == 4) { // 4 corners spaced far enough in angle from the center
if (area > maxArea) {
bestContour = rawContour;
bestContourHull = hull;
bestContourCorners = cornerPoints;
maxArea = area;
}
}
}
}
}
}
}
}
return { contour: bestContour, hull: bestContourHull, corners: bestContourCorners };
}
/**
* Warps the image to fix the perspective based on the found corners and then applies NICK thresholding
* to have better black/white images for OCR
*/
function warpExtractedResultAndPrepareForOCR(canvas, targetCanvas, extractResult, settings, debug) {
var fullCtx = canvas.getContext("2d");
var videoImageData = fullCtx.getImageData(0, 0, canvas.width, canvas.height);
var grayscale = BufferManager.getInstance().getUInt8Buffer(videoImageData.width * videoImageData.height);
var warpResult = new WarpAndPrepareResult();
warpResult.timing.push(doTime("Full grayscale", function () {
var dataIdx = 0;
for (var idx_1 = 0; idx_1 < grayscale.length; idx_1++) {
grayscale[idx_1] = (videoImageData.data[dataIdx] + videoImageData.data[dataIdx + 1] + videoImageData.data[dataIdx + 2]) / 3;
dataIdx += 4;
}
}, false));
var result;
warpResult.timing.push(doTime("Warp perspective", function () {
result = processPerspective(grayscale, videoImageData.width, videoImageData.height, extractResult.leftTop, extractResult.rightTop, extractResult.leftBottom, extractResult.rightBottom);
BufferManager.getInstance().releaseUInt8Buffer(grayscale);
//enhanceContrast(result.data, 2.5);
if (debug)
GUI.saveToCanvas("warpPerspectiveResult", result.data, result.width, result.height);
}, false));
var thresh;
warpResult.timing.push(doTime("NICK Binary Threshold", function () {
thresh = result.data;
ImageOps.binaryThresholdNICK(thresh, result.width, result.height, settings.nickThresholdWindowSize, settings.nickThresholdK, videoImageData.width, videoImageData.height);
}, false));
warpResult.timing.push(doTime("Erode", function () {
var erode = MorphologicalOps.erode1Fast(thresh, result.width, result.height, videoImageData.width, videoImageData.height);
BufferManager.getInstance().releaseUInt8Buffer(thresh);
thresh = erode;
}, false));
// copy it to the target canvas
targetCanvas.width = result.width;
targetCanvas.height = result.height;
var targetCtx = targetCanvas.getContext("2d");
var targetData = targetCtx.createImageData(result.width, result.height);
var targetArr = targetData.data;
var idx = 0;
for (var i = 0; i < thresh.length; i++) {
targetArr[idx] = thresh[i];
targetArr[idx + 1] = thresh[i];
targetArr[idx + 2] = thresh[i];
targetArr[idx + 3] = 255;
idx += 4;
}
BufferManager.getInstance().releaseUInt8Buffer(thresh);
targetCtx.putImageData(targetData, 0, 0);
return warpResult;
}
Algorithm.warpExtractedResultAndPrepareForOCR = warpExtractedResultAndPrepareForOCR;
/**
* Warps the perspective (similar to open cv's warp perspective)
* Each pixel in the target image gets looked up into the source image with the
* PerspectiveOps.project(i,j), but this is refactored to reduce the nr of operations
*/
function processPerspective(srcArray, srcWidth, srcHeight, leftTopCorner, rightTopCorner, leftBottomCorner, rightBottomCorner) {
// length of left edge / length of top edge gives the ratio
var v0x = leftBottomCorner[0] * srcWidth - leftTopCorner[0] * srcWidth;
var v0y = leftBottomCorner[1] * srcHeight - leftTopCorner[1] * srcHeight;
var v1x = rightTopCorner[0] * srcWidth - leftTopCorner[0] * srcWidth;
var v1y = rightTopCorner[1] * srcHeight - leftTopCorner[1] * srcHeight;
var leftEdgeLength = Math.sqrt(v0x * v0x + v0y * v0y);
var topEdgeLength = Math.sqrt(v1x * v1x + v1y * v1y);
// console.log("Top edge: " + topEdgeLength + " vs left " + leftEdgeLength);
var ratio = leftEdgeLength / topEdgeLength;
var targetHeight;
var targetWidth;
if (ratio < 1) {
// width is much larger than the height
targetWidth = srcWidth;
targetHeight = srcWidth * ratio;
}
else {
// height is much larger than the width
targetWidth = srcHeight;
targetHeight = srcHeight * ratio;
}
//console.log("target: " + targetWidth + "x" + targetHeight);
if (targetWidth > srcWidth) {
// resize to fit
var resizeRatio = 1 / targetWidth * srcWidth;
targetWidth = srcWidth;
targetHeight = targetHeight * resizeRatio;
}
if (targetHeight > srcHeight) {
var resizeRatio = 1 / targetHeight * srcHeight;
targetWidth = targetWidth * resizeRatio;
targetHeight = srcHeight;
}
targetWidth = Math.floor(targetWidth);
targetHeight = Math.floor(targetHeight);
// console.log("target: " + targetWidth + "x" + targetHeight);
var transform = PerspectiveOps.general2DProjection(0, 0, leftTopCorner[0], leftTopCorner[1], // lt
1, 0, rightTopCorner[0], rightTopCorner[1], // rt
0, 1, leftBottomCorner[0], leftBottomCorner[1], // lb
1, 1, rightBottomCorner[0], rightBottomCorner[1]);
//let targetArray = new Uint8Array(targetWidth * targetHeight);
// make the buffer larger than it's supposed to be
// it's not necessary if it runs once, but keeping it the same size as the source
// means the buffer can be reused later and as these are can be quite large which
// would save a lot in memory allocation
var targetArray = BufferManager.getInstance().getUInt8Buffer(srcWidth * srcHeight);
var targetIdx = 0;
// transform per pixel on a full HD image is way too slow on phones
// instead project every blockSize pixels and then linearly interpolate between the points
var dx = 1 / targetWidth;
var dy = 1 / targetHeight;
var t0dx = transform[0] * dx;
var t3dx = transform[3] * dx;
var t6dx = transform[6] * dx;
var t1dy = transform[1] * dy;
var t4dy = transform[4] * dy;
var t7dy = transform[7] * dy;
var t1 = 0 + transform[2];
var t4 = 0 + transform[5];
var t7 = 0 + transform[8];
for (var y = 0; y < targetHeight; y++) {
//let pxPart = transform[1] * j + transform[2];
//let pyPart = transform[4] * j + transform[5];
//let pzPart = transform[7] * j + transform[8];
var pxPart = t1;
var pyPart = t4;
var pzPart = t7;
var t0 = 0;
var t3 = 0;
var t6 = 0;
for (var x = 0; x < targetWidth; x++) {
//let px = transform[0] * i + pxPart;
//let py = transform[3] * i + pyPart;
//let pz = transform[6] * i + pzPart;
var px = t0 + pxPart;
var py = t3 + pyPart;
var pz = t6 + pzPart;
var srcX = pz == 0 ? 0 : ~~(px / pz * srcWidth);
if (srcX >= 0 && srcX < srcWidth) {
var srcY = pz == 0 ? 0 : ~~(py / pz * srcHeight);
if (srcY >= 0 && srcY < srcHeight) {
var idx = (srcY * srcWidth + srcX);
targetArray[targetIdx] = srcArray[idx];
}
}
targetIdx++;
t0 += t0dx;
t3 += t3dx;
t6 += t6dx;
}
t1 += t1dy;
t4 += t4dy;
t7 += t7dy;
}
return {
width: targetWidth,
height: targetHeight,
data: targetArray
};
}
})(Algorithm || (Algorithm = {}));
var ContourOps;
(function (ContourOps) {
function angleBetween(prev, cur, next, width) {
var xprev = prev % width;
var yprev = Math.floor(prev / width);
var xcur = cur % width;
var ycur = Math.floor(cur / width);
var xnext = next % width;
var ynext = Math.floor(next / width);
var v1x = xprev - xcur;
var v1y = yprev - ycur;
var v2x = xnext - xcur;
var v2y = ynext - ycur;
var dot = v1x * v2x + v1y * v2y;
var lenv1 = Math.sqrt(v1x * v1x + v1y * v1y);
var lenv2 = Math.sqrt(v2x * v2x + v2y * v2y);
var cos = dot / (lenv1 * lenv2);
return Math.round(Math.acos(cos) / Math.PI * 180);
}
function findCorners(contour, width) {
// find the 4 points that are furthest from the center and have at least 45° between them
var minimumAngle = 45;
var center = centerOfPolygon(contour, width);
var centerX = center % width;
var centerY = Math.floor(center / width);
var bestPoints = [];
var distancesSquared = new Array(contour.length);
for (var i = 0; i < contour.length; i++) {
var x = contour[i] % width;
var y = Math.floor(contour[i] / width);
distancesSquared[i] = (x - centerX) * (x - centerX) + (y - centerY) * (y - centerY);
}
var visited = new Array(contour.length);
while (bestPoints.length < 4) {
var maxDistance = Number.MIN_VALUE;
var maxDistanceIndex = -1;
for (var i = 0; i < contour.length; i++) {
if (!visited[i]) {
if (maxDistance < distancesSquared[i]) {
maxDistance = distancesSquared[i];
maxDistanceIndex = i;
}
}
}
if (maxDistanceIndex == -1)
break;
visited[maxDistanceIndex] = true;
var canAdd = true;
for (var i = 0; i < bestPoints.length && canAdd; i++) {
var angle = angleBetween(bestPoints[i], center, contour[maxDistanceIndex], width);
if (angle < minimumAngle || angle > 360 - minimumAngle)
canAdd = false;
}
if (canAdd && maxDistanceIndex != -1)
bestPoints.push(contour[maxDistanceIndex]);
}
return bestPoints;
}
ContourOps.findCorners = findCorners;
function spiralAround(sx, sy, width, height, func) {
var l = sx;
var r = sx + 1;
var t = sy;
var b = sy + 1;
var radius = Math.max(width, height);
var curX = l;
var curY = t - 1;
var curRadius = 0;
while (curRadius < radius) {
var edgeWidth = 1 + 2 * curRadius;
if (curY >= 0 && curY < height) {
for (var i = l; i <= r + edgeWidth; i++) {
if (curX < width && curX >= 0)
func(curX, curY);
curX++;
}
}
else
curX += r + edgeWidth + 1 - l;
curX--;
curY++;
if (curX >= 0 && curX < width) {
for (var i = t; i <= b + edgeWidth; i++) {
if (curY < height && curY >= 0)
func(curX, curY);
curY++;
}
}
else
curY += b + edgeWidth + 1 - t;
curY--;
curX--;
if (curY >= 0 && curY < height) {
for (var i = r; i >= l - edgeWidth; i--) {
if (curX >= 0 && curY < width)
func(curX, curY);
curX--;
}
}
else {
curX -= r + 1 - (l - edgeWidth);
}
curX++;
curY--;
if (curX >= 0 && curX < width) {
for (var i = b; i >= t - edgeWidth; i--) {
if (curY >= 0 && curY < height)
func(curX, curY);
curY--;
}
}
else {
curY -= b + 1 - (t - edgeWidth);
}
curRadius++;
}
}
// implementation of http://www.mdpi.com/1424-8220/16/3/353
function traceContours(padding, grayscale, width, height) {
var allContours = [];
var Direction;
(function (Direction) {
Direction[Direction["Right"] = 0] = "Right";
Direction[Direction["Bottom"] = 1] = "Bottom";
Direction[Direction["Left"] = 2] = "Left";
Direction[Direction["Top"] = 3] = "Top";
})(Direction || (Direction = {}));
var Position;
(function (Position) {
Position[Position["LeftFront"] = 0] = "LeftFront";
Position[Position["Front"] = 1] = "Front";
Position[Position["RightFront"] = 2] = "RightFront";
Position[Position["Right"] = 3] = "Right";
Position[Position["RightRear"] = 4] = "RightRear";
Position[Position["Rear"] = 5] = "Rear";
Position[Position["LeftRear"] = 6] = "LeftRear";
Position[Position["Left"] = 7] = "Left";
})(Position || (Position = {}));
// contour
var getX = function (pos, dir) {
switch (dir) {
case Direction.Top:
switch (pos) {
case Position.Left:
case Position.LeftFront:
case Position.LeftRear:
return -1;
case Position.Right:
case Position.RightFront:
case Position.RightRear:
return 1;
}
break;
case Direction.Right:
switch (pos) {
case Position.Front:
case Position.LeftFront:
case Position.RightFront:
return 1;
case Position.Rear:
case Position.LeftRear:
case Position.RightRear:
return -1;
}
break;
case Direction.Bottom:
switch (pos) {
case Position.Right:
case Position.RightFront:
case Position.RightRear:
return -1;
case Position.Left:
case Position.LeftFront:
case Position.LeftRear:
return 1;
}
break;
case Direction.Left:
switch (pos) {
case Position.LeftFront:
case Position.Front:
case Position.RightFront:
return -1;
case Position.LeftRear:
case Position.Rear:
case Position.RightRear:
return 1;
}
break;
}
return 0;
};
var getY = function (pos, dir) {
switch (dir) {
case Direction.Top:
switch (pos) {
case Position.Front:
case Position.LeftFront:
case Position.RightFront:
return -1;
case Position.Rear:
case Position.LeftRear:
case Position.RightRear:
return 1;
}
break;
case Direction.Right:
switch (pos) {
case Position.Right:
case Position.RightFront:
case Position.RightRear:
return 1;
case Position.Left:
case Position.LeftFront:
case Position.LeftRear:
return -1;
}
break;
case Direction.Bottom:
switch (pos) {
case Position.Front:
case Position.LeftFront:
case Position.RightFront:
return 1;
case Position.Rear:
case Position.LeftRear:
case Position.RightRear:
return -1;
}
break;
case Direction.Left:
switch (pos) {
case Position.Right:
case Position.RightFront:
case Position.RightRear:
return -1;
case Position.Left:
case Position.LeftFront:
case Position.LeftRear:
return 1;
}
break;
}
return 0;
};
var getDirection = function (pos, dir) {
switch (dir) {
case Direction.Top:
switch (pos) {
case Position.Front: return Direction.Top;
case Position.Left: return Direction.Left;
case Position.Right: return Direction.Right;
case Position.Rear: return Direction.Bottom;
}
break;
case Direction.Right:
switch (pos) {
case Position.Front: return Direction.Right;
case Position.Left: return Direction.Top;