-
Notifications
You must be signed in to change notification settings - Fork 0
/
circles.html
823 lines (740 loc) · 33.6 KB
/
circles.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
<html>
<head>
<script type="text/javascript">
<!--
// https://github.com/mrdoob/three.js/wiki/How-to-run-things-locally
// https://github.com/cmisenas/canny-edge-detection
// http://ru.wikipedia.org/wiki/%D0%94%D0%B8%D1%84%D1%84%D0%B5%D1%80%D0%B5%D0%BD%D1%86%D0%B8%D0%B0%D0%BB%D1%8C%D0%BD%D0%B0%D1%8F_%D0%B3%D0%B5%D0%BE%D0%BC%D0%B5%D1%82%D1%80%D0%B8%D1%8F_%D0%BA%D1%80%D0%B8%D0%B2%D1%8B%D1%85
function sqr(x) { return x*x; }
function abs(x) { return x >= 0 ? x : -x; }
function sign(x) {return x >= 0 ? 1 : -1; }
function min(a, b) { return a < b ? a : b; }
function max(a, b) { return a > b ? a : b; }
function ss(x1, y1, x2, y2) { return x1*x2 + y1*y2; }
function module(x, y) { return Math.sqrt(x*x + y*y); }
function module2(x, y) { return x*x + y*y; }
function rotS(edge, i) {
var DY1 = edge.y[i] - edge.y[i - 1];
var DX1 = edge.x[i] - edge.x[i - 1];
var DY2 = edge.y[i+1] - edge.y[i];
var DX2 = edge.x[i+1] - edge.x[i];
return (DY1*DX2 - DY2*DX1); // /(module(DX1, DY1) * module(DX2, DY2));
}
// { Canvas
function Canvas(id, w, h, res) {
this.elem = document.getElementById(id);
this.width = w || 600;
this.height = h || 400;
if (this.elem === null) {
this.elem = document.createElement('canvas');
this.elem.id = id;
this.elem.width = this.width;
this.elem.height = this.height;
document.body.insertBefore(this.elem, document.body.firstChild);
}
this.ctx = this.elem.getContext('2d');
this.images = [];
this.currentImg = {};
var resizable = res || true;
if (resizable === true) {
this.elem.onmouseover = this.resize;
this.elem.onmouseout = function() {
this.style.cursor = 'auto';
};
}
}
Canvas.prototype.resize = function(e) {
if (e.pageX === this.offsetLeft && e.pageY !== this.offsetTop) {
this.style.cursor = 'w-resize';
} else if (e.pageX !== this.offsetLeft && e.pageY === this.offsetTop) {
this.style.cursor = 'n-resize';
} else if (e.pageX === this.offsetLeft + this.width - 1 && e.pageY !== this.offsetTop + this.height - 1) {
this.style.cursor = 'e-resize';
} else if (e.pageX !== this.offsetLeft + this.width - 1 && e.pageY === this.offsetTop + this.height - 1) {
this.style.cursor = 's-resize';
}
};
Canvas.prototype.loadImg = function(img, sx, sy) {
this.images.push(img);
this.currentImg.index = this.images.indexOf(img);
var that = this;
var usrImg = new Image();
usrImg.onload = function() {
var maxSize = 8000;
var maxISize = max(usrImg.width, usrImg.height);
if (maxISize > maxSize) {
usrImg.width = ~~(usrImg.width * maxSize/maxISize);
usrImg.height = ~~(usrImg.height * maxSize/maxISize);
}
if (usrImg.width !== that.width || usrImg.height !== that.height) {
that.width = usrImg.width;
that.height = usrImg.height;
that.elem.width = that.width;
that.elem.height = that.height;
}
that.ctx.drawImage(usrImg, sx || 0, sy || 0, usrImg.width, usrImg.height);
that.currentImg.imgData = that.ctx.getImageData(0, 0, that.elem.width, that.elem.height);
if (that.onImageLoaded) {
that.onImageLoaded();
}
};
usrImg.src = img;
return this;
};
Canvas.prototype.runImg = function(size, fn) {
var that = this;
for (var y = 0; y < this.height; y++) {
for (var x = 0; x < this.width; x++) {
var i = x * 4 + y * this.width * 4;
var matrix = getMatrix(x, y, size);
fn(i, matrix);
}
}
function getMatrix(cx, cy, size) {//will generate a 2d array of size x size given center x, center y, size, image width & height
var matrix = [];
for (var i = 0, y = -(size-1)/2; i < size; i++, y++) {
matrix[i] = [];
for (var j = 0, x = -(size-1)/2; j < size; j++, x++) {
matrix[i][j] = (cx + x) * 4 + (cy + y) * that.width * 4;
}
}
return matrix;
}
};
Canvas.prototype.copyImageData = function(src) {
var dst = this.ctx.createImageData(src.width, src.height);
dst.data.set(src.data);
return dst;
};
Canvas.prototype.setPixel = function(i, val, imgData) {
imgData.data[i] = typeof val == 'number'? val: val.r;
imgData.data[i + 1] = typeof val == 'number'? val: val.g;
imgData.data[i + 2] = typeof val == 'number'? val: val.b;
};
Canvas.prototype.getPixel = function(i, imgData) {
if (i < 0 || i > imgData.data.length - 4) {
return {r: 255, g: 255, b: 255, a: 255};
} else {
return {r: imgData.data[i], g: imgData.data[i + 1], b: imgData.data[i + 2], a: imgData.data[i + 3] };
}
};
// } Canvas
// { Canny
function Canny(canvElem) {
var canvas = canvElem;
this.grayscale = function(imgData) {
var imgDataCopy = canvas.copyImageData(imgData);
console.time('Grayscale Time');
canvas.runImg(null, function(current) {
var grayLevel = (0.3 * imgDataCopy.data[current]) + (0.59 * imgDataCopy.data[current + 1]) + (0.11 * imgDataCopy.data[current + 2]);
canvas.setPixel(current, grayLevel, imgDataCopy);
});
console.timeEnd('Grayscale Time');
return imgDataCopy;
};
this.gaussianBlur = function(imgData, sigma, size) {
var imgDataCopy = canvas.copyImageData(imgData);
var that = this;
var kernel = generateKernel(sigma, size);
console.time('Blur Time');
canvas.runImg(size, function(current, neighbors) {
var resultR = 0;
var resultG = 0;
var resultB = 0;
for (var i = 0; i < size; i++) {
for (var j = 0; j < size; j++) {
var pixel = canvas.getPixel(neighbors[i][j], imgData);
resultR += pixel.r * kernel[i][j];//return the existing pixel value multiplied by the kernel matrix
resultG += pixel.g * kernel[i][j];
resultB += pixel.b * kernel[i][j];
}
}
canvas.setPixel(current, {r: resultR, g: resultG, b: resultB}, imgDataCopy);
});
console.timeEnd('Blur Time');
function generateKernel(sigma, size) {
var matrix = [];
var E = 2.718;//Euler's number rounded of to 3 places
for (var y = -(size - 1)/2, i = 0; i < size; y++, i++) {
matrix[i] = [];
for (var x = -(size - 1)/2, j = 0; j < size; x++, j++) {
//create matrix round to 3 decimal places
matrix[i][j] = 1/(2 * Math.PI * Math.pow(sigma, 2)) * Math.pow(E, -(Math.pow(Math.abs(x), 2) + Math.pow(Math.abs(y), 2))/(2 * Math.pow(sigma, 2)));
}
}
//normalize the matrix to make its sum 1
var normalize = 1/that.sum(matrix);
for (var k = 0; k < matrix.length; k++) {
for (var l = 0; l < matrix[k].length; l++) {
matrix[k][l] = Math.round(normalize * matrix[k][l] * 1000)/1000;
}
}
return matrix;
}
return imgDataCopy;
};
this.sobel = function(imgData) {//find intensity gradient of image
var imgDataCopy = canvas.copyImageData(imgData);
var dirMap = [];
var gradMap = [];
//perform vertical convolution
var xfilter =
[[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]];
//perform horizontal convolution
var yfilter =
[[1, 2, 1],
[0, 0, 0],
[-1, -2, -1]];
console.time('Sobel Filter Time');
canvas.runImg(3, function(current, neighbors) {
var edgeX = 0;
var edgeY = 0;
if (checkCornerOrBorder(current, imgDataCopy.width, imgDataCopy.height) === false) {
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
edgeX += imgData.data[neighbors[i][j]] * xfilter[i][j];
edgeY += imgData.data[neighbors[i][j]] * yfilter[i][j];
}
}
}
var dir = roundDir(Math.atan2(edgeY, edgeX) * (180/Math.PI));
dirMap[current] = dir;
var grad = Math.round(Math.sqrt(edgeX * edgeX + edgeY * edgeY));
gradMap[current] = grad;
canvas.setPixel(current, grad, imgDataCopy);
});
console.timeEnd('Sobel Filter Time');
function checkCornerOrBorder(i, width, height) {//returns true if a pixel lies on the border of an image
return i - (width * 4) < 0 || i % (width * 4) === 0 || i % (width * 4) === (width * 4) - 4 || i + (width * 4) > width * height * 4;
}
function roundDir(deg) {//rounds degrees to 4 possible orientations: horizontal, vertical, and 2 diagonals
deg = deg < 0 ? deg + 180 : deg;
var roundVal;
if ((deg >= 0 && deg <= 22.5) || (deg > 157.5 && deg <= 180)) {
roundVal = 0;
} else if (deg > 22.5 && deg <= 67.5) {
roundVal = 45;
} else if (deg > 67.5 && deg <= 112.5) {
roundVal = 90;
} else if (deg > 112.5 && deg <= 157.5) {
roundVal = 135;
}
return roundVal;
}
imgDataCopy.dirMap = dirMap;
imgDataCopy.gradMap = gradMap;
return imgDataCopy;
};
this.nonMaximumSuppress = function(imgData) {
var imgDataCopy = canvas.copyImageData(imgData);
console.time('NMS Time');
canvas.runImg(3, function(current, neighbors) {
var pixNeighbors = getNeighbors(imgData.dirMap[current]);
//pixel neighbors to compare
var pix1 = imgData.gradMap[neighbors[pixNeighbors[0].x][pixNeighbors[0].y]];
var pix2 = imgData.gradMap[neighbors[pixNeighbors[1].x][pixNeighbors[1].y]];
if (pix1 > imgData.gradMap[current] || pix2 > imgData.gradMap[current]) {//suppress
canvas.setPixel(current, 0, imgDataCopy);
} else if (pix2 === imgData.gradMap[current] && pix1 < imgData.gradMap[current]) {
canvas.setPixel(current, 0, imgDataCopy);
}
});
console.timeEnd('NMS Time');
function getNeighbors(dir) {
var degrees = {0 : [{x:1, y:2}, {x:1, y:0}], 45 : [{x: 0, y: 2}, {x: 2, y: 0}], 90 : [{x: 0, y: 1}, {x: 2, y: 1}], 135 : [{x: 0, y: 0}, {x: 2, y: 2}]};
return degrees[dir];
}
return imgDataCopy;
};
this.hysteresis = function(imgData, d){ //mark strong and weak edges, discard others as false edges; only keep weak edges that are connected to strong edges
var that = this;
return function() {
var imgDataCopy = canvas.copyImageData(imgData);
var realEdges = []; //where real edges will be stored with the 1st pass
var t2 = 127 - d; //low threshold value
var t1 = 127 + d; //high threshold value
//first pass
console.time('Hysteresis Time');
canvas.runImg(null, function(current) {
if (imgData.data[current] > t1 && realEdges[current] === undefined) {//accept as a definite edge
var group = that.traverseEdge(current, imgData, t2, []);
for(var i = 0; i < group.length; i++){
realEdges[group[i]] = true;
}
}
});
//second pass
canvas.runImg(null, function(current) {
if (realEdges[current] === undefined) {
canvas.setPixel(current, 0, imgDataCopy);
} else {
canvas.setPixel(current, 255, imgDataCopy);
}
});
console.timeEnd('Hysteresis Time');
return imgDataCopy;
};
};
this.invertColors = function(imgData) {
var imgDataCopy = canvas.copyImageData(imgData);
console.time('Invert Colors Time');
canvas.runImg(null, function(current) {
canvas.setPixel(current, {r: 255 - imgDataCopy.data[current], g: 255 - imgDataCopy.data[current + 1], b: 255 - imgDataCopy.data[current + 2]}, imgDataCopy);
});
console.timeEnd('Invert Colors Time');
return imgDataCopy;
};
this.showDirMap = function(imgData) {//just a quick function to look at the direction results
return function() {
var imgDataCopy = canvas.copyImageData(imgData);
canvas.runImg(null, function(i) {
if (imgData.dirMap[i] === 0) {
canvas.setPixel(i, {r: 255, g: 0, b: 0}, imgDataCopy);
} else if (imgData.dirMap[i] === 45) {
canvas.setPixel(i, {r: 0, g: 255, b: 0}, imgDataCopy);
} else if (imgData.dirMap[i] === 90) {
canvas.setPixel(i, {r: 0, g: 0, b: 255}, imgDataCopy);
} else if (imgData.dirMap[i] === 135) {
canvas.setPixel(i, {r: 255, g: 255, b: 0}, imgDataCopy);
} else {
canvas.setPixel(i, {r: 255, g: 0, b: 255}, imgDataCopy);
}
});
return imgDataCopy;
};
};
this.showGradMap = function(imgData) {
return function() {
var imgDataCopy = canvas.copyImageData(imgData);
canvas.runImg(null, function(i) {
if (imgData.gradMap[i] < 0) {
canvas.setPixel(i, {r: 255, g: 0, b: 0}, imgDataCopy);
} else if (imgData.gradMap[i] < 200) {
canvas.setPixel(i, {r: 0, g: 255, b: 0}, imgDataCopy);
} else if (imgData.gradMap[i] < 400) {
canvas.setPixel(i, {r: 0, g: 0, b: 255}, imgDataCopy);
} else if (imgData.gradMap[i] < 600) {
canvas.setPixel(i, {r: 255, g: 255, b: 0}, imgDataCopy);
} else if (imgData.gradMap[i] < 800) {
canvas.setPixel(i, {r: 0, g: 255, b: 255}, imgDataCopy);
} else {
canvas.setPixel(i, {r: 255, g: 0, b: 255}, imgDataCopy);
}
});
return imgDataCopy;
};
};
//helper functions
this.sum = function(arr) {//receives an array and returns sum
var result = 0;
for (var i = 0; i < arr.length; i++) {
if (/^\s*function Array/.test(String(arr[i].constructor)))
{
result += this.sum(arr[i]);
} else {
result += arr[i];
}
}
return result;
};
this.traverseEdge = function(current, imgData, threshold, traversed) {//traverses the current pixel until a length has been reached
var group = [current]; //initialize the group from the current pixel's perspective
var neighbors = this.getNeighborEdges(current, imgData, threshold, traversed);//pass the traversed group to the getNeighborEdges so that it will not include those anymore
for(var i = 0; i < neighbors.length; i++){
group = group.concat(this.traverseEdge(neighbors[i], imgData, threshold, traversed.concat(group)));//recursively get the other edges connected
}
return group; //if the pixel group is not above max length, it will return the pixels included in that small pixel group
};
this.getNeighborEdges = function(i, imgData, threshold, includedEdges) {
var neighbors = [];
var directions = [
i + 4, //e
i - imgData.width * 4 + 4, //ne
i - imgData.width * 4, //n
i - imgData.width * 4 - 4, //nw
i - 4, //w
i + imgData.width * 4 - 4, //sw
i + imgData.width * 4, //s
i + imgData.width * 4 + 4 //se
];
for(var j = 0; j < directions.length; j++)
if(imgData.data[directions[j]] >= threshold && (includedEdges === undefined || includedEdges.indexOf(directions[j]) === -1))
neighbors.push(directions[j]);
return neighbors;
};
this.getAllEdges = function(imgData) {
var that = this;
var traversed = [];
var edges = [];
console.time('Get Edges Time');
canvas.runImg(null, function(current) {
if (imgData.data[current] === 255 && traversed[current] === undefined) {//assumes that an edge has white value
var group = that.traverseEdge(current, imgData, 255, []);
edges.push(group);
for(var i = 0; i < group.length; i++){
traversed[group[i]] = true;
}
}
});
console.timeEnd('Get Edges Time');
return edges;
};
}
// } Canny
function createFragments(offsetEdges, width) {
var edges = new Array(offsetEdges.length);
var lineSize = width*4;
for(var i = 0; i < offsetEdges.length; ++i){
var offsetEdge = offsetEdges[i];
var arX = new Array(offsetEdge.length);
var arY = new Array(offsetEdge.length);
for(var k = 0; k < offsetEdge.length; ++k) {
var pos = offsetEdge[k];
arX[k] = (pos % lineSize) / 4;
arY[k] = ~~(pos / lineSize);
}
edges[i] = {x:arX, y:arY, length:offsetEdge.length};
}
return edges;
}
function avg(edge, i, r) {
var cX = 0;
var cY = 0;
var collected = 0;
for(var k = max(0, i-r); k < min(edge.length, i+r); ++k) {
cX += edge.x[k];
cY += edge.y[k];
++collected;
}
return {x:cX/collected, y:cY/collected};
}
function smoothFragments(edges, r) {
var sedges = [];
var sedges_pos = 0;
for(var i = 0; i < edges.length; ++i){
var edge = edges[i];
var arSize = edge.length - 2*r;
if (arSize <= 0)
continue;
var arX = new Array(arSize);
var arY = new Array(arSize);
var sedge_pos = 0;
for(var k = r; k < edge.length - r; ++k) {
var p = avg(edge, k, r);
arX[sedge_pos] = p.x;
arY[sedge_pos] = p.y;
++sedge_pos;
}
sedges[sedges_pos++] = {x:arX, y:arY, length:sedge_pos};
}
return sedges;
}
function splitByJumpsFragments(edges, dist) {
var dist2 = dist * dist;
var sedges = [];
var sedges_pos = 0;
for(var i = 0; i < edges.length; ++i){
var edge = edges[i];
var arX = [edge.x[0]];
var arY = [edge.y[0]];
var sedge_pos = 1;
for(var k = 1; k < edge.length; ++k) {
var sdist2 = sqr(edge.x[k] - edge.x[k-1]) + sqr(edge.y[k] - edge.y[k-1]);
if (sdist2 >= dist2) {
if (sedge_pos > 3)
sedges[sedges_pos++] = {x:arX, y:arY, length:sedge_pos};
sedge_pos = 0;
arX = [];
arY = [];
}
arX[sedge_pos] = edge.x[k];
arY[sedge_pos] = edge.y[k];
++sedge_pos;
}
if (sedge_pos >= 3)
sedges[sedges_pos++] = {x:arX, y:arY, length:sedge_pos};
}
return sedges;
}
function splitByRotFragments(edges) {
var sedges = [];
var sedges_pos = 0;
for(var i = 0; i < edges.length; ++i){
var edge = edges[i];
if (edge.length < 3)
continue;
var arX = [edge.x[0], edge.x[1]];
var arY = [edge.y[0], edge.y[1]];
var sedge_pos = 2;
var prevRot = rotS(edge, 1);
for(var k = 2; k < edge.length - 1; ++k) {
var rot = rotS(edge, k);
if (rot*prevRot < 0 && sedge_pos > 31) {
if (sedge_pos > 3)
sedges[sedges_pos++] = {x:arX, y:arY, length:sedge_pos};
sedge_pos = 0;
arX = [];
arY = [];
}
prevRot = rot;
arX[sedge_pos] = edge.x[k];
arY[sedge_pos] = edge.y[k];
++sedge_pos;
}
if (sedge_pos >= 3)
sedges[sedges_pos++] = {x:arX, y:arY, length:sedge_pos};
}
return sedges;
}
function drawEdges(edges, canvas) {
var colors = ["#F00", "#FF0", "#F0F", "#0FF"];
for(var i = 0; i < edges.length; ++i){
var edge = edges[i];
canvas.ctx.strokeStyle = colors[i % colors.length];
canvas.ctx.beginPath();
canvas.ctx.moveTo(edge.x[0], edge.y[0]);
for(var k = 1; k < edge.length; ++k) {
canvas.ctx.lineTo(edge.x[k], edge.y[k]);
canvas.ctx.arc(edge.x[k], edge.y[k], 2, 0, 2*Math.PI);
}
canvas.ctx.stroke();
}
}
var ic = 0;
function getCircle(x, y, imgData) {
var N = x.length;
if (N < 32)
return null;
var Rmax = min(imgData.height, imgData.width)/4;
var s = {x:0, y:0, r:4};
for (var i = 0; i < N; ++i) {
s.x += x[i];
s.y += y[i];
}
s.x /= N;
s.y /= N;
for (var u = 0; u < 32; ++u) {
var A = [[0,0,0], [0,0,0], [0,0,0]];
var b = [0,0,0];
for (var i = 0; i < N; ++i) {
var xi = x[i], yi = y[i];
var dx = xi - s.x, dy = yi - s.y;
var dx2 = dx*dx, dy2 = dy*dy, dxdy = dx * dy;
var R = Math.sqrt(dx2 + dy2);
if (R == 0) R = 1;
var R2 = R*R;
var rR = s.r/R, dxR = dx/R, dyR = dy/R;
var rR3 = rR/R2;
A[0][0] += rR3*dx2 - rR + 1; A[0][1] += rR3*dxdy; A[0][2] += dxR;
/*A[1][0] = A[0][1];*/ A[1][1] += rR3*dy2 - rR + 1; A[1][2] += dyR;
/*A[2][0] = A[0][2];*/ /*A[2][1] = A[1][2];*/ /*A[1][2] += 1;*/
b[0] += (1 - rR) * dx;
b[1] += (1 - rR) * dy;
b[2] += R - s.r;
}
A[1][0] = A[0][1]; A[2][0] = A[0][2]; A[2][1] = A[1][2]; A[2][2] = N;
var determinant = +A[0][0]*[A[1][1]*A[2][2]-A[2][1]*A[1][2]]
-A[0][1]*[A[1][0]*A[2][2]-A[1][2]*A[2][0]]
+A[0][2]*[A[1][0]*A[2][1]-A[1][1]*A[2][0]];
if (determinant == 0)
return null;
var invdet = 1/determinant;
// invert transponed
var r = [[0,0,0], [0,0,0], [0,0,0]];
r[0][0] = (A[1][1]*A[2][2]-A[2][1]*A[1][2])*invdet;
r[1][0] = -(A[0][1]*A[2][2]-A[0][2]*A[2][1])*invdet;
r[2][0] = (A[0][1]*A[1][2]-A[0][2]*A[1][1])*invdet;
r[0][1] = -(A[1][0]*A[2][2]-A[1][2]*A[2][0])*invdet;
r[1][1] = (A[0][0]*A[2][2]-A[0][2]*A[2][0])*invdet;
r[2][1] = -(A[0][0]*A[1][2]-A[1][0]*A[0][2])*invdet;
r[0][2] = (A[1][0]*A[2][1]-A[2][0]*A[1][1])*invdet;
r[1][2] = -(A[0][0]*A[2][1]-A[2][0]*A[0][1])*invdet;
r[2][2] = (A[0][0]*A[1][1]-A[1][0]*A[0][1])*invdet;
var d = [
r[0][0] * b[0] + r[0][1] * b[1] + r[0][2] * b[2],
r[1][0] * b[0] + r[1][1] * b[1] + r[1][2] * b[2],
r[2][0] * b[0] + r[2][1] * b[1] + r[2][2] * b[2],
];
s.x += d[0];
s.y += d[1];
s.r += d[2];
if (s.r <= 0)
return null;
if (s.r > Rmax)
break;
}
s.x = ~~s.x;
s.y = ~~s.y;
s.r = ~~s.r;
return checkColor(s, imgData);
}
function checkColor(c, imgData) {
var cRed = 0;
var cGreen = 0;
var cBlue = 0;
var r2 = sqr(c.r);
var lineSize = imgData.width*4;
var minX = max(0, c.x - c.r - 1);
var maxX = min(imgData.width, c.x + c.r + 1);
var minY = max(0, c.y - c.r - 1);
var maxY = min(imgData.height, c.y + c.r + 1);
var data = imgData.data;
var index = new Array(sqr(2*(c.r + 1)));
var pointCount = 0;
for (var x = minX; x < maxX; ++x) {
for (var y = minY; y < maxY; ++y) if ( module2(x - c.x, y - c.y) < r2 ) {
var offset = lineSize*y + x*4;
index[pointCount++] = offset;
cRed += data[offset];
cGreen += data[++offset];
cBlue += data[++offset];
}
}
if (pointCount > 0) {
cRed /= pointCount;
cGreen /= pointCount;
cBlue /= pointCount;
}
c.color = "rgba(" + (~~cRed) + "," + (~~cGreen) + "," + (~~cBlue) + ", 0.3)";
var error = 0;
for (var i = 0; i < pointCount; ++i) {
var offset = index[i];
var dr = data[offset] - cRed;
var dg = data[++offset] - cGreen;
var db = data[++offset] - cBlue;
error += Math.sqrt(sqr(dr) + sqr(dg) + sqr(db));
}
c.error = error;
c.errorU = error/pointCount;
console.log(++ic + 'x:' + c.x + ' y:' + c.y + ' r:' + c.r + ' c:' + c.errorU);
return c;
}
function getFillColor(imgData) {
var cRed = 0;
var cGreen = 0;
var cBlue = 0;
var data = imgData.data;
for (var offset = 0; offset < data.length; offset+=4) {
cRed += data[offset];
cGreen += data[offset + 1];
cBlue += data[offset + 2];
}
var norm = Math.sqrt(3*sqr(127))/Math.sqrt(sqr(cRed) + sqr(cGreen) + sqr(cBlue));
/*
if (data.length > 0) {
cRed /= data.length;
cGreen /= data.length;
cBlue /= data.length;
}
*/
if (data.length > 0) {
cRed *= norm;
cGreen *= norm;
cBlue *= norm;
}
return "rgb(" + (~~cRed) + "," + (~~cGreen) + "," + (~~cBlue) + ")";
}
//heap
function heap_check(ar, heap_size, i, key)
{
if (i < heap_size) {
var max = i;
var left = 2*i + 1;
var right = 2*(i + 1);
if (left < heap_size && key(ar[left]) > key(ar[max]))
max = left;
if (right < heap_size && key(ar[right]) > key(ar[max]))
max = right;
if (max != i) {
var temp = ar[i];
ar[i] = ar[max];
ar[max] = temp;
heap_check(ar, heap_size, max, key);
}
}
}
function heap_build(ar, count, key)
{
for (var i = Math.floor(count/2); i >=0; --i) {
heap_check(ar, count, i, key);
}
}
function heap_sort(ar, count, key) //O(n * ln(n))
{
heap_build(ar, count, key);
for (var i = count - 1; i >= 0; --i) {
var max = ar[0];
ar[0] = ar[i];
ar[i] = max;
heap_check(ar, i, 0, key);
}
}
function drawCircles(circles, canvas, bkColor) {
for(var i = 0; i < circles.length; ++i){
var circle = circles[i];
canvas.ctx.beginPath();
canvas.ctx.arc(circle.x, circle.y, circle.r, 0, 2*Math.PI, false);
canvas.ctx.fillStyle = (bkColor != null) ? bkColor : circle.color;
canvas.ctx.fill();
canvas.ctx.strokeStyle = canvas.ctx.fillStyle;
//canvas.ctx.strokeStyle = colors[i % colors.length];
canvas.ctx.stroke();
}
}
function getBestCircles(edges, imgData) {
var circles = [];
var circleCount = 0;
for(var i = 0; i < edges.length; ++i){
var edge = edges[i];
var circle = getCircle(edge.x, edge.y, imgData);
if (circle!=null/*&& circle.errorU < 50*/) {
circles[circleCount++] = circle;
}
}
heap_sort(circles, circleCount, function(circle) { return 1/circle.error; } );
return circles;
}
function init() {
var img = document.getElementById('imageS');
new Canvas("image").loadImg(img.src).onImageLoaded = function() {
var canvas = this;
var canny = new Canny(this);
var currentImgData = canvas.ctx.getImageData(0, 0, canvas.width, canvas.height);
var newImgData =
canny.hysteresis(
canny.nonMaximumSuppress(
canny.sobel(
canny.grayscale(currentImgData)
)
)
, parseInt(document.getElementById("d").value))();
var edges =
splitByRotFragments(
smoothFragments(
splitByJumpsFragments(
createFragments(canny.getAllEdges(newImgData), canvas.width)
,16)
,8)
);
var circles = getBestCircles(edges, currentImgData);
canvas.ctx.beginPath();
canvas.ctx.fillStyle = getFillColor(currentImgData);
canvas.ctx.fillRect(0,0,canvas.width,canvas.height);
drawCircles(circles, canvas, null);
document.getElementById('imageD').src = document.getElementById('image').toDataURL("image/png");
};
}
-->
</script>
</head>
<body onload="init();">
<img id="imageS" src="lena4.jpg"/>
<canvas id="image">
</canvas>
<img id="imageD"/>
<input id="d" type="number" value="90"/><button onclick="init()">Redraw</button>
<div id="data"></div>
</body>
</html>