-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflame-monkey.js
3034 lines (2539 loc) · 86.7 KB
/
flame-monkey.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
// I guess this happens to be the first file which gets included
// so I might as well use this to write a message here for whoever
// ends up reading this
function uuid(){
for(var i = 0, s, b = ''; i < 42; i++)
if(/\w/i.test(s = String.fromCharCode(48 + Math.floor(75 * Math.random())))) b += s;
return b;
}
/**
* Display an image in the console.
* @param {string} url The url of the image.
* @param {int} scale Scale factor on the image
* @return {null}
* http://dunxrion.github.io
*/
console.image = function(url, log) {
var img = new Image();
function getBox(width, height) {
return {
string: "+",
style: "font-size: 1px; padding: " + Math.floor(height/2) + "px " + Math.floor(width/2) + "px; line-height: " + height + "px;"
}
}
img.onload = function() {
var dim = getBox(this.width, this.height);
console.log(log, url)
console.log("%c" + dim.string, dim.style + "background: url(" + url + "); background-size: " + (this.width) + "px " + (this.height) + "px; color: transparent;");
};
img.src = url;
};
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
// requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
// MIT license
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
|| window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
var global_params = {
ocrad_worker: 'js/ocrad-worker.js',
swt_worker: 'js/swt-worker.js',
inpaint_worker: 'js/inpaint-worker.js',
mask_worker: 'js/mask-worker.js',
num_workers: 2,
is_extension: true,
queue_expires: 1000 * 2, // two seconds
user_id: null
}
// maybe a better spot for this would be in default_params
// TODO: figure out how the params system shoudl work
function load_user_id(){
chrome.storage.sync.get(['user_id'], function(value){
if(value['user_id']){
global_params.user_id = value['user_id'];
}else{
chrome.storage.sync.set({'user_id': uuid()}, function(){
load_user_id()
})
}
})
}
load_user_id()
var storage_cache = {
warn_ocrad: true
};
function load_settings(){
chrome.storage.sync.get(['settings'], function(val){
var settings = val['settings']
// console.log('loaded settings', settings)
if(settings){
for(var i in settings){
storage_cache[i] = settings[i];
}
}else{
save_settings()
}
})
}
chrome.storage.onChanged.addListener(function(changes, namespace){
load_settings()
})
load_settings()
function get_setting(name){ return storage_cache[name] }
function save_settings(){
// console.log('save settings', storage_cache)
chrome.storage.sync.set({
settings: storage_cache
})
}
function put_setting(name, val){
storage_cache[name] = val;
save_settings()
}
function broadcast(data){
// window.parent.postMessage(data, '*')
if(data.id){
var parts = data.id.split("@#")
// hopefully this isn't a security issue
var tabId = parseInt(parts[1], 10);
// console.log('sending data to', data.id, data)
data.id = parts[0]
chrome.tabs.sendMessage(tabId, data)
}else{
console.error("dont know where this data will be sent", data)
}
}
// window.addEventListener('message', function(e){
// receive(e.data)
// })
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
// sender.tab.id
if(request.id){
// console.log(sender.tab.id, request)
// request.id = sender.tab.id + "#/" + request.id
request.id += "@#" + sender.tab.id;
receive(request)
}else{
console.error("dont know where this data comes from", request)
}
});
function inject_clipboard(region, ocr){
var original = getClipboard();
var incomplete = 0;
var modified = substitute_recognition(original, function(region_id){
if(region.id == region_id){
// woot
return {
region: region,
ocr: ocr
}
}
incomplete++;
return null;
})
if(incomplete == 0){
// yay were done
clipboard_watch = 0
}
if(original != modified){
// omg changedzorz
setClipboard(modified)
}
}
// http://stackoverflow.com/questions/6969403/cant-get-execcommandpaste-to-work-in-chrome
function getClipboard() {
var pasteTarget = document.createElement("div");
pasteTarget.contentEditable = true;
var actElem = document.activeElement.appendChild(pasteTarget).parentNode;
pasteTarget.focus();
document.execCommand("Paste", null, null);
var paste = pasteTarget.innerText;
actElem.removeChild(pasteTarget);
return paste;
};
// https://coderwall.com/p/5rv4kq
function setClipboard(text){
var copyDiv = document.createElement('div');
copyDiv.contentEditable = true;
document.body.appendChild(copyDiv);
copyDiv.innerText = text;
copyDiv.unselectable = "off";
copyDiv.focus();
document.execCommand('SelectAll');
document.execCommand("Copy", false, null);
document.body.removeChild(copyDiv);
}
var chunk_queue = [];
var chunk_processing = [];
var image_cache = {};
var image_cache_loading = {};
var client_id = "naptha006_" + uuid();
var clipboard_watch = 0;
var real_srcs = {}
function im(id){
if(!(id in images)){
throw "Error: image (" +id+" ) does not exist"
}
var image = images[id];
if(!img_ready(image.src)){
return null
}
var img = img_get(image.src);
var params = image.params;
if(!image.initialized){
image.width = Math.round(img.naturalWidth * params.scale)
image.height = Math.round(img.naturalHeight * params.scale)
image.processed = []
image.regions = []
image.initialized = true;
}
return image;
}
function img_ready(src){
var LOAD_TIMEOUT = 1000;
var MAX_CONCURRENT = 3;
if(src in image_cache){
delete image_cache_loading[src];
return true;
}else if(src in image_cache_loading){
return false;
}else{
var now = Date.now(), count = 0
for(var key in image_cache_loading){
var ts = image_cache_loading[key]
if(now - ts > LOAD_TIMEOUT){
delete image_cache_loading[key]
}else{
count++
}
}
if(count < MAX_CONCURRENT){
var img = new Image();
img.src = real_srcs[src] || src;
if(!img.complete){
image_cache_loading[src] = Date.now()
img.onload = function(){
var load_end = Date.now()
console.log(src, 'loaded in ', load_end - image_cache_loading[src])
image_cache[src] = img;
delete image_cache_loading[src];
}
}else{
image_cache[src] = img;
console.log(src, 'loaded instantaneously')
return true;
}
}
}
return false;
}
function img_get(src){
if(img_ready(src)) return image_cache[src];
throw "Image not yet ready"
}
// it takes an input in terms of natural cordinates
function img_cut(src, scale, x0, y0, w, h){
var img = img_get(src)
var canvas = document.createElement('canvas')
// w = Math.min(img.naturalWidth - Math.floor(x0), w)
// h = Math.min(img.naturalHeight - Math.floor(y0), h)
canvas.width = Math.floor(w * scale)
canvas.height = Math.floor(h * scale)
var ctx = canvas.getContext('2d')
// ctx.fillStyle = 'white'
// ctx.fillStyle = 'rgb(155, 51, 181)'
ctx.fillStyle = 'rgb(250,254,252)'
ctx.fillRect(0, 0, canvas.width, canvas.height)
var sx = (x0), sy = (y0);
// firefox doesnt allow drawing an image with a negative
// source start index
var offx = Math.max(0, -sx),
offy = Math.max(0, -sy);
var remx = Math.max(0, (sx + (w)) - img.naturalWidth),
remy = Math.max(0, (sy + (h)) - img.naturalHeight);
// the area immediately under the area of interest is painted
// white, for images which have semitransparent backgrounds
ctx.fillStyle = 'white';
ctx.fillRect(Math.round(offx * scale), Math.round(offy * scale),
canvas.width - Math.round(offx * scale + remx * scale),
canvas.height - Math.round(offy * scale + remy * scale))
ctx.drawImage(img, Math.round(sx + offx), Math.round(sy + offy),
Math.round(w - offx - remx), Math.round(h - offy - remy), // swidth, sheight
Math.round(offx * scale), Math.round(offy * scale),
canvas.width - Math.round(offx * scale + remx * scale),
canvas.height - Math.round(offy * scale + remy * scale))
// console.image(canvas.toDataURL('image/png'))
var im = ctx.getImageData(0, 0, canvas.width, canvas.height)
delete ctx;
delete canvas;
return im;
}
function scaled_cut(src, scale, x0, y0, w, h){
var img = img_get(src)
var canvas = document.createElement('canvas')
canvas.width = w
canvas.height = h
var ctx = canvas.getContext('2d')
ctx.fillStyle = 'rgb(250,254,252)'
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(
img,
Math.round(x0 / scale), Math.round(y0 / scale), // sx, sy
Math.round(w / scale),
Math.round(h / scale), // swidth, sheight
0, 0, // x, y
canvas.width, canvas.height // width, height
);
var im = ctx.getImageData(0, 0, canvas.width, canvas.height)
// console.image(ctx.canvas.toDataURL('image/png'))
delete ctx;
delete canvas;
return im;
}
var images = {};
function broadcast_image(image){
// console.log(image)
// in theory, things have certain listners so that only if you subscribe to a given
// id, you'd receive a message like this
// window.parent.postMessage({
// regions: image.regions,
// id: image.id,
// chunks: Object.keys(image.processed)
// .filter(function(e){ return image.processed[e] })
// .map(function(e){ return parseInt(e) })
// }, '*')
broadcast({
type: 'region',
regions: image.regions,
id: image.id,
stitch_debug: image.stitch_debug,
chunks: Object.keys(image.processed)
.filter(function(e){ return image.processed[e] })
.map(function(e){ return parseInt(e) })
})
}
function receive(data){
if(data.type == 'qchunk'){
if(data.id in images){
var image = im(data.id);
var chunks = image ? data.chunks.filter(function(e){
return !(e in image.processed)
}) : data.chunks;
if(chunks.length > 0){
chunk_queue.unshift([data.id, chunks, data.time]);
touch_scheduler();
}
}else{
broadcast({
id: data.id,
type: 'getparam',
initial_chunk: [data.id, data.chunks, data.time]
})
}
}else if(data.type == 'gotparam'){
if(!(data.id in images)){
images[data.id] = {
params: data.params,
id: data.id,
src: data.src
}
real_srcs[data.src] = data.real_src;
if(data.initial_chunk){
chunk_queue.unshift(data.initial_chunk);
touch_scheduler();
}
console.log('creating a new image', data.id)
}
}else if(data.type == 'qocr'){
queue_ocr(data)
}else if(data.type == 'qpaint'){
queue_paint(data)
}else if(data.type == 'clipwatch'){
clipboard_watch = Date.now()
}else if(data.type == 'copy'){
if(typeof setClipboard == 'function'){
setClipboard(data.text)
}else{
alert("can not save to clipboard on platform")
}
}else{
console.log('unknown data packet', data.type, data)
}
}
function queue_ocr(data){
// queue the generation of some kind of mask out of the thing
// console.log(data.region)
// var image = im(data.id)
// scaled_cut(image.src, scale, x0, y0, w, h)
var col = data.region;
var avg_height = (col.original || col.lines).map(function(e){ return e.lineheight })
.sort(function(a, b){ return a - b })[Math.floor(col.lines.length / 2)]; // take median
var colscale = Math.min(10, Math.max(1, 100 / avg_height));
// console.log('running ocr', data.reg_id)
console.time('computing mask')
var xpad = 5;
var ypad = 5;
mask_region(data.src, col, colscale, data.swtscale, data.swtwidth, xpad, ypad, function(output){
console.timeEnd('computing mask')
var mask = output.mask;
// console.log('colors', output.colors)
console.time("rotating stuff")
var tmp = document.createElement('canvas')
tmp.width = mask.cols;
tmp.height = mask.rows;
var tmx = tmp.getContext('2d')
console.log(mask)
var out = tmx.createImageData(mask.cols, mask.rows)
for(var i = 0; i < mask.cols * mask.rows; i++){
out.data[i * 4 + 3] = 255
out.data[i * 4] = out.data[i * 4 + 1] = out.data[i * 4 + 2] = mask.data[i] ? 0 : 255
}
tmx.putImageData(out, 0, 0)
var reduce = 0.9;
var rot = document.createElement('canvas')
rot.width = Math.round(mask.cols * reduce);
rot.height = Math.round(mask.rows * reduce);
var rox = rot.getContext('2d')
rox.fillStyle = 'white'
rox.fillRect(0, 0, rot.width, rot.height)
rox.translate(rot.width / 2, rot.height / 2)
rox.rotate(-col.angle)
rox.drawImage(tmp, -rot.width / 2, -rot.height / 2, rot.width, rot.height)
console.timeEnd("rotating stuff")
// console.image(rot.toDataURL('image/png'))
var meta = {
v: 3,
id: col.id,
x0: col.x0,
y0: col.y0,
x1: col.x1,
y1: col.y1,
ang: col.angle,
dir: col.direction,
red: reduce,
cos: colscale,
sws: data.swtscale,
xp: xpad,
yp: ypad
};
if(data.engine == 'ocrad'){
var worker = new Worker(global_params.ocrad_worker)
worker.onmessage = function(e){
var raw = parseOcrad({ meta: meta, raw: e.data.raw });
broadcast({
type: 'recognized',
id: data.id,
reg_id: data.reg_id,
text: e.data.text,
engine: data.engine,
raw: raw
})
if(Date.now() - clipboard_watch < 1000 * 60 && typeof inject_clipboard == 'function'){
// clipboard watch runs for 1 minutes
inject_clipboard(col, { raw: raw })
}
}
worker.postMessage({
img: rox.getImageData(0, 0, rot.width, rot.height),
invert: false
})
}else if(data.engine.slice(0, 5) == 'tess:'){
console.time('blobifying')
rot.toBlob(function(blob){
var formData = new FormData();
formData.append("engine", data.engine);
// formData.append("user", "naptha.js on localhost");
formData.append('user', global_params.user_id)
formData.append("url", data.src);
formData.append("meta", JSON.stringify(meta));
formData.append("channel", client_id)
formData.append("image", blob, 'sample.png');
var request = new XMLHttpRequest();
request.open("POST", data.apiroot + "upload");
request.send(formData);
request.onerror = function(e){
// console.log(request, e)
broadcast({
type: 'recognized',
enc: 'error',
id: data.id,
reg_id: data.reg_id,
engine: data.engine,
text: "Error: Network error connecting to remote character recognition service"
})
}
request.onload = function(){
broadcast({
type: 'recognized',
enc: 'tesseract',
id: data.id,
reg_id: data.reg_id,
engine: data.engine,
text: request.responseText
})
if(Date.now() - clipboard_watch < 1000 * 60 && typeof inject_clipboard == 'function'){
// clipboard watch runs for 1 minutes
var raw = parseTesseract(JSON.parse(request.responseText))
inject_clipboard(col, { raw: raw })
}
}
}, 'image/png')
console.timeEnd('blobifying')
}else{
console.warn("no recognized ocr engine available")
}
})
}
var WORKERCOUNT = 0;
function process_queue(){
var found_chunk;
// go through the chunk queue looking for something which
// appears to be loaded and can be processed and then uh
// do the processing on said chunk
for(var i = 0; i < chunk_queue.length && !found_chunk; i++){
var job = chunk_queue[i];
if(!job) continue;
var id = job[0];
if(!(id in images) || !img_ready(images[id].src)) continue;
if(job[1].length == 0){ chunk_queue[i] = null; continue; }
var assigned = job[2];
if(assigned < Date.now() - global_params.queue_expires) continue;
// var image = images[id];
var image = im(id);
var params = image.params;
var num_chunks = Math.max(1, Math.ceil((image.height - params.chunk_overlap) / (params.chunk_size - params.chunk_overlap)));
while(job[1].length > 0 && !found_chunk){
// console.log(job)
// if(typeof job[1][0] == 'number'){
// job[1].unshift(to_chunks(job[1].shift() * params.scale, image))
// }
// if(job[1][0].length == 0){
// job[1].shift(); // this set of chunks is done
// continue;
// }
var chunk = job[1].shift();
if(
chunk >= 0 &&
chunk < num_chunks &&
isFinite(chunk) &&
// !(chunk in image.processing) &&
!chunk_processing.some(function(e){
return e[0] == id && e[1] == chunk
}) &&
!(chunk in image.processed)
){
found_chunk = true;
}
}
}
chunk_queue = chunk_queue.filter(function(e){ return e }); // get rid of the blank ones
if(!found_chunk) return; // future unclear; try again later
chunk_processing.push([id, chunk]);
// image.processing[chunk] = 1;
// console.log(images[id].height, chunk, (params.chunk_size - params.chunk_overlap) * chunk)
var offset = chunk * (params.chunk_size - params.chunk_overlap);
function save_lines(lines){
lines.forEach(function(line, index){
line.y0 += offset; line.y1 += offset; line.cy += offset;
line.chunk = chunk;
line.letters.forEach(function(e){
e.y0 += offset; e.y1 += offset; e.cy += offset;
})
})
var has_before = lines.some(function(line){
var cy = line.cy - (params.chunk_size - params.chunk_overlap) * chunk;
return !(cy >= params.chunk_overlap / 2 || chunk == 0)
})
var has_after = lines.some(function(line){
var cy = line.cy - (params.chunk_size - params.chunk_overlap) * chunk;
return !(cy < params.chunk_size - params.chunk_overlap / 2 || chunk == num_chunks - 1)
})
if(has_before) chunk_queue.push([id, [chunk - 1], assigned]);
if(has_after) chunk_queue.push([id, [chunk + 1], assigned]);
// console.log('has before/after', has_before, has_after, chunk, JSON.stringify(chunk_queue, null, ' '));
image.processed[chunk] = lines
chunk_processing = chunk_processing.filter(function(e){
return !(e[0] == id && e[1] == chunk)
})
touch_scheduler()
// delete image.processing[chunk]
update_regions(image);
}
var worker = new Worker(global_params.swt_worker);
worker.onmessage = function(e){
var msg = e.data;
// console.log('done', src, chunk, found_chunk)
if(msg.action == 'swtdat'){
worker.terminate();
save_lines(msg.lines)
}else if(msg.action == 'vizmat'){
visualize_matrix(msg.matrix, msg.letters)
console.log('matrix visualizations not implemented')
}else if(msg.action == 'grouptask'){
console.groupCollapsed(msg.logs.slice(-1)[0][1], chunk)
msg.logs.slice(0, -1).forEach(function(e){
if(e[0] == '$end'){
console.groupEnd()
}else if(e[0] == '$start'){
console.groupCollapsed(e[1])
}else if(e[0] == '$log'){
console.log(e[1])
}
})
console.groupEnd()
}
}
var chunk_height = Math.min(params.chunk_size, image.height - (params.chunk_size - params.chunk_overlap) * chunk);
// var dat = img_cut(
// image.src, params.scale,
// 0, offset / params.scale,
// Infinity, chunk_height / params.scale
// );
// var canvas = document.createElement('canvas')
// canvas.width = image.width
// canvas.height = image.height
// var ctx = canvas.getContext('2d')
// ctx.drawImage(img_get(image.src), 0, 0, canvas.width, canvas.height)
// var dat = ctx.getImageData(0, offset, image.width, chunk_height);
// convert this into an img_cut?
var dat = scaled_cut(
image.src, params.scale,
0, offset,
image.width, chunk_height
);
// var blah = document.createElement('canvas')
// blah.width = image.width
// blah.height = chunk_height
// var dat = blah.getContext('2d').createImageData(image.width, chunk_height)
// console.log(dat, image.width, offset, chunk_height)
// var im = images[id].context.getImageData(0, offset, images[id].width, chunk_height);
// show_image_data(im)
// console.log(chunk, id, im)
worker.postMessage({
action: 'swt',
imageData: dat,
params: image.params
})
// var lines = partial_swt(im, swt_params);
}
function update_regions(image){
var params = image.params;
var num_chunks = Math.max(1, Math.ceil((image.height - params.chunk_overlap) / (params.chunk_size - params.chunk_overlap)))
var valid_lines = []
var process_count = 0;
// for(var i = 0; i < num_chunks; i++){
// var before = image.processed[i - 1],
// lines = image.processed[i],
// after = image.processed[i + 1];
// }
// var blah = document.createElement('canvas')
// blah.width = image.width
// blah.height = image.height
// var ctx = blah.getContext('2d')
// ctx.drawImage(img_get(image.src), 0, 0, image.width, image.height)
// num_chunks
image.processed.forEach(function(lines, chunk){
var line_counter = 0;
process_count++
lines.forEach(function(line){
// line.id = line_counter++;
line.id = chunk.toString(36) + ':' + (line_counter++).toString(36)
})
})
// image.processed.forEach(function(lines, chunk){
// process_count++
// lines.forEach(function(line){
// line.id = line_counter++;
// var cy = line.cy - (params.chunk_size - params.chunk_overlap) * chunk;
// var is_before = (cy < params.chunk_overlap / 2 && chunk != 0);
// var is_after = (cy >= params.chunk_size - params.chunk_overlap / 2 && chunk != num_chunks - 1);
// // ctx.strokeStyle = 'green'
// // ctx.strokeRect(line.x0, line.y0, line.width, line.height)
// if(!is_before && !is_after)
// valid_lines.push(line);
// });
// });
function intersects(a, b){
var width = Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0),
height = Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0);
// return width > 0 && height > 0
return width > Math.min(a.width, b.width) * 0.7 &&
height > Math.min(a.height, b.height) * 0.7
}
// basically what this does, is it goes through each chunk
// and searches for all the intersections with the previous remainder
// for the intersecting lines, it picks the set which has a certain
// desireable trait, for the elements of the remainder with no
// intersections with the current, we add those to the valid lines
// list, and all the other non-matches comprise the remainder
// for the next iteration
var last = image.processed[0]
var orphaned_lines = [];
for(var i = 1; i < num_chunks; i++){
var n = 1;
var lines = (image.processed[i] || []).filter(function(line){
var offset = line.chunk * (params.chunk_size - params.chunk_overlap)
var dist_top = Math.max(0, line.y0 - offset),
dist_bot = Math.max(0, (offset + params.chunk_size) - line.y1);
// return Math.min(dist_top, dist_bot) > 1
return true
}).map(function(line){
return { geom: line, id: n++}
});
var prev = ((image.processed[i - 1] ? last : null) || []).map(function(line){
return { geom: line, id: n++}
});
var forest = new UnionFind(n)
lines.forEach(function(a){
prev.forEach(function(b){
if(intersects(a.geom, b.geom) && a.geom.direction == b.geom.direction){
// set a = b
forest.link(a.id, b.id)
}
})
})
var groups = {};
lines.forEach(function(e){
var name = forest.find(e.id)
if(!(name in groups)) groups[name] = { cur: [], prev: [] };
groups[name].cur.push(e.geom)
})
prev.forEach(function(e){
var name = forest.find(e.id)
if(!(name in groups)) groups[name] = { cur: [], prev: [] };
groups[name].prev.push(e.geom)
})
function margin(lines){
return Math.min.apply(Math, lines.map(function(line){
var offset = line.chunk * (params.chunk_size - params.chunk_overlap)
var dist_top = Math.max(0, line.y0 - offset),
dist_bot = Math.max(0, (offset + params.chunk_size) - line.y1);
return Math.min(dist_top, dist_bot)
}))
}
function alt_metric(lines){
// return lines.map(function(line){
// return line.size
// }).reduce(function(a, b){ return a + b })
// return lines.reduce(function(a, b){
// return a.lettercount + b.lettercount
// })
return Math.max.apply(Math, lines.map(function(line){
return line.lettercount
}))
}
var new_last = []
for(var j in groups){
var g = groups[j];
if(g.cur.length == 0){
valid_lines = valid_lines.concat(g.prev)
}else if(g.prev.length == 0){
new_last = new_last.concat(g.cur)
}else{
var cur_margin = margin(g.cur),
pre_margin = margin(g.prev);
// pick the line which is furthest away from the chunk boundary
var proximity = (alt_metric(g.cur) - alt_metric(g.prev)) / (alt_metric(g.prev) + alt_metric(g.cur))
if(Math.min(cur_margin, pre_margin) < params.chunk_size / 4 && proximity < 0.5){
valid_lines = valid_lines.concat(cur_margin > pre_margin ? g.cur : g.prev)
orphaned_lines = orphaned_lines.concat(cur_margin < pre_margin ? g.cur : g.prev)
}else{
// unless they're both safe, in which case, we pick the one which has moar pixels
var cur_alt = alt_metric(g.cur),
pre_alt = alt_metric(g.prev);
valid_lines = valid_lines.concat(cur_alt > pre_alt ? g.cur : g.prev)
orphaned_lines = orphaned_lines.concat(cur_alt < pre_alt ? g.cur : g.prev)
}
}
}
last = new_last
}
valid_lines = valid_lines.concat(last)
image.stitch_debug = orphaned_lines.map(function(line){
return {x0: line.x0, y0: line.y0, width: line.width, height: line.height,
direction: line.direction, type: 'orphan'}
}).concat(valid_lines.map(function(line){
return {x0: line.x0, y0: line.y0, width: line.width, height: line.height,
direction: line.direction, type: 'valid'}
}));
// var blah = document.createElement('canvas')
// blah.width = image.width
// blah.height = image.height
// var ctx = blah.getContext('2d')
// ctx.drawImage(img_get(image.src), 0, 0, image.width, image.height)
// ctx.lineWidth = 2;
// orphaned_lines.forEach(function(line){
// ctx.strokeStyle = 'blue'
// ctx.strokeRect(line.x0, line.y0, line.width, line.height);
// })
// valid_lines.forEach(function(line){
// ctx.strokeStyle = 'red'
// ctx.strokeRect(line.x0, line.y0, line.width, line.height);
// })
// console.image(blah.toDataURL('image/png'))
// var blah = document.createElement('canvas')
// blah.width = image.width
// blah.height = image.height
// var ctx = blah.getContext('2d')
// ctx.drawImage(img_get(image.src), 0, 0, image.width, image.height)
// ctx.lineWidth = 2;
// orphaned_lines.forEach(function(line){
// ctx.strokeStyle = 'yellow'
// if(line.direction < 0) ctx.strokeRect(line.x0, line.y0, line.width, line.height);
// })
// valid_lines.forEach(function(line){
// ctx.strokeStyle = 'green'
// if(line.direction < 0) ctx.strokeRect(line.x0, line.y0, line.width, line.height);
// })
// console.image(blah.toDataURL('image/png'))
// visualize_matrix(valid)
// console.log(valid_lines)
// ctx.strokeStyle = 'black'
// valid_lines.forEach(function(line){
// ctx.strokeRect(line.x0, line.y0, line.width, line.height)
// })
// console.image(blah.toDataURL('image/png'))
// image.regions = new_regions
// Ximage = image
function set_regions(regions){
image.regions = regions.filter(function(col){
return col.lettercount > 2
}).sort(function(a, b){