-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathcbl.js
1479 lines (1336 loc) · 69.3 KB
/
cbl.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
/*
* CBL-js
* CAPTCHA Breaking Library in JavaScript
* https://github.com/skotz/cbl-js
* Copyright (c) 2015-2021 Scott Clayton
*/
var CBL = function (options) {
var defaults = {
preprocess: function() { warn("You should define a preprocess method!"); },
model_file: "",
model_string: "",
model_loaded: function() { },
training_complete: function() { },
blob_min_pixels: 1,
blob_max_pixels: 99999,
blob_min_width: 1,
blob_min_height: 1,
blob_max_width: 99999,
blob_max_height: 99999,
pattern_width: 20,
pattern_height: 20,
pattern_maintain_ratio: false,
pattern_auto_rotate: false,
incorrect_segment_char: "\\",
blob_debug: "",
blob_console_debug: false,
allow_console_log: false,
allow_console_warn: true,
perceptive_colorspace: false,
character_set: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
fixed_blob_locations: [ ], // Expected format: [ { x1: 0, y1: 0, x2: 0, y2: 0 }, ... ]
exact_characters: -1,
exact_characters_width: -1, // Used to guess how many characters there are in a large blob
exact_characters_play: -1 // Used to find a good vertical split point when splitting by an exact number of characters
};
options = options || {};
for (var opt in defaults) {
if (defaults.hasOwnProperty(opt) && !options.hasOwnProperty(opt)) {
options[opt] = defaults[opt];
}
}
var obj = {
/***********************************************\
| General Methods |
\***********************************************/
// Load an image and attempt to solve it based on trained model
solve : function (el) {
return obj.train(el, true);
},
done : function (resultHandler) {
addQueue(function () {
resultHandler(doneResult);
runQueue();
});
},
// Load an image and attempt to solve it based on trained model
train : function (el, solving) {
if (typeof solving === 'undefined') {
solving = false;
}
addQueue(function() {
var image;
var needSetSrc = false;
if (document.getElementById(el) != null) {
image = document.getElementById(el);
} else {
image = document.createElement("img");
needSetSrc = true;
}
var afterLoad = function() {
var solution = "";
var canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext('2d').drawImage(image, 0, 0);
// Run user-specified image preprocessing
var cblImage = new cbl_image(canvas);
options.preprocess(cblImage);
// Run segmentation
var blobs;
if (options.fixed_blob_locations.length > 0) {
blobs = cblImage.segmentBlocks(options.pattern_width,
options.pattern_height,
options.fixed_blob_locations,
options.blob_debug);
} else {
blobs = cblImage.segmentBlobs(options.blob_min_pixels,
options.blob_max_pixels,
options.pattern_width,
options.pattern_height,
options.blob_debug);
}
// FOR TRAINING
// Set up a list of patterns for a human to classify
if (!solving) {
for (var i = 0; i < blobs.length; i++) {
var imgUrl = blobs[i].toDataURL();
var blobPattern = blobToPattern(blobs[i]);
pendingPatterns.push({
imgSrc: imgUrl,
pattern: blobPattern,
imgId: patternElementID,
txtId: humanSolutionElementID,
self: obj,
onComplete: options.training_complete
});
}
// Load first pattern
if (!currentlyTraining) {
obj.loadNextPattern();
}
currentlyTraining = true;
}
// FOR SOLVING
// Solve an image buy comparing each blob against our model of learned patterns
else {
for (var i = 0; i < blobs.length; i++) {
solution += findBestMatch(blobToPattern(blobs[i]));
}
log("Solution = " + solution);
}
doneResult = solution;
runQueue();
};
if (image.complete && !needSetSrc) {
afterLoad();
}
else {
image.onload = afterLoad;
// Set the source AFTER setting the onload
if (needSetSrc) {
image.src = el;
}
}
});
return this;
},
// Load the next pattern pending human classification
loadNextPattern: function() {
var nextPattern = pendingPatterns.pop();
if (nextPattern) {
log("Loading a pattern for human classification.");
openClassifierDialog();
document.getElementById(nextPattern.imgId).src = nextPattern.imgSrc;
document.getElementById(nextPattern.txtId).focus();
document.getElementById(nextPattern.txtId).onkeyup = function(event) {
var typedLetter = document.getElementById(nextPattern.txtId).value;
if ((options.character_set.indexOf(typedLetter) > -1 && typedLetter.length) || typedLetter == options.incorrect_segment_char) {
if (typedLetter != options.incorrect_segment_char) {
model.push({
pattern: nextPattern.pattern,
solution: document.getElementById(nextPattern.txtId).value
});
log("Added \"" + document.getElementById(nextPattern.txtId).value + "\" pattern to model!");
} else {
log("Did not add bad segment to model.");
}
document.getElementById(nextPattern.txtId).value = "";
// Load the next pattern
if (pendingPatterns.length) {
nextPattern.self.loadNextPattern();
}
else {
currentlyTraining = false;
document.getElementById(nextPattern.txtId).onkeyup = function () { };
if (typeof nextPattern.onComplete === 'function') {
nextPattern.onComplete();
closeClassifierDialog();
}
}
}
else {
document.getElementById(nextPattern.txtId).value = "";
}
};
}
},
// Load a model by deserializing a model string
loadModelString: function (modelString) {
modelString = LZString.decompressFromBase64(modelString);
model = new Array();
var patterns = modelString.replace(/\[/g, "").split("]");
for (var i = 0; i < patterns.length; i++) {
var parts = patterns[i].split("=");
if (parts.length == 2) {
var p = parts[1];
var s = parts[0];
model.push({
pattern: p,
solution: s
});
}
}
if (!model.length) {
warn("No patterns to load in provided model.");
}
else {
log("Model loaded with " + model.length + " patterns!");
options.model_loaded();
}
},
// Load a model from a file on the server
loadModel: function (url) {
try {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText) {
obj.loadModelString(xhr.responseText);
}
}
}
catch (err) {
warn("Could not load model from \"" + url + "\"! (" + err.message + ")");
}
},
// Serialize the model
serializeModel: function () {
var str = "";
for (var i = 0; i < model.length; i++) {
str += "[" + model[i].solution + "=" + model[i].pattern + "]";
}
str = LZString.compressToBase64(str);
return str;
},
// Save the model to a file
saveModel: function () {
var str = obj.serializeModel();
var anchor = document.createElement('a');
anchor.href = "data:application/octet-stream," + encodeURIComponent(str);
anchor.setAttribute('download', 'cbl-model.dat');
anchor.click();
},
// Debug stuff about the model
debugModel: function () {
for (var i = 0; i < model.length; i++) {
log(model[i].solution + " pattern length = " + model[i].pattern.split(".").length);
}
},
// Sort the model by pattern solution alphabetically
sortModel: function() {
model = model.sort(function(a, b) { return a.solution.localeCompare(b.solution); });
},
// Output the model as images to an element for debugging
visualizeModel: function (elementId) {
for (var m = 0; m < model.length; m++) {
var pattern = document.createElement('canvas');
pattern.width = options.pattern_width;
pattern.height = options.pattern_height;
var pctx = pattern.getContext('2d').getImageData(0, 0, options.pattern_width, options.pattern_height);
var patternValues = model[m].pattern.split('.');
for (var x = 0; x < options.pattern_width; x++) {
for (var y = 0; y < options.pattern_height; y++) {
var i = x * 4 + y * 4 * options.pattern_width;
var p = y + x * options.pattern_width;
pctx.data[i] = patternValues[p];
pctx.data[i + 1] = patternValues[p];
pctx.data[i + 2] = patternValues[p];
pctx.data[i + 3] = 255;
}
}
pattern.getContext('2d').putImageData(pctx, 0, 0);
var test = document.createElement("img");
test.src = pattern.toDataURL();
document.getElementById(elementId).appendChild(test);
}
},
// Condense the model by combining patterns with the same solution
condenseModel: function () {
var newModel = new Array();
var oldCount = model.length;
for (var i = 0; i < model.length; i++) {
var patternArray = model[i].pattern.split(".");
var found = false;
for (var j = 0; j < newModel.length; j++) {
// These two patterns have the same solution, so combine the patterns
if (newModel[j].solution == model[i].solution) {
for (var x = 0; x < newModel[j].tempArray.length; x++) {
newModel[j].tempArray[x] = parseInt(newModel[j].tempArray[x]) + parseInt(patternArray[x]);
}
newModel[j].tempCount++;
found = true;
break;
}
}
if (!found) {
newModel.push({
pattern: model[i].pattern,
solution: model[i].solution,
tempArray: patternArray,
tempCount: 1
});
}
}
// Normalize the patterns
for (var i = 0; i < newModel.length; i++) {
for (var x = 0; x < newModel[i].tempArray.length; x++) {
newModel[i].tempArray[x] = Math.round(newModel[i].tempArray[x] / newModel[i].tempCount);
}
newModel[i].pattern = newModel[i].tempArray.join(".");
}
model = newModel;
log("Condensed model from " + oldCount + " patterns to " + model.length + " patterns!");
return this;
}
};
var cbl_image = function (canvas) {
var obj = {
/***********************************************\
| Image Manipulation Methods |
\***********************************************/
// Fills each distinct region in the image with a different random color
colorRegions: function (tolerance, ignoreWhite, pixelJump) {
if (typeof ignoreWhite === 'undefined') {
ignoreWhite = false;
}
if (typeof pixelJump === 'undefined') {
pixelJump = 0;
}
var exclusions = new Array();
var image = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
for (var x = 0; x < image.width; x++) {
for (var y = 0; y < image.height; y++) {
var i = x * 4 + y * 4 * image.width;
if (!arrayContains(exclusions, i)) {
obj.floodfill(x, y, getRandomColor(), tolerance, image, exclusions, ignoreWhite, pixelJump);
}
}
}
canvas.getContext('2d').putImageData(image, 0, 0);
return this;
},
// Display an image in an image tag
display: function (el) {
document.getElementById(el).src = canvas.toDataURL();
return this;
},
// Displays the canvas as an image in another element
debugImage: function (debugElement) {
var test = document.createElement("img");
test.src = canvas.toDataURL();
document.getElementById(debugElement).appendChild(test);
return this;
},
// Flood fill a given color into a region starting at a certain point
floodfill: function (x, y, fillcolor, tolerance, image, exclusions, ignoreWhite, pixelJump) {
var internalImage = false;
if (typeof image === 'undefined') {
internalImage = true;
image = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
}
if (typeof pixelJump === 'undefined') {
pixelJump = 0;
}
var data = image.data;
var length = data.length;
var Q = [];
var i = (x + y * image.width) * 4;
var e = i, w = i, me, mw, w2 = image.width * 4;
var targetcolor = [data[i], data[i + 1], data[i + 2], data[i + 3]];
var targettotal = data[i] + data[i + 1] + data[i + 2] + data[i + 3];
if (!pixelCompare(i, targetcolor, targettotal, fillcolor, data, length, tolerance)) {
return false;
}
Q.push(i);
while (Q.length) {
i = Q.pop();
if (typeof exclusions !== 'undefined') {
if (arrayContains(exclusions, i)) {
continue;
}
}
if (pixelCompareAndSet(i, targetcolor, targettotal, fillcolor, data, length, tolerance, exclusions, ignoreWhite)) {
e = i;
w = i;
mw = (i / w2) * w2;
me = mw + w2;
while (mw < (w -= 4) && pixelCompareAndSet(w, targetcolor, targettotal, fillcolor, data, length, tolerance, exclusions, ignoreWhite));
while (me > (e += 4) && pixelCompareAndSet(e, targetcolor, targettotal, fillcolor, data, length, tolerance, exclusions, ignoreWhite));
if (pixelJump > 0) {
// Skip over a certain number of pixels that don't match
w -= pixelJump * 4;
e += pixelJump * 4;
}
for (var j = w; j < e; j += 4) {
if (j - w2 >= 0 && pixelCompare(j - w2, targetcolor, targettotal, fillcolor, data, length, tolerance)) {
Q.push(j - w2);
}
if (j + w2 < length && pixelCompare(j + w2, targetcolor, targettotal, fillcolor, data, length, tolerance)) {
Q.push(j + w2);
}
}
}
}
if (internalImage) {
canvas.getContext('2d').putImageData(image, 0, 0);
}
},
// Blur the image (box blur)
blur : function (level) {
if (typeof level === 'undefined') {
level = 1;
}
if (level == 2) {
return this.convolute([ [1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1] ], 1.0/25);
}
else if (level == 3) {
return this.convolute([ [1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1] ], 1.0/49);
}
else {
return this.convolute([ [1, 1, 1],
[1, 1, 1],
[1, 1, 1] ], 1.0/9);
}
},
// Sharpen
sharpen : function () {
return this.convolute([ [ 0, -1, 0],
[-1, 5, -1],
[ 0, -1, 0] ]);
},
// Convert the image to grayscale
grayscale : function () {
var image = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
for (var x = 0; x < image.width; x++) {
for (var y = 0; y < image.height; y++) {
var i = x * 4 + y * 4 * image.width;
var brightness = 0.34 * image.data[i] + 0.5 * image.data[i + 1] + 0.16 * image.data[i + 2];
image.data[i] = brightness;
image.data[i + 1] = brightness;
image.data[i + 2] = brightness;
image.data[i + 3] = 255;
}
}
canvas.getContext('2d').putImageData(image, 0, 0);
return this;
},
// Change all semi-gray colors to white
removeGray : function (tolerance) {
var image = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
for (var x = 0; x < image.width; x++) {
for (var y = 0; y < image.height; y++) {
var i = x * 4 + y * 4 * image.width;
var diff = Math.max(Math.abs(image.data[i] - image.data[i + 1]),
Math.abs(image.data[i + 1] - image.data[i + 2]),
Math.abs(image.data[i + 2] - image.data[i]));
if (diff < tolerance) {
image.data[i] = 255;
image.data[i + 1] = 255;
image.data[i + 2] = 255;
image.data[i + 3] = 255;
}
}
}
canvas.getContext('2d').putImageData(image, 0, 0);
return this;
},
// Change all colors above a certain brightness to white
removeLight : function (brightness) {
var image = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
for (var x = 0; x < image.width; x++) {
for (var y = 0; y < image.height; y++) {
var i = x * 4 + y * 4 * image.width;
var diff = Math.max(image.data[i], image.data[i + 1], image.data[i + 2]);
if (diff > brightness) {
image.data[i] = 255;
image.data[i + 1] = 255;
image.data[i + 2] = 255;
image.data[i + 3] = 255;
}
}
}
canvas.getContext('2d').putImageData(image, 0, 0);
return this;
},
// Convert the image to black and white given a grayscale threshold
binarize : function (threshold) {
var image = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
for (var x = 0; x < image.width; x++) {
for (var y = 0; y < image.height; y++) {
var i = x * 4 + y * 4 * image.width;
var brightness = 0.34 * image.data[i] + 0.5 * image.data[i + 1] + 0.16 * image.data[i + 2];
image.data[i] = brightness >= threshold ? 255 : 0;
image.data[i + 1] = brightness >= threshold ? 255 : 0;
image.data[i + 2] = brightness >= threshold ? 255 : 0;
image.data[i + 3] = 255;
}
}
canvas.getContext('2d').putImageData(image, 0, 0);
return this;
},
// Apply a convolution filter
convolute : function (matrix, factor) {
var image = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
var out = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
var w = matrix[0].length;
var h = matrix.length;
var half = Math.floor(h / 2);
if (typeof factor === 'undefined') {
factor = 1;
}
var bias = 0;
for (var y = 0; y < image.height - 1; y++) {
for (var x = 0; x < image.width - 1; x++) {
var px = x * 4 + y * 4 * image.width;
var r = 0;
var g = 0;
var b = 0;
for (var cy = 0; cy < w; cy++) {
for (var cx = 0; cx < h; cx++) {
var cpx = ((y + (cy - half)) * image.width + (x + (cx - half))) * 4;
r += image.data[(cpx + image.data.length) % image.data.length] * matrix[cy][cx];
g += image.data[(cpx + 1 + image.data.length) % image.data.length] * matrix[cy][cx];
b += image.data[(cpx + 2 + image.data.length) % image.data.length] * matrix[cy][cx];
}
}
out.data[px + 0] = factor * r + bias;
out.data[px + 1] = factor * g + bias;
out.data[px + 2] = factor * b + bias;
out.data[px + 3] = 255;
}
}
canvas.getContext('2d').putImageData(out, 0, 0);
return this;
},
// Apply an erosion filter
erode : function () {
return this.convolute([ [-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1] ]);
},
// Apply an specific filter to each pixel
// The filter method should accept and return one parameter that will have three properties: r, g, and b
// foreach(function (p) { return p; })
foreach : function (filter) {
var image = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
for (var x = 0; x < image.width; x++) {
for (var y = 0; y < image.height; y++) {
var i = x * 4 + y * 4 * image.width;
var pixel = { r: image.data[i + 0], g: image.data[i + 1], b: image.data[i + 2] };
pixel = filter(pixel);
image.data[i + 0] = pixel.r;
image.data[i + 1] = pixel.g;
image.data[i + 2] = pixel.b;
image.data[i + 3] = 255;
}
}
canvas.getContext('2d').putImageData(image, 0, 0);
return this;
},
// Replace transparent pixels with a solid color
removeTransparency : function (opacity, color) {
if (typeof opacity === 'undefined') {
opacity = 128;
}
if (typeof color === 'undefined') {
color = { r: 255, g: 255, b: 255 };
}
var image = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
for (var x = 0; x < image.width; x++) {
for (var y = 0; y < image.height; y++) {
var i = x * 4 + y * 4 * image.width;
if (image.data[i + 3] <= opacity) {
image.data[i + 0] = color.r;
image.data[i + 1] = color.g;
image.data[i + 2] = color.b;
image.data[i + 3] = 255;
}
}
}
canvas.getContext('2d').putImageData(image, 0, 0);
return this;
},
// Invert the color of every pixel
invert : function (filter) {
return this.foreach(function (p) {
p.r = 255 - p.r;
p.g = 255 - p.g;
p.b = 255 - p.b;
return p;
});
},
// Crop an image
cropRelative : function (left, top, right, bottom) {
var image = canvas.getContext('2d').getImageData(left, top, canvas.width - left - right, canvas.height - top - bottom);
canvas.width = canvas.width - left - right;
canvas.height = canvas.height - top - bottom;
canvas.getContext('2d').putImageData(image, 0, 0);
return this;
},
// Remove a horizontal line from the image (must span the entire picture width)
removeHorizontalLine : function (lineWidth, color) {
if (typeof color === 'undefined') {
color = { r: 0, g: 0, b: 0 };
}
if (typeof lineWidth === 'undefined') {
lineWidth = 1;
}
var image = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
var play = [ 0, -1, 1 ];
// Get all the possible line starts
var starts = [];
for (var y = 0; y < canvas.height; y++) {
var pixel = this.getPixel(0, y);
if (pixel.r == color.r && pixel.g == color.g && pixel.b == color.b) {
starts.push({ x: 0, y: y });
}
}
// Get all the possible line ends
var ends = [];
for (var y = 0; y < canvas.height; y++) {
var pixel = this.getPixel(canvas.width - 1, y);
if (pixel.r == color.r && pixel.g == color.g && pixel.b == color.b) {
ends.push({ x: canvas.width - 1, y: y });
}
}
// Find a line which connects at least one start with at least one end (with the fewest vertical movements possible)
var self = this;
var maxSearch = 10000;
var dead = [];
var search = function (x, y, line) {
if (false) {
// Debug
var i = x * 4 + y * 4 * image.width;
image.data[i + 0] = 255;
image.data[i + 1] = 0;
image.data[i + 2] = 0;
image.data[i + 3] = 255;
}
if (maxSearch-- <= 0) {
return null;
}
var allLines = [];
var copy = JSON.parse(JSON.stringify(line));
copy.points.push({ x: x, y: y });
if (x >= canvas.width - 1 && ends.some(function (e) { return e.x == copy.points[copy.points.length - 1].x && e.y == copy.points[copy.points.length - 1].y; })) {
return copy;
}
var pixel = self.getPixel(x, y);
if (pixel.r != color.r || pixel.g != color.g || pixel.b != color.b) {
return null;
}
for (var d = 0; d < play.length; d++) {
if (y + play[d] >= 0 && y + play[d] < canvas.height) {
copy.vertical += Math.abs(play[d]);
if (dead.some(function (e) { return e.x == x + 1 && e.y == y + play[d]; })) {
// Don't revisit dead nodes
continue;
}
var subLine = search(x + 1, y + play[d], copy);
if (subLine != null) {
allLines.push(subLine);
// Return the first one we find
return subLine;
} else {
dead.push({ x: x + 1, y: y + play[d] });
}
}
}
return allLines && allLines.length ? allLines.reduce(function (a, b) { return a.vertical < b.vertical ? a : b; }) : null;
};
// Remove the lines
for (var s = 0; s < starts.length; s++) {
var line = search(starts[s].x, starts[s].y, { points: [], vertical: 0 });
if (line && line.points) {
for (var p = 0; p < line.points.length; p++) {
for (var w = -lineWidth; w <= lineWidth; w++) {
var i = line.points[p].x * 4 + (line.points[p].y + w) * 4 * image.width;
var k = line.points[p].x * 4 + (line.points[p].y + w - 1) * 4 * image.width;
image.data[i + 0] = image.data[k + 0];
image.data[i + 1] = image.data[k + 1];
image.data[i + 2] = image.data[k + 2];
image.data[i + 3] = 255;
}
}
}
}
canvas.getContext('2d').putImageData(image, 0, 0);
return this;
},
/***********************************************\
| Image Helper Methods |
\***********************************************/
// Get the R, G, and B values of a pixel at a given location in the image
// Returned object is in the format { r: 0, g: 0, b: 0 }
getPixel : function (x, y) {
var image = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
var i = x * 4 + y * 4 * image.width;
var pixel = { r: image.data[i + 0], g: image.data[i + 1], b: image.data[i + 2] };
return pixel;
},
/***********************************************\
| Image Segmentation Methods |
\***********************************************/
// Cut the image into separate, pre-defined sections
segmentBlocks : function (segmentWidth, segmentHeight, segmentLocations, debugElement) {
if (typeof segmentWidth === 'undefined') {
segmentWidth = 20;
}
if (typeof segmentHeight === 'undefined') {
segmentHeight = 20;
}
if (typeof segmentLocations === 'undefined') {
segmentLocations = [ ];
}
var image = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
// Create blobs
var blobs = new Array();
for (var c = 0; c < segmentLocations.length; c++) {
var blob = document.createElement('canvas');
blob.width = image.width;
blob.height = image.height;
var blobContext = blob.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
var blobData = blobContext.data;
var pixels = 0;
var leftmost = segmentLocations[c].x1;
var rightmost = segmentLocations[c].x2;
var topmost = segmentLocations[c].y1;
var bottommost = segmentLocations[c].y2;
// Scale, crop, and resize blobs
var temp = document.createElement('canvas');
temp.width = rightmost - leftmost + 1;
temp.height = bottommost - topmost + 1;
temp.getContext('2d').putImageData(image, -leftmost, -topmost, leftmost, topmost, temp.width, temp.height);
blob.width = segmentWidth;
blob.height = segmentHeight;
if (options.pattern_maintain_ratio) {
var dWidth = temp.width;
var dHeight = temp.height;
if (dWidth / segmentWidth > dHeight / segmentHeight) {
// Scale width
blob.getContext('2d').drawImage(temp, 0, 0, segmentWidth, dHeight * (segmentWidth / dWidth));
}
else {
// Scale height
blob.getContext('2d').drawImage(temp, 0, 0, dWidth * (segmentHeight / dHeight), segmentHeight);
}
}
else {
// Stretch the image
blob.getContext('2d').drawImage(temp, 0, 0, segmentWidth, segmentHeight);
}
blobs.push(blob);
// Debugging help
if (typeof debugElement !== 'undefined' && debugElement.length) {
if (options.blob_console_debug) {
log("Blob size = " + pixels);
}
var test = document.createElement("img");
test.src = blob.toDataURL();
document.getElementById(debugElement).appendChild(test);
}
}
return blobs;
},
// Cut the image into separate blobs where each distinct color is a blob
segmentBlobs : function (minPixels, maxPixels, segmentWidth, segmentHeight, debugElement) {
if (typeof minPixels === 'undefined') {
minPixels = 1;
}
if (typeof maxPixels === 'undefined') {
maxPixels = 100000;
}
if (typeof segmentWidth === 'undefined') {
segmentWidth = 20;
}
if (typeof segmentHeight === 'undefined') {
segmentHeight = 20;
}
var image = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
var toColor = function (d, i) { return d[i] * 255 * 255 + d[i + 1] * 256 + d[i + 2]; };
var white = toColor([ 255, 255, 255 ], 0);
// Find distinct colors
var colors = new Array();
for (var x = 0; x < image.width; x++) {
for (var y = 0; y < image.height; y++) {
var i = x * 4 + y * 4 * image.width;
var rgb = toColor(image.data, i);
if (!arrayContains(colors, rgb) && rgb != white) {
colors.push(rgb);
}
}
}
// Create blobs
var blobs = new Array();
for (var c = 0; c < colors.length; c++) {
var blob = document.createElement('canvas');
blob.width = image.width;
blob.height = image.height;
var blobContext = blob.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
var blobData = blobContext.data;
var pixels = 0;
var leftmost = image.width;
var rightmost = 0;
var topmost = image.height;
var bottommost = 0;
for (var x = 0; x < image.width; x++) {
for (var y = 0; y < image.height; y++) {
var i = x * 4 + y * 4 * image.width;
var rgb = toColor(image.data, i);
if (rgb == colors[c]) {
blobData[i] = 0;
blobData[i + 1] = 0;
blobData[i + 2] = 0;
blobData[i + 3] = 255;
pixels++;
if (x < leftmost) {
leftmost = x;
}
if (x > rightmost) {
rightmost = x;
}
if (y < topmost) {
topmost = y;
}
if (y > bottommost) {
bottommost = y;
}
} else {
blobData[i] = 255;
blobData[i + 1] = 255;
blobData[i + 2] = 255;
blobData[i + 3] = 255;
}
}
}
// Only save blobs of a certain size
if (pixels >= minPixels && pixels <= maxPixels &&
rightmost - leftmost >= options.blob_min_width &&
bottommost - topmost >= options.blob_min_height &&
rightmost - leftmost <= options.blob_max_width &&
bottommost - topmost <= options.blob_max_height) {
// Scale, crop, and resize blobs
var temp = document.createElement('canvas');
temp.width = rightmost - leftmost + 1;
temp.height = bottommost - topmost + 1;
temp.getContext('2d').putImageData(blobContext, -leftmost, -topmost, leftmost, topmost, temp.width, temp.height);
blob.width = segmentWidth;
blob.height = segmentHeight;
blob.orig_width = temp.width;
blob.orig_image = temp;
if (options.pattern_maintain_ratio) {
var dWidth = temp.width;
var dHeight = temp.height;
if (dWidth / segmentWidth > dHeight / segmentHeight) {
// Scale width
blob.getContext('2d').drawImage(temp, 0, 0, segmentWidth, dHeight * (segmentWidth / dWidth));
}
else {
// Scale height
blob.getContext('2d').drawImage(temp, 0, 0, dWidth * (segmentHeight / dHeight), segmentHeight);
}
}
else {
// Stretch the image
blob.getContext('2d').drawImage(temp, 0, 0, segmentWidth, segmentHeight);
}
// Rotate the blobs using a histogram to minimize the width of non-white pixels
if (options.pattern_auto_rotate) {
blob = obj.histogramRotate(blob);
}
blobs.push(blob);
}
}
// Make sure we have exactly N blobs if we know there are N characters
if (options.exact_characters > 0) {
// Split the largest blob into two
while (blobs.length < options.exact_characters) {
var largestIndex = 0;
var largest = blobs[0].orig_width;
for (var i = 1; i < blobs.length; i++) {
if (blobs[i].orig_width > largest) {
largest = blobs[i].orig_width;
largestIndex = i;
}
}
// How many blobs should this one large blob be split into?
var resultingBlobs = 2;
if (options.exact_characters_width > 0) {
resultingBlobs = Math.ceil(largest / options.exact_characters_width);
resultingBlobs = Math.max(resultingBlobs, 2);
resultingBlobs = Math.min(resultingBlobs, options.exact_characters - blobs.length + 1);
}
for (var split = 1; split <= resultingBlobs; split ++) {
var splitSection = cloneCanvas(blobs[largestIndex].orig_image);
var blobContext = splitSection.getContext('2d').getImageData(0, 0, splitSection.width, splitSection.height);
var slice = splitSection.width / resultingBlobs;
leftmost = Math.floor(slice * (split - 1));
rightmost = Math.floor(slice * split);
topmost = 0;
bottommost = splitSection.height;
// How far to look for the best vertical split point
if (options.exact_characters_play > 0) {
// Find the best left cut
var bestLeft = 0;
var bestLeftX = 0;
for (var fpx = leftmost - options.exact_characters_play; fpx < leftmost + options.exact_characters_play; fpx++) {
var currentLeft = 0;
for (var fpy = topmost; fpy < bottommost; fpy++) {
var fpix = getPixel(blobContext, fpx, fpy);
if (fpix.r == 255 && fpix.g == 255 && fpix.b == 255) {
currentLeft++;
}
}
if (currentLeft > bestLeft) {