-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.html
1059 lines (977 loc) · 44.5 KB
/
main.html
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
<!DOCTYPE HTML>
<html>
<head>
<!-- Stylesheets -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="stylesheets/style.css">
<link rel="stylesheet" href="resources/bootstrap.min.css">
<link rel="stylsesheet" href="resources/bootstrap-theme.min.css">
<!-- External resources and libraries -->
<script type="text/javascript" src="resources/tracking.js"></script>
<script type="text/javascript" src="resources/jquery.js"></script>
<script type="text/javascript" src="resources/cornerdetect.js"></script>
<script type="text/javascript" src="resources/Chart.js" charset="utf-8"></script>
<script type="text/javascript" src="resources/bootstrap.min.js"></script>
<!-- Functions to get test images in base 64-->
<script type="text/javascript" src="test_images/initial_images.js"></script>
<script type="text/javascript" src="test_images/test_images_rotated.js"></script>
<!-- Own methods and helpers -->
<script type="text/javascript" src="helpers.js"></script>
<script type="text/javascript" src="data_structures.js"></script>
<script type="text/javascript" src="utils.js"></script>
<!-- Google API for Geolocation-->
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="canvas-container">
<canvas id="canvas" class="row"></canvas>
<p id="runtimeAnalysis"></p>
<p id="mousePos"></p>
</div>
<div id ="controls" class="btn-group-vertical row" role="group">
<button type="button" class="btn btn-default" onclick = "getRuntime(detect)"> Detect rectangle </button>
<button type="button" class="btn btn-default" onclick = "getRuntime(crop)"> Crop </button>
<button type="button" class="btn btn-default" onclick = "getRuntime(rotate)"> Rotate </button>
<button type="button" class="btn btn-default" onclick = "getRuntime(removeMarkers)"> Remove markers </button>
<button type="button" class="btn btn-default" onclick = "getRuntime(getBlackBoxes)"> Find Black Boxes </button>
<button type="button" class="btn btn-default" onclick = "getRuntime(LocateMe)"> Find Location </button>
<button type="button" class="btn btn-default" onclick = "getRuntime(processAllLanes)">Process Lanes</button>
<button type="button" class="btn btn-default" onclick = "getRuntime(generateDiagnosis)">Diagnose</button>
<div id="map-canvas" class="row"></div>
</div>
<div id="graph-container">
<h3 id="chartTitle"></h3>
<canvas id="graph" width="900" height="600"></canvas>
<p>Graph Lane:</p><input type="number" id="laneNo" name="laneNo" value="0" min="0" oninput="input()">
</div>
<div id="map-canvas" class="row"></div>
</div>
<div id="table-container">
<table id="resultsTable" class="table table-striped"></table>
</div>
<script>
//********************************** GEOLOCATION SETUP **********************************
var mapOptions = {
zoom: 2
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var DisplayRandomMap = function(){
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: "Map Initialized"
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
};
//********************************** END GEOLOCATION SETUP **********************************
//********************************** CANVAS SETUP **********************************
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
var imageHeight, imageWidth;
var imageData, pixels;
//variables for the tracker.js
var tracked_rect;
var markerRectangle;
//Test images in base64
var mmdx_image_normal = getTestImageNormal();
var mmdx_image_tilted_right = getTestImageRotatedRight();
var mmdx_image_tilted_left = getTestImageRotatedLeft();
var mmdx_image_tilted_left2 = getTestImageRotatedLeft2();
// USED IN ANDROID
// function loadImage(image_base64){
// imageObj = new Image();
// mmdx_image_app = image_base64;
// imageObj.src = image_base64;
// //console.log("Image from android");
// //console.log(image_base64.substring(0, 50));
// imageObj.onload = function() {
// imageHeight = imageObj.height;
// imageWidth = imageObj.width;
// canvas.height = imageHeight;
// canvas.width = imageWidth;
// context.drawImage(imageObj,0, 0);
// }
// }
//************ COMMENT OUT INSIDE ANDROID ***************
//Set test image
//var mmdx_image = mmdx_image_normal;
var mmdx_image = mmdx_image_tilted_left;//getImageRotated10();
imageObj.src = mmdx_image;//"https://dl.dropboxusercontent.com/s/a75cdy8umi5l178/2015-05-11%2014.49.32.jpg";
imageObj.crossOrigin = "anonymous"; //just in case
//draw image to canvas
imageObj.onload = function() {
imageHeight = imageObj.height;
imageWidth = imageObj.width;
canvas.height = 800*(imageHeight/imageWidth);
canvas.width = 800;
/// step 1
var oc = document.createElement('canvas'),
octx = oc.getContext('2d');
oc.width = imageWidth * 0.5;
oc.height = imageHeight * 0.5;
octx.drawImage(imageObj, 0, 0, oc.width, oc.height);
/// step 2
octx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5);
context.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5,
0, 0, canvas.width, canvas.height);
//canvas.height = imageHeight;
//canvas.width = imageWidth;
//context.drawImage(imageObj,0, 0);
};
//function loadImage(image_base64){
// imageObj.src = image_base64
//}
//******** END COMMENT OUT INSIDE ANDROID ***************
//array that has the positional data of the lanes to be processed
var markerBoxes=[];
//the array of signal objects of the processed lanes
var laneData=[];
//Constant specifying how many regions along each strip is considered
var nMarkerRegions=2;
//*****************************************************************************************************
//*****************************************************************************************************
//*********************************** YOU CAN COPY CODE AS FROM HERE INTO THE INNER ONE****************
//*****************************************************************************************************
//*****************************************************************************************************
//Register color tracking.js uses to identify markers
tracking.ColorTracker.registerColor('marker', function(r, g, b) {
return isRed({r:r,g:g,b:b});
});
//********************************** END CANVAS SETUP **********************************
function analyze (){
}
//********************************** RECOGNITION: MARKER DETECTION *********************
/**
DETECTION:
Uses tracking.js to find markers (color details are specified above)
Finds a rectangle around a detected object
=======
<script>
//********************************** GEOLOCATION SETUP **********************************
// var mapOptions = {
// zoom: 1
// };
// var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// var DisplayRandomMap = function(){
// var options = {
// map: map,
// position: new google.maps.LatLng(60, 105),
// content: "Map Initialized"
// };
// var infowindow = new google.maps.InfoWindow(options);
// map.setCenter(options.position);
// };
//********************************** END GEOLOCATION SETUP **********************************
//********************************** CANVAS SETUP **********************************
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
var imageHeight, imageWidth;
var imageData, pixels;
//variables for the tracker.js
var tracked_rect;
var markerRectangle;
//Test images in base64
var mmdx_image_normal = getTestImageNormal();
var mmdx_image_tilted_right = getTestImageRotatedRight();
var mmdx_image_tilted_left = getTestImageRotatedLeft();
var mmdx_image_tilted_left2 = getTestImageRotatedLeft2();
// USED IN ANDROID
// function loadImage(image_base64){
// imageObj = new Image();
// mmdx_image_app = image_base64;
// imageObj.src = image_base64;
// //console.log("Image from android");
// //console.log(image_base64.substring(0, 50));
// imageObj.onload = function() {
// imageHeight = imageObj.height;
// imageWidth = imageObj.width;
// //canvas.height = imageHeight;
// //canvas.width = imageWidth;
// //context.drawImage(imageObj,0, 0);
// canvas.height = 800*(imageHeight/imageWidth);
// canvas.width = 800;
// /// step 1
// var oc = document.createElement('canvas'),
// octx = oc.getContext('2d');
// oc.width = imageWidth * 0.5;
// oc.height = imageHeight * 0.5;
// octx.drawImage(imageObj, 0, 0, oc.width, oc.height);
// /// step 2
// octx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5);
// context.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5,
// 0, 0, canvas.width, canvas.height);
// }
// }
//************ COMMENT OUT INSIDE ANDROID ***************
//Set test image
var mmdx_image = mmdx_image_normal;
//var mmdx_image = getImageRotated10();
//"https://dl.dropboxusercontent.com/s/npfv94ktix8fqrz/20150510_171950.jpg";
//"https://dl.dropboxusercontent.com/s/lsebdpc9rdo42li/1431378655452.jpg"; //native tracking works with isRed in this file
//"https://dl.dropboxusercontent.com/s/8lkfdh28ajgxkuc/1431378100503.jpg";//native tracking works
//"https://dl.dropboxusercontent.com/s/d32lmuakp8q0f9d/1431284418461.jpg"; //didn't work carton markers
//"https://dl.dropboxusercontent.com/s/n2o5pft318g74vq/1431292734919.jpg";
var image_goodLighting = "https://dl.dropboxusercontent.com/s/jpkfzol1fxylmbl/2015-05-11%2014.04.10.jpg";
var image_rotated_with_strips = "https://dl.dropboxusercontent.com/s/e0h29cc7k8vwp8n/rotatedRightColor.png";
var image_shade = "https://dl.dropboxusercontent.com/s/a75cdy8umi5l178/2015-05-11%2014.49.32.jpg";
var image_flash = "https://dl.dropboxusercontent.com/s/8zxumw5wnxmcc6b/2015-05-11%2014.57.54.jpg";
// FAILS
var image_original = "https://dl.dropboxusercontent.com/s/gndxrbigfy2r4zv/originalRecolored.png";
var image_redBackground = "https://dl.dropboxusercontent.com/s/47zpza9q81s2evp/2015-05-11%2014.59.09.jpg";
var image_goodLightingRotated= "https://dl.dropboxusercontent.com/s/oru5sae9bbzt7op/2015-05-11%2014.04.06.jpg?dl=0";
imageObj.src = "https://dl.dropboxusercontent.com/s/n2o5pft318g74vq/1431292734919.jpg";
imageObj.crossOrigin = "anonymous"; //just in case
//draw image to canvas
imageObj.onload = function() {
var resolution = .7;
imageHeight = imageObj.height;
imageWidth = imageObj.width;
canvas.height = 800*(imageHeight/imageWidth);
canvas.width = 800;
/// step 1
var oc = document.createElement('canvas'),
octx = oc.getContext('2d');
oc.width = imageWidth * resolution;
oc.height = imageHeight * resolution;
octx.drawImage(imageObj, 0, 0, oc.width, oc.height);
/// step 2
octx.drawImage(oc, 0, 0, oc.width * resolution, oc.height * resolution);
context.drawImage(oc, 0, 0, oc.width * resolution, oc.height * resolution,
0, 0, canvas.width, canvas.height);
};
//function loadImage(image_base64){
// imageObj.src = image_base64
//}
//******** END COMMENT OUT INSIDE ANDROID ***************
//array that has the positional data of the lanes to be processed
var markerBoxes=[];
//the array of signal objects of the processed lanes
var laneData=[];
//*****************************************************************************************************
//*****************************************************************************************************
//*********************************** YOU CAN COPY CODE AS FROM HERE INTO THE INNER ONE****************
//*****************************************************************************************************
//*****************************************************************************************************
//Register color tracking.js uses to identify markers
tracking.ColorTracker.registerColor('marker', function(r, g, b) {
return isRed({r:r,g:g,b:b});
});
//********************************** END CANVAS SETUP **********************************
//********************************** RECOGNITION: MARKER DETECTION *********************
/**
DETECTION:
Uses tracking.js to find markers (color details are specified above)
Finds a rectangle around a detected object
>>>>>>> 4ffd84f342b6bb07f3d9282d4f4e947d6766d0d7
(tracker returns "rect" object {x: value, y:value, height:value, width:value, color:value})
If not rotated, will draw the abovementioned rectange and use its corners
If rotated, find the intersection of the actual rectange with the abovemention rectangle
and assigns corners correctly
*/
function detect(){
imageData = context.getImageData(0,0,imageWidth, imageHeight);
pixels = imageData.data;
console.log("Start Detecting");
var tracker = new tracking.ColorTracker(['marker']);
tracker.on('track', function(event) {
event.data.forEach(function(rect) {
console.log("tracking found smth");
tracked_rect = rect;
var x = rect.x;
var y = rect.y;
var w = rect.width;
var h = rect.height;
//corners might change
var corners = [new Point(x,y),new Point(x+w, y+h), new Point(x+w,y), new Point(x, y+h)];
var rotated = checkIfRotated();
markerRectangle = new Rectangle(corners, rotated);
drawRectangle(markerRectangle.getCorners(), "blue");
if (markerRectangle.isRotated()){
findCorners();
}
drawRectangle(markerRectangle.getCorners(), "yellow");
});
});
tracking.track('#canvas', tracker); //start tracking
}
/*
Moves along the detected rectangle, if the majority of the points are red, assumes
tracker found a correct rectangle
*/
function checkIfRotated(){
console.log("checkIfRotated");
var threshold = .4; //NEED TO ADJUST/TEST
var x = tracked_rect.x;
var y = tracked_rect.y;
var w = tracked_rect.width;
var h = tracked_rect.height;
var numPoints = 10*(w+(h-10));
var countRed = 0;
//move along the top edge
for (var p=0; p<5;p++){
for (var i = 0; i<w; i++){
var px = getPixelRGB(pixels, x+i, y+p, imageWidth, imageWidth);
if (isRed(px)){
countRed++
}
}
}
//bottom edge
for (var p=0; p<5;p++){
for (var i = 0; i<w; i++){
var px = getPixelRGB(pixels, x+i, y+h-p, imageWidth, imageWidth);
if (isRed(px)){
countRed++
}
}
}
//left edge
for (var p=0; p<5;p++){
for (var i = 5; i<h-5; i++){
var px = getPixelRGB(pixels, x+p, y+i, imageWidth, imageWidth);
if (isRed(px)){
countRed++
}
}
}
//right edge
for (var p=0; p<5;p++){
for (var i = 5; i<h-5; i++){
var px = getPixelRGB(pixels, x+w-p, y+i, imageWidth, imageWidth);
if (isRed(px)){
countRed++
}
}
}
console.log("ratio");
console.log(countRed/numPoints);
return (countRed/numPoints) < threshold;
}
// Now we use a "radius" walk to find point closer to the corner of the tracking.js blue rectangle
function findCorners(){
console.log("Finding corners 2");
var x = tracked_rect.x+5;
var y = tracked_rect.y+5;
//console.log("RECTANGLE DIMENSIONS X,y: ", x, y);
var w = tracked_rect.width-5;
var h = tracked_rect.height-5;
//console.log("RECTANGLE DIMENSIONS: ", w, h);
var c1, c2, c3, c4; //corners
var radius = Math.min(w,h);
//upper left (x, y)
context.fillStyle="green";
context.fillRect(x,y,10,10);
for (var iter = 1; iter<radius; iter++){
var deltaX = iter;
var deltaY = 0;
var check = true;
while (deltaX>=0 && check){
var px = getPixelRGB(pixels, x+deltaX, y+deltaY, imageWidth, imageHeight);
//context.fillStyle="purple";
//context.fillRect(x+deltaX,y+deltaY,1,1);
if (isRed(px)){
c1 = new Point(x+deltaX, y+deltaY);
console.log("C1");
console.log(c1);
check=false;
}
deltaX--;
deltaY++;
}
if (!check){
break;
}
}
//upper right (x+w, y)
context.fillStyle="green";
context.fillRect(x+w,y,10,10);
for (var iter = 1; iter<radius; iter++){
deltaX = iter;
deltaY = 0;
check = true;
while (deltaX>=0 && check){
px = getPixelRGB(pixels, x+w-deltaX, y+deltaY, imageWidth, imageHeight);
//context.fillStyle="purple";
//context.fillRect(x+w-deltaX,y+deltaY,1,1);
if (isRed(px)){
c3 = new Point(x+w-deltaX, y+deltaY);
console.log("C3");
console.log(c3);
check=false;
}
deltaX--;
deltaY++;
}
if (!check){
break;
}
}
//lower left (x, y+h)
context.fillStyle="green";
context.fillRect(x,y+h,10,10);
for (var iter = 1; iter<radius; iter++){
deltaX = iter;
deltaY = 0;
check = true;
while (deltaX>=0 && check){
px = getPixelRGB(pixels, x+deltaX, y+h-deltaY, imageWidth, imageHeight);
//context.fillStyle="purple";
//context.fillRect(x+deltaX,y+h-deltaY,1,1);
if (isRed(px)){
//context.fillStyle="cyan";
//context.fillRect(x+deltaX,y+h-deltaY,10,10);
c4 = new Point(x+deltaX, y+h-deltaY);
console.log("C4");
console.log(c4);
check=false;
}
deltaX--;
deltaY++;
}
if (!check){
break;
}
}
//lower right (x+w, y+h)
context.fillStyle="green";
context.fillRect(x+w,y+h,10,10);
for (var iter = 1; iter<radius; iter++){
deltaX = iter;
deltaY = 0;
check = true;
while (deltaX>=0 && check){
px = getPixelRGB(pixels, x+w-deltaX, y+h-deltaY, imageWidth, imageHeight);
//context.fillStyle="purple";
//context.fillRect(x+w-deltaX,y+h-deltaY,1,1);
if (isRed(px)){
c2 = new Point(x+w-deltaX, y+h-deltaY);
console.log("C2");
console.log(c2);
check=false;
}
deltaX--;
deltaY++;
}
if (!check){
break;
}
}
markerRectangle.setCorners([c1,c2,c3,c4]);
}
function drawRectangle(points, color){
var c1 = points[0];
var c2 = points[1];
var c3 = points[2];
var c4 = points[3];
console.log("drawCorners:",c1,c2,c3,c4 );
context.strokeStyle = color;
context.beginPath();
context.beginPath();
context.moveTo(c1.x,c1.y);
context.lineTo(c3.x,c3.y);
context.lineTo(c2.x,c2.y);
context.lineTo(c4.x,c4.y);
//context.lineTo(c1.x,c1.y);
context.closePath();
context.stroke();
}
//********************************** END RECOGNITION: MARKER DETECTION *********************
//********************************** RECOGNITION: ROTATION *********************************
/*
Rotates the image based on the angle between the top line of the rect (from tracker)
and new rotated rect (whose corners are found in findCorners())
*/
var rotate = function (){
if (!markerRectangle.isRotated()){
alert("no need to rotate");
return;
}
var c1 = markerRectangle.getCorners()[0];
var c2 = markerRectangle.getCorners()[1];
var c3 = markerRectangle.getCorners()[2];
var c4 = markerRectangle.getCorners()[3];
//save image data so we can modify canvas
var imageURL = canvas.toDataURL();
var image = new Image();
image.src = imageURL;
var angle = markerRectangle.findAngleOfRotation();
//find the center to rotate about
var center = new Point(Math.round(tracked_rect.x+tracked_rect.width/2), Math.round(tracked_rect.y+tracked_rect.height/2));
context.translate(1*center.x, 1*center.y);
context.save();
context.rotate(angle.radians); //canvas rotate clockwise
context.translate(-1*center.x, -1*center.y);
context.drawImage(image,0, 0);
context.restore();
// translate back to 0,0 coordinates
context.translate(-1*center.x, -1*center.y);
rotated = false;
};
//********************************** END RECOGNITION: ROTATION *********************
//********************************** RECOGNITION: CROP *********************
/*
Crops the image by its markers (either rect from tracker or adjusted corners)
Assumes corners are known
*/
var crop = function(){
var c1 = markerRectangle.getCorners()[0];
var c2 = markerRectangle.getCorners()[1];
var c3 = markerRectangle.getCorners()[2];
var c4 = markerRectangle.getCorners()[3];
// Create a canvas that we will use as a mask
var maskCanvas = document.createElement('canvas');
// Ensure same dimensions
maskCanvas.width = canvas.width;
maskCanvas.height = canvas.height;
var maskCtx = maskCanvas.getContext('2d');
// This color is the one of the filled shape
maskCtx.fillStyle = "white";
// Fill the mask
maskCtx.fillRect(0, 0, maskCanvas.width, maskCanvas.height);
// Set xor operation
maskCtx.globalCompositeOperation = 'xor';
// Draw the shape you want to take out
maskCtx.beginPath();
maskCtx.moveTo(c1.x,c1.y);
maskCtx.lineTo(c3.x,c3.y);
maskCtx.lineTo(c2.x,c2.y);
maskCtx.lineTo(c4.x,c4.y);
maskCtx.lineTo(c1.x,c1.y);
maskCtx.closePath();
maskCtx.fill();
context.drawImage(maskCanvas, 0, 0);
context.save();
};
//********************************** END RECOGNITION: REMOVE MARKERS *********************
/*
Removes red markers, assumes the image is properly oriented
*/
var removeMarkers = function(){
var padding = 10;
console.log("removing");
var leftEdge, rightEdge, upperEdge, lowerEdge;
var w = canvas.width;
var h = canvas.height;
imageData = context.getImageData(0,0,w, h);
pixels = imageData.data;
var y = 0;
//look for beginning of the top edge
while(!(isRed(getPixelRGB(pixels, Math.round(w/2),y, w, h)))){
y++;
}
//end of the top edge
while (isRed(getPixelRGB(pixels, Math.round(w/2),y, w, h))) {
y++;
}
upperEdge = y-1 + padding;
//look for beginning of the bottom edge
y = h;
while(!(isRed(getPixelRGB(pixels, Math.round(w/2),y, w, h)))){
y--;
}
//end of the bottom edge
while (isRed(getPixelRGB(pixels, Math.round(w/2),y, w, h))) {
y--;
}
lowerEdge = y+1 - padding;
//look for beginning of the left edge
var x = 0;
while(!(isRed(getPixelRGB(pixels, x, Math.round(h/2), w, h)))){
x++;
}
//end of the right edge
while (isRed(getPixelRGB(pixels, x,Math.round(h/2), w, h))) {
x++;
}
leftEdge = x+1 + padding;
var x = w;
while(!(isRed(getPixelRGB(pixels, x, Math.round(h/2), w, h)))){
x--;
}
//end of the right edge
while (isRed(getPixelRGB(pixels, x,Math.round(h/2), w, h))) {
x--;
}
rightEdge = x-1 - padding;
console.log(leftEdge, rightEdge, upperEdge, lowerEdge);
context.drawImage(canvas, leftEdge, upperEdge, rightEdge - leftEdge, lowerEdge - upperEdge, 0, 0, w, h);
}
//****************************** END RECOGNITION: REMOVE MARKERS *********************
//****************************** RECOGNITION: BLACK BOX DETECTION ********************
function getBlackBoxes(){
//This is just for optimization might get rid of it if it causes problems
var searchWidth = canvas.width;
var searchHeight = canvas.height * .20;
//coordinates of the black boxes
var rawBoxData = [];
var boxArray = [];
var pixelRow = context.getImageData(0, 0, searchWidth, 1);
var data = pixelRow.data;
/**
* Finds the vertical middle of the row of black boxes. We use this row to search because the tops and bottoms of the boxes aren't perfectly aligned.
* @returns {number}
*/
function getMiddleYOfBoxes() {
var startColumn = 0;
var horizontalMiddleOfBox = 0;
while (!foundFirstBoxEdge(data) && horizontalMiddleOfBox < searchHeight) {
pixelRow = context.getImageData(startColumn, horizontalMiddleOfBox, searchWidth, 1);
data = pixelRow.data;
horizontalMiddleOfBox++;
}
horizontalMiddleOfBox += canvas.height * .04;
return horizontalMiddleOfBox;
}
/**
* Fills the box arrays with their dimensions
*/
function getBoxEdges(){
var startColumn = 0;
var horizontalMiddleOfBox = getMiddleYOfBoxes();
var pixelRowMiddle = context.getImageData(startColumn, horizontalMiddleOfBox, searchWidth, 1);
var midData = pixelRowMiddle.data;
findBlackBoxEdgesFromMiddle(startColumn,rawBoxData,midData);
for(var boxData = 0; boxData < rawBoxData.length; boxData += 2){
boxArray.push([rawBoxData[boxData],rawBoxData[boxData+1]])
}
for(var box = 0; box<boxArray.length; box++){
getHeights(boxArray[box]);
removeExtraYCoords(boxArray[box]);
drawLanes(boxArray[box]);
}
markerBoxes=boxArray;
}
getBoxEdges();
}
//****************************** END RECOGNITION: BLACK BOX DETECTION ****************
//****************************** ANALYSIS: LANE PROCESSING ***************************
//Parameters:
//start_x: lane left line x
//start_y: top marker box bottom y
//end_x: lane right line x
//end_y: bottom marker box top y
//sampling rate: floating point number between (0.0,1.0) specifying what percentage
//of the lane will be processed
//Return value:
//signal object of one lane with the following properties
// rgbVector: rgb average of each sampled band
// start_x, end_x, start_y, end_y
// strip_length, strip_width
// samplingRate, numberOfSamples
var processLane=function (start_x,end_x,start_y,end_y,samplingRate){
context.fillStyle="green";
pixels=context.getImageData(0,0,imageWidth,imageHeight).data;
var signal={};
signal.samplingRate=samplingRate;
signal.start_x=start_x;
signal.start_y=start_y;
signal.end_x=end_x;
signal.end_y=end_y;
signal.strip_length=Math.abs(end_y-start_y);
signal.strip_width=Math.abs(end_x-start_x);
signal.numberOfSamples=Math.ceil(signal.strip_length*samplingRate);
var increment=Math.floor(signal.strip_length/(signal.numberOfSamples-1));
var rgbVector=[];
var hslVector=[];
var index=0;
for (var i=start_y; i < end_y; i+=increment){
var test_r=0;
var test_g=0;
var test_b=0;
//averaging rgb values along each band
for(var j=start_x; j < end_x; j++){
rgb=getPixelRGB(pixels,j,i,imageWidth,imageHeight);
test_r+=rgb.r;
test_g+=rgb.g;
test_b+=rgb.b;
}
test_r/=signal.strip_width;
test_g/=signal.strip_width;
test_b/=signal.strip_width;
rgbVector[index]={"r":test_r,"g":test_g,"b":test_b};
hslVector[index]=rgbToHsl(test_r,test_g,test_b);
index++;
context.fillRect(start_x,i,signal.strip_width,1);
}
signal.rgbVector=rgbVector;
signal.hslVector=hslVector;
return signal;
}
function processAllLanes(){
var i=0;
var samplingRate=0.4;
for(var i in markerBoxes){
var test=markerBoxes[i];
laneData[i]=processLane(test[0],test[1],test[2],test[3],samplingRate);
i++;
}
};
//************************** END ANALYSIS: LANE PROCESSING ****************************
//************************** GEOLOCATION **********************************************
//handling geolocation here
//current version only works on the click of a button, therefore, we have a button up there "Locate Me"
//Later: pass in diagnosis as argument to LocateMe <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<IMPORTANT
//handling geolocation here
//current version only works on the click of a button, therefore, we have a button up there "Locate Me"
//Later: pass in diagnosis as argument to LocateMe <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<IMPORTANT
function LocateMe() { // works on LG but not on OPO
console.log("Running Locate Me!");
// Try HTML5 geolocation
if(navigator.geolocation) {
console.log("NAVIGATOR OK");
//console.log(navigator.geolocation.getCurrentPosition);
navigator.geolocation.getCurrentPosition(function(position) {
console.log("POS Running");
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
console.log("INFO-WINDOW Running");
// var infowindow = new google.maps.InfoWindow({
// map: map,
// position: pos,
// content: 'Location found using HTML5.'
// });
console.log("myLOCATION Running");
var mylocation = {lat: position.coords.latitude, lng:position.coords.longitude};
// call to function to send to DB
var Results = mylocation;
Results.diagnosis = "Ebola";
sendDataToDB(Results);
//END this call here
console.log("This is my Location");
console.log(mylocation.lat);
console.log(mylocation.lng);
//map.setCenter(pos);
}, function() {
console.log("HandleGeolocFailure within navigator Running");
handleGeolocationFailure(true);
},
{ timeout:60000,
enableHighAccuracy:false
}
);
} else {
console.log("NAVIGATOR NOT OK");
// Browser doesn't support Geolocation
handleGeolocationFailure(false);
}
}
//this function handles the case when geolocation cannot be found, then it centers the map component at a random location
function handleGeolocationFailure(errorFlag) {
console.log("Running handleGeolocationFailure");
if (errorFlag) {
console.log("Error: The Geolocation service failed");
var content = 'Error: The Geolocation service failed.';
} else {
console.log("Error: Browser does not support geolocation");
var content = 'Error: Your browser doesn\'t support geolocation.';
}
// var options = {
// map: map,
// position: new google.maps.LatLng(100, 105),
// content: content
// };
// var infowindow = new google.maps.InfoWindow(options);
// map.setCenter(options.position);
}
//************************** END GEOLOCATION ******************************************
//************************** SEND DATA TO SERVER **************************************
// Flow works as follows: detect Rectangle, Rotate, Crop, removeMarkers, FindBlackBoxes
// Analyse/ Diagnose (To be implemented), Find Location
// (Find Location then calls sendDataToDB);
// Automatically do image processing, Diagnosis and location finding when called
// this will be used to post stuff to the DB as well
function sendDataToDB(results){
//results contains: lng, lat, diagnosis
console.log("calling the diagnosis function");
console.log(results.lat);
console.log(results.lng);
console.log(results.diagnosis);
var url = "http://localhost:5000/results?"; //lat=10.1&lng=10&diagnosis=Ebola;
//sends dummy data, not yet connected to website
//location.href = url+ "lat="+results.lat+"&lng="+results.lng+"&diagnosis="+results.diagnosis;
console.log("calling Set Data");
setData(JSON.stringify(results));
}
//testing sending stuff to native android
var setData = function(data) {
console.log("okay i got into the local SetData method");
Android.setData(data);
window.alert("Data sent to Native Android");
}
//************************** END SEND DATA TO SERVER **********************************
//************************** GRAPH RESULTS ********************************************
//Parameters:
// the index of the lane to be graphed from the list of processed lanes
//Creates a graph of rgb values vs sampled band index for the given laneIndex
function graph(laneIndex){
var lane=laneData[laneIndex];
var rgb=lane.rgbVector;
//console.log("strip_length"+lane.strip_length);
//console.log("samplingRate"+lane.samplingRate);
//console.log("#samples: "+lane.numberOfSamples); //sometimes off
//console.log("rgbVector:"+rgb.length);
var xLabels=range(rgb.length);
var ctx = document.getElementById("graph").getContext("2d");
var r_data=[];
var g_data=[];
var b_data=[];
for (var colors in rgb){
r_data[colors]=rgb[colors].r;
g_data[colors]=rgb[colors].g;
b_data[colors]=rgb[colors].b;
}
//console.log(r_data);
var data = {
labels: xLabels,
datasets: [
{
label: "r values",
fillColor: "rgba(255,0,0,0.5)",
strokeColor: "rgba(255,0,0,0.8)",
highlightFill: "rgba(255,0,0,0.75)",
highlightStroke: "rgba(255,0,0,1)",
data: r_data
},
{
label: "g values",
fillColor: "rgba(0,255,0,0.5)",
strokeColor: "rgba(0,255,0,0.8)",
highlightFill: "rgba(0,255,0,0.75)",
highlightStroke: "rgba(0,255,0,1)",
data: g_data
},
{
label: "b values",
fillColor: "rgba(0,0,255,0.5)",
strokeColor: "rgba(0,0,255,0.8)",
highlightFill: "rgba(0,0,255,0.75)",
highlightStroke: "rgba(0,0,255,1)",
data: b_data
}
]
};
$("#chartTitle").text("RGB values for each sampled band for lane#"+laneIndex);
var chart=new Chart(ctx).Bar(data,Chart.defaults);
};
//input event for graph textbox
function input(){
var laneNumber=$("#laneNo").val();
if (laneNumber>=0 || laneNumber<laneData.length){
graph(laneNumber);
} else{
alert("Please enter a number between 0 and "+laneData.length);
}
};
//************************** END GRAPH RESULTS ****************************************
//************************** DEBUGGING TOOLS ******************************************
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
var mouseX = evt.clientX - rect.left;
var mouseY = evt.clientY - rect.top;
var p = context.getImageData(mouseX, mouseY, 1, 1).data;
hsl = rgbToHsl(p[0],p[1],p[2]);
return {
x: mouseX,
y: mouseY,
r: p[0],
g: p[1],
b: p[2],
h: hsl.h * 360,
s: hsl.s,
l: hsl.l
};
}
canvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
var message = 'Mouse position: ' + mousePos.x + ', ' + mousePos.y +
" : Color: " + mousePos.r+ ', ' +mousePos.g+ ', ' +mousePos.b+
" : HSL: "+mousePos.h.toFixed(2)+ ', ' +mousePos.s.toFixed(2)+ ', ' +mousePos.l.toFixed(2)+" isRed: "+isRed({r:mousePos.r, g:mousePos.g, b:mousePos.b});
$("#mousePos").text(message);
}, false);
var troubleShoot=function(err){
Android.troubleShoot(err);
}
//********************** END DEBUGGING TOOLS ******************************************
function findRedRegions(laneSignal){
var regions=[];
var region={};
region.parentLaneLen=laneSignal.rgbVector.length;
var rgbVector=laneSignal.rgbVector;
region.rgbVector=[];
var foundRegionStart=false;
for (var i=0; i<rgbVector.length; i++){
console.log(isRedDiff(rgbVector[i],20));
if (isRedDiff(rgbVector[i],20)){
if (!foundRegionStart){
foundRegionStart=true;
region.startIndex=i;
region.rgbVector.push(rgbVector[i]);
} else{
region.rgbVector.push(rgbVector[i]);
}
} else{
if (foundRegionStart){
foundRegionStart=false;