-
Notifications
You must be signed in to change notification settings - Fork 3
/
code2D.cpp
1172 lines (885 loc) · 37.4 KB
/
code2D.cpp
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
#include "code2D.h"
using namespace std;
using namespace cv;
using zxing::Ref;
using zxing::ArrayRef;
using zxing::LuminanceSource;
using namespace zxing;
using namespace datamatrix;
using namespace zxing::datamatrix;
//PopulateArrayFromMatrix : reg->sizeIdx
// - TallyModuleJumps: reg->offColor(=0), reg->onColor (=255), reg->flowBegin.plane (=0)
// - - ReadModuleColor : reg->fit2raw
// - - - dmtxDecodeGetPixelValue : dec->image (then general image data)
// /**
// * @struct DmtxRegion
// * @brief DmtxRegion
// */
// typedef struct DmtxRegion_struct {
// /* Trail blazing values */
// int jumpToPos; /* */
// int jumpToNeg; /* */
// int stepsTotal; /* */
// DmtxPixelLoc finalPos; /* */
// DmtxPixelLoc finalNeg; /* */
// DmtxPixelLoc boundMin; /* */
// DmtxPixelLoc boundMax; /* */
// DmtxPointFlow flowBegin; /* */
// /* Orientation values */
// int polarity; /* */
// int stepR;
// int stepT;
// DmtxPixelLoc locR; /* remove if stepR works above */
// DmtxPixelLoc locT; /* remove if stepT works above */
// /* Region fitting values */
// int leftKnown; /* known == 1; unknown == 0 */
// int leftAngle; /* hough angle of left edge */
// DmtxPixelLoc leftLoc; /* known (arbitrary) location on left edge */
// DmtxBestLine leftLine; /* */
// int bottomKnown; /* known == 1; unknown == 0 */
// int bottomAngle; /* hough angle of bottom edge */
// DmtxPixelLoc bottomLoc; /* known (arbitrary) location on bottom edge */
// DmtxBestLine bottomLine; /* */
// int topKnown; /* known == 1; unknown == 0 */
// int topAngle; /* hough angle of top edge */
// DmtxPixelLoc topLoc; /* known (arbitrary) location on top edge */
// int rightKnown; /* known == 1; unknown == 0 */
// int rightAngle; /* hough angle of right edge */
// DmtxPixelLoc rightLoc; /* known (arbitrary) location on right edge */
// /* Region calibration values */
// int onColor; /* */
// int offColor; /* */
// int sizeIdx; /* Index of arrays that store Data Matrix constants */
// int symbolRows; /* Number of total rows in symbol including alignment patterns */
// int symbolCols; /* Number of total columns in symbol including alignment patterns */
// int mappingRows; /* Number of data rows in symbol */
// int mappingCols; /* Number of data columns in symbol */
// /* Transform values */
// DmtxMatrix3 raw2fit; /* 3x3 transformation from raw image to fitted barcode grid */
// DmtxMatrix3 fit2raw; /* 3x3 transformation from fitted barcode grid to raw image */
// } DmtxRegion;
/*
std::string doDmtxDecode(const Mat &matImageIn, long timeout_ms){
std::cout << "doDmtxDecode(..," << timeout_ms << ")" << std::endl;
std::string string_libdmtx;
//Set decoding properties
cv::Mat matImage;
double scale = 2; //It seems the scale has to be at least '2'
int border_add = 1;
copyMakeBorder(matImageIn, matImage, border_add, border_add, border_add, border_add, BORDER_CONSTANT, 255);
resize(matImage, matImage, cv::Size(), scale, scale, INTER_AREA);
DmtxImage *img = dmtxImageCreate(matImage.data, matImage.cols, matImage.rows, DmtxPack8bppK);
assert(img != NULL);
DmtxDecode *dec = dmtxDecodeCreate(img, 1);
assert(dec != NULL);
DmtxTime timeout = dmtxTimeAdd(dmtxTimeNow(), timeout_ms);
//DmtxRegion *reg = dmtxRegionFindNext(dec, &timeout);
DmtxRegion *reg = (DmtxRegion *)malloc(sizeof(DmtxRegion));
reg->sizeIdx=0;
static const int symbolDim[] = { 10, 12, 14, 16, 18, 20, 22, 24, 26}; //.. (from libdmtx)
for (int i=0; i<9; i++){
if (matImageIn.cols ==symbolDim[i]){
reg->sizeIdx=i;
break;
}
}
reg->offColor=255;
reg->onColor=0;
reg->flowBegin.plane=0;
reg->fit2raw[0][0]=scale*matImageIn.cols; //scale(x)
reg->fit2raw[0][1]=0;
reg->fit2raw[0][2]=0;
reg->fit2raw[1][0]=0;
reg->fit2raw[1][1]=scale*matImageIn.rows; //scale(y)
reg->fit2raw[1][2]=0;
reg->fit2raw[2][0]=border_add*scale; //translation(x)
reg->fit2raw[2][1]=border_add*scale; //translation(y)
reg->fit2raw[2][2]=1; //unity
if(reg != NULL) {
std::cout << "doDmtxDecode::Found Region!" << std::endl;
DmtxMessage *msg = dmtxDecodeMatrixRegion(dec, reg, DmtxUndefined);
if(msg != NULL) {
std::cout << "doDmtxDecode::Found Message!" << std::endl;
fputs("doDmtxDecode::output: \"", stdout);
fwrite(msg->output, sizeof(unsigned char), msg->outputIdx, stdout);
string_libdmtx = std::string( (const char*) msg->output, msg->outputSize);
fputs("\"\n", stdout);
dmtxMessageDestroy(&msg);
}
dmtxRegionDestroy(®);
}
dmtxDecodeDestroy(&dec);
dmtxImageDestroy(&img);
std::cout << "END doDmtxDecode()" << std::endl;
return string_libdmtx;
}*/
// typedef struct DmtxMessage_struct {
// size_t arraySize; /* mappingRows * mappingCols */
// size_t codeSize; /* Size of encoded data (data words + error words) */
// size_t outputSize; /* Size of buffer used to hold decoded data */
// int outputIdx; /* Internal index used to store output progress */
// int padCount;
// unsigned char *array; /* Pointer to internal representation of Data Matrix modules */
// unsigned char *code; /* Pointer to internal storage of code words (data and error) */
// unsigned char *output; /* Pointer to internal storage of decoded output */
// } DmtxMessage;
std::string doDmtxDecode(const Mat &matImageIn, long timeout_ms){
std::cout << "doDmtxDecode(..," << timeout_ms << ")" << std::endl;
std::string string_libdmtx;
int sizeIdx = getSizeIdxFromSymbolDimension(matImageIn.cols, matImageIn.rows);
DmtxMessage * msg = dmtxMessageCreate(sizeIdx, DmtxFormatMatrix);
int idx=0;
for (int h=1; h<matImageIn.rows-1; h++){
for (int w=1; w<matImageIn.cols-1; w++){
msg->array[idx] = matImageIn.at<uchar>(h,w)==255 ? DmtxModuleOff : DmtxModuleOnRGB;
msg->array[idx] |= DmtxModuleAssigned;
idx++;
}
}
dmtxDecodePopulatedArray(sizeIdx, msg, -1);
if(msg != NULL) {
std::cout << "doDmtxDecode::Found Message!" << std::endl;
fputs("doDmtxDecode::output: \"", stdout);
fwrite(msg->output, sizeof(unsigned char), msg->outputIdx, stdout);
//string_libdmtx = std::string( (const char*) msg->output, msg->outputSize); // can yield /0's
string_libdmtx = std::string(reinterpret_cast<char*>(msg->output));
fputs("\"\n", stdout);
// dmtxMessageDestroy(&msg); // @TODO(tzaman) removed on 8 AUG 2016, this can crash apparently.
}
std::cout << "END doDmtxDecode()" << std::endl;
return string_libdmtx;
}
std::string bc2D::decode_pure_barcode(cv::Mat matImage){
//cout << "bc2D::decode_pure_barcode()" << endl;
string bcString="";
Mat matImageK_orig;
if(matImage.channels() == 3){
//vector<Mat> imgPlanes(3);
//split(matImage, imgPlanes);
//matImageK = imgPlanes[1];//.clone();
cvtColor(matImage, matImageK_orig, cv::COLOR_BGR2GRAY);
} else {
matImageK_orig=matImage;//.clone();
}
//Enhange image
Mat matImageK=matImageK_orig.clone();
//Auto enhance darkness and brightness
util::autoClipBrighten(matImageK, 0.10, 0.90);
//Extract the width and height of the barcode.
//Currently we only use 10, 12, 14.
//Sample the grid, maybe do this by resizing the image down to the size of the barcode itself :)
Mat matBits;
int numsizes = 4;
int sizes[4]={10, 12, 14, 16};
float stddevs[numsizes];
for (int i=0; i<numsizes; i++){
int w = sizes[i];
resize(matImageK, matBits, Size(w, w), 0, 0, INTER_AREA);
Scalar mean,stddev;
meanStdDev(matBits, mean, stddev);
stddevs[i]=stddev[0];
//cout << "mean=" << mean << " stddev=" << stddev << endl;
}
//Find highest one
float max=0;
int imax=0;
for (int i=0;i<numsizes;i++){
if (stddevs[i]>max){
imax=i;
max=stddevs[i];
}
}
//We found the width
int width = sizes[imax];
int height = width;
//Reconstruct the image for sampling
resize(matImageK, matBits, Size(width, height), 0, 0, INTER_AREA);
//Finally, check the barcode's orientation, white patch should be in the top right.
if (matBits.at<uchar>(0, 0) > 128){ //Its in the top left
util::rot90(matBits,1); //90CW
} else if (matBits.at<uchar>(height-1, width-1) > 128){ //Its in the bottom right
util::rot90(matBits,2); //90CCW
} else if (matBits.at<uchar>(height-1,0) > 128){ //Its in the bottom left
util::rot90(matBits,3); //180
} //else: good place already, leave it.
if (0){
imwrite("/Users/tzaman/Desktop/bc/matBitsRot.png",matBits);
cout << "plz press key" << endl;
char a;
cin >> a;
}
/*
bool vals[144]= //this is actually an external 12x12 matrix that says 'test'
{1,0,1,0,1,0,1,0,1,0,1,0,
1,0,1,1,0,0,1,1,0,0,1,1,
1,1,0,0,1,0,1,0,1,1,1,0,
1,1,1,0,0,0,0,1,0,1,0,1,
1,0,1,1,0,0,1,0,0,0,1,0,
1,1,0,0,1,0,0,0,0,0,0,1,
1,1,1,1,0,1,0,0,0,0,0,0,
1,0,0,1,0,1,0,1,0,1,0,1,
1,1,1,0,1,1,0,1,1,1,1,0,
1,0,1,0,1,0,0,0,0,1,0,1,
1,1,1,0,0,1,1,1,0,0,1,0,
1,1,1,1,1,1,1,1,1,1,1,1};
bool vals[100]=
{1,0,1,0,1,0,1,0,1,0,
1,1,1,0,0,0,1,0,1,1,
1,0,0,0,1,0,1,0,1,0,
1,1,0,0,0,0,1,1,1,1,
1,0,1,0,1,0,0,0,0,0,
1,0,0,0,1,1,0,1,1,1,
1,1,0,0,0,0,0,0,0,0,
1,1,0,1,1,0,1,1,0,1,
1,0,1,0,0,1,1,0,0,0,
1,1,1,1,1,1,1,1,1,1};*/
vector<int> thresholds;
thresholds.push_back(100); //Attempt a fixed threshold for value 100 [0:255]
//Find a dynamic threshold for badly printed targets.
//The strategy used here is finding a threshold so that the entire
//'connected edge' (bottom left) is filled (black). So find the minimum black
//value therein
int minVal = 255;
for (int x=0;x<matBits.cols;x++){
int valNow = matBits.at<uchar>(x,matBits.rows-1);
if (valNow < minVal){
minVal = valNow;
}
}
for (int y=0; y<matBits.rows; y++){
int valNow = matBits.at<uchar>(0,y);
if (valNow < minVal){
minVal = valNow;
}
}
//cout << "minVal=" << minVal << endl;
//Now finally add a few points for a little margin.
minVal = minVal + 5;
thresholds.push_back(minVal);
for (int i=0; i<thresholds.size(); i++){
cv::Mat matBitsThres;
threshold(matBits, matBitsThres, thresholds[i], 255, THRESH_BINARY);
//Verify the L-shape and the timing
const double min_border_validity_percentage = 0.85;
int validity_points=0;
int validity_points_max=matBitsThres.cols*2 + matBitsThres.rows*2 - 4; //length of entire edge
//Vertical Check
for (int h=0; h<matBitsThres.rows; h++){
if(matBitsThres.at<uchar>(h, 0)==0) { //Continuous part of L-shape
validity_points++;
}
if((matBitsThres.at<uchar>(h, matBitsThres.cols-1)==0) == h%2) { // Alternating test
validity_points++;
}
}
//Horizontal check
for (int w=0; w<matBitsThres.cols; w++){
if(matBitsThres.at<uchar>(matBitsThres.rows-1, w)==0) {//Continuous part of L-shape
validity_points++;
}
if((matBitsThres.at<uchar>(0, w)==255) == w%2) { // Alternating test
validity_points++;
}
}
validity_points-=4; //Subtract redundant points (4 corners)
if (validity_points < validity_points_max*min_border_validity_percentage){
//std::cout << " rejecting validity (" << validity_points << "/" << validity_points_max << ")" << std::endl;
continue;
}
//imwrite("/Users/tzaman/Desktop/bc_" + std::to_string(thresholds[i]) + ".tif",matBitsThres); //@TODO REMOVE ME
std::string string_libdmtx = doDmtxDecode(matBitsThres, 500);
if (!string_libdmtx.empty()){
bcString = string_libdmtx;
break;
}
/*
Ref<BitMatrix> bits(new BitMatrix(width));
for (int w=0; w<width; w++){
for (int h=0; h<height; h++){
if (matBits.at<uchar>(w, h) < thresholds[i]){
bits->set(h,w); //toggle black=1
}
}
}
try{
datamatrix::Decoder decoder_;
Ref<DecoderResult> decoderResult(decoder_.decode(bits));
bcString = decoderResult->getText()->getText();
cout << "Found barcode:" << bcString << endl;
break;
//cout << decoderResult->getRawBytes() << endl;
}catch (const zxing::ChecksumException& e) {
cout << "zxing::ChecksumException: " + string(e.what()) << endl;
} catch (const zxing::ReaderException& e) {
cout << "zxing::ReaderException: " + string(e.what()) << endl;
} catch (const zxing::IllegalArgumentException& e) {
cout << "zxing::IllegalArgumentException: " + string(e.what()) << endl;
} catch (const zxing::Exception& e) {
cout << "zxing::Exception: " + string(e.what()) << endl;
} catch (const std::exception& e) {
cout << "std::exception: " + string(e.what()) << endl;
} catch (...) { //GOTTA CATCH EM ALL *POKEMON*
//POKEMON!
cout << "Pokemon ZXING Catch!" << endl;
}*/
}
//cout << " decode_pure_barcode END" << endl;
return bcString;
}
std::string bc2D::decode_image_barcode(const cv::Mat &matImage, vector<int> vecBarcodeTypes, int numwiggles){
//This is only used for QR codes atm if i am not mistaken
string bcString="";
Mat matImageK_orig;
if(matImage.channels() == 3){
//vector<Mat> imgPlanes(3);
//split(matImage, imgPlanes);
//matImageK = imgPlanes[1];//.clone();
cvtColor(matImage, matImageK_orig, cv::COLOR_BGR2GRAY);
} else {
matImageK_orig=matImage;//.clone();
}
if (matImage.total()<300){
return "";
}
for (int w=0; w<numwiggles; w++){
Mat matImageK = matImageK_orig.clone();
if (w==0){
//Nothing for first wiggle
} else if (w==1){
//Second wiggle, crop it to the inside
int bordersz = matImageK.cols*0.1;
int bordersz_h = floor(bordersz*0.5);
Rect r(Point(bordersz_h, bordersz_h), Point(matImageK.cols-bordersz, matImageK.rows-bordersz)); //Crop off 7 pixels on all sides
r = util::constrainRectInSize(r, matImageK.size());
matImageK = matImageK(r);
} else if (w==2){
//Third wiggle, scale down a bit
resize(matImageK, matImageK, Size(), 0.9, 0.9, INTER_AREA);
} else if (w==3){
//Fourth wiggle, rotate 10 degrees
util::rotate(matImageK, 10, matImageK);
//Then crop the inside a bit because rotating introduces black masking edges
Rect r(Point(5,5), Point(matImageK.cols-10, matImageK.rows-10)); //Crop off 5 pixels on all sides
matImageK = matImageK(r);
} else if (w==4){
//Add border
int bordersz = matImageK.cols*0.1;
copyMakeBorder(matImageK, matImageK, bordersz, bordersz, bordersz, bordersz, BORDER_REPLICATE);
}
if (matImageK.total()<300){
return "";
}
//Copy the data, making sure we have no loose ends or 'smart' data referencing
Mat matCopy;
matImageK.copyTo(matCopy);
try{
zxingwrapper * zxwrap = new zxingwrapper(matCopy);
Ref<zxingwrapper> lumisourceRef(zxwrap);
//Binarizer * binarizer =new GlobalHistogramBinarizer(lumisourceRef);
Binarizer * binarizer =new HybridBinarizer(lumisourceRef);
Ref<Binarizer> binarizerRef(binarizer);
BinaryBitmap * bitmap = new BinaryBitmap(binarizerRef);
Ref<BinaryBitmap> bitmapRef(bitmap);
DecodeHints hints = DecodeHints(DecodeHints::TRYHARDER_HINT); //memoryleak?
Ref<MultiFormatReader> mfReader(new MultiFormatReader());
//Add the different barcode types from vector
for (int i=0;i<vecBarcodeTypes.size();i++){
hints.addFormat(zxing::BarcodeFormat::Value(vecBarcodeTypes[i]));
}
Ref<Result> result(mfReader->decode(bitmapRef, hints));
bcString=string(result->getText()->getText());
//cout << bcString << endl;
/*if (result->getResultPoints()->size()==4){
bc.UL = Point(result->getResultPoints()[0]->getX(), result->getResultPoints()[0]->getY());
bc.BL = Point(result->getResultPoints()[1]->getX(), result->getResultPoints()[1]->getY());
bc.UR = Point(result->getResultPoints()[2]->getX(), result->getResultPoints()[2]->getY());
bc.BR = Point(result->getResultPoints()[3]->getX(), result->getResultPoints()[3]->getY());
bc.M = (bc.UL + bc.BL +bc.UR + bc.BR)*0.25;
bc.barcodeType = result->getBarcodeFormat();
}*/
//Dont free news or delete anything here, they are all smart pointers that auto delete
} catch (const zxing::ReaderException& e) {
//cell_result = "zxing::ReaderException: " + string(e.what());
} catch (const zxing::IllegalArgumentException& e) {
//cell_result = "zxing::IllegalArgumentException: " + string(e.what());
util::logASL("IllegalArgumentException Catch:"+string(e.what()));
} catch (const zxing::Exception& e) {
//cell_result = "zxing::Exception: " + string(e.what());
} catch (const std::exception& e) {
//cell_result = "std::exception: " + string(e.what());
} catch (...) { //GOTTA CATCH EM ALL *POKEMON*
//POKEMON!
util::logASL("Pokemon ZXING Catch!");
}
if (!bcString.empty()){
cout << "found code on wiggle:" << w << endl;
break;
}
}
return bcString;
}
std::string bc2D::readQR(cv::Mat matImage, double dpi){
cout << "readQR()" << endl;
//Mat matImage = imread("/Users/tzaman/Desktop/bc.tif");
//Mat matImage = imread("/Users/tzaman/Desktop/qr.tif");
//Mat matImage = imread("/Users/tzaman/Desktop/20150505_Oslo_Run/20150505_153650_CAM0.tiff");
// Mat matImage = imread("/Users/tzaman/Desktop/20150505_Oslo_Run/20150505_153700_CAM0.tiff");
//Mat matImage = imread("/Users/tzaman/Desktop/20150505_Oslo_Run/20150505_153533_CAM0.tiff");
//Mat matImage = imread("/Users/tzaman/Desktop/20150505_Oslo_Run/20150505_153518_CAM0.tiff");
//Mat matImage = imread("/Users/tzaman/Desktop/20150505_Oslo_Run/20150505_153513_CAM0.tiff");
//Mat matImage = imread("/Users/tzaman/Desktop/20150505_Oslo_Run/20150505_153623_CAM0.tiff");
//Mat matImage = imread("/Users/tzaman/Desktop/20150505_Oslo_Run/20150505_153639_CAM0.tiff");
//Mat matImage = imread("/Users/tzaman/Desktop/20150505_Oslo_Run/20150505_153705_CAM0.tiff");
Mat matImageK; //grayscale image
Mat matImageC; //contour image
cvtColor(matImage, matImageK, CV_BGR2GRAY); //Convert RGB to BGR
//cout << "blur_start" << endl;
//Blur it to supress noise and shit
cv::GaussianBlur(matImageK, matImageK, cv::Size(0, 0), 1.0);
//cout << "blur_end" << endl;
threshold(matImageK, matImageC, 130, 255,THRESH_BINARY); //put it high, the featuers are quite black
vector< vector<Point> > contours; // Vector for storing contour
vector<Vec4i> hierarchy;
findContours( matImageC, contours, hierarchy,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE ); // Find the contours in the image
//cout << "contours#=" << contours.size() << endl;
//namedWindow( "rectangles" );
//imshow("rectangles", matImage);
//waitKey(0);
//Parameters
//double dpi = 300;
double squareness_threshold = 0.2; //f.e. 0.1=10% deviation aspect ratio width/height
double barcode_width_inch = 0.64;//QR CODE 0.64 inch
double bc_sizedef_threshold = 0.4; //f.e. 0.1=10% deviation to probable barcode size (1dim)
//UNUSED - SHOULD USE double bc_margin_extra_inch = 0.05; //add margin to final crop (in inches)
//double hist_thres = 0.6; //f.e. 0.75=75% histgram comparison (with band-stop histogram filter)
double qr_square_ratio_dev = 0.35; //allowed size deviation of the *ratios* of the squares areas, fe 0.2=[-20% to +20%]
double thres_dist_cluster = 2; //threshold of closeness of found centers of multiple square features
//Histogram correspondance params
int histSize = 16; //from 0 to 255
float range[] = { 0, 256 } ; //the upper boundary is exclusive
const float* histRange = { range };
bool uniform = true; bool accumulate = false;
//Define the band-stop filter (that weights the center, gray, low and the whites and blacks high)
double idealhist[16]={1.0, 1.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0};
//Caculate barcode dimention from inches and dpi
double barcode_width_px = dpi*barcode_width_inch;
//Calculate size to add to rect in pixels
//Point bc_ptadd(bc_margin_extra_inch*dpi*0.5, bc_margin_extra_inch*dpi*0.5);
//Size bc_szadd(bc_margin_extra_inch*dpi, bc_margin_extra_inch*dpi);
//Calculate thresholds
//Aspect ratio thresholds
double ar_th_low = 1.0 - squareness_threshold;
double ar_th_high = 1.0 + squareness_threshold;
//Barcode size thresholds
double bc_th_low = barcode_width_px * (1-bc_sizedef_threshold);
double bc_th_high = barcode_width_px * (1+bc_sizedef_threshold);
// ********************* //
// QR CODE //
// ********************* //
double aim_ratio_big_mid = 2.18;
double aim_ratio_big_small = 4.75;
//Make a square feature
vector<Point> contour_square;
contour_square.push_back(Point(0, 0));
contour_square.push_back(Point(0, 100));
contour_square.push_back(Point(100, 100));
contour_square.push_back(Point(100, 0));
vector<RotatedRect> rectCandidates;
bool useDebug = false;
Mat matGui;
if (useDebug){
matGui = matImageK.clone();
}
//For the QR code, we want to find 3 squares that overlap on the same place
for( int i = 0; i< contours.size(); i++ ) {// iterate through each contour.
RotatedRect rRect = minAreaRect(contours[i]);
//First check for squareness
int w = rRect.size.width;
int h = rRect.size.height;
double ar = double(w)/double(h); //Aspect Ratio
if (ar<ar_th_low || ar>ar_th_high){ //If not square
continue;
}
//For the QR code, test for the smalles square feature to the bigger one in the 3 markers
int avg = (w+h)*0.5; //Average dimention of the square (w and h avg)
if (avg<bc_th_low*0.06 || avg> bc_th_high*0.23){
continue;
}
//cout << contours[i] << endl;
//We now test if the feature matches a square shape indeed
double shapematch = matchShapes(contours[i], contour_square, CV_CONTOURS_MATCH_I2, 0);
//cout << "shapematch=" << shapematch << endl;
if (shapematch>0.02){ //not a square [maximum correct match i've seen so far is 0.02
continue;
}
if (useDebug){
Mat image = matImageK.clone();
Point2f vertices[4];
rRect.points(vertices);
for (int i = 0; i < 4; i++){
line(matGui, vertices[i], vertices[(i+1)%4], Scalar(255,0,0), 1);
}
//rectangle(matImage, boundRect, Scalar(255,0,0), 1);
//drawContours( image, contours, 0, Scalar(255), CV_FILLED, 8, hierarchy ); // Draw the largest contour using previously stored index.
//imshow("rectangles", image);
//waitKey(0);
//imwrite(boost::lexical_cast<string>(i)+"_qr_rects.png", image(rRect.boundingRect()));
}
rectCandidates.push_back(rRect);
}
if (useDebug){
imwrite("/Users/tzaman/Desktop/bc/0_qr_gui.png", matGui);
}
cout << "Found " << rectCandidates.size () << " rectangular candidates" << endl;
if (rectCandidates.size()<9){
cout << "Did not find at least 9 candidates, to make 3 markers that make 1 code." << endl;
return "";
}
// *****
// Shapes to Markers
// *****
//vector<int> dist;
vector< vector <int> > combinemap(rectCandidates.size());
vector<int> skipmap;
for (int i=0; i<rectCandidates.size(); i++){
//cout << "i=" << i << endl;
//Check if we already done this one
bool skip=false;
for (int s=0; s<skipmap.size(); s++){
if (i==skipmap[s]){
skip=true;
break;
}
}
if (skip){
continue;
}
//Add itself to itself - NOPE
// combinemap[i].push_back(i); //Not neccesary, it computes the distance to itself already, so it will always add itself
// skipmap.push_back(i);
for (int j=0; j<rectCandidates.size(); j++){
//cout << "j=" << j << endl;
//Compute the distance to each other center
double d = util::pointDist(rectCandidates[i].center, rectCandidates[j].center);
if (d < thres_dist_cluster){
//cout << "[" << i << "] to [" << j << "]" << " d=" << d << endl;
combinemap[i].push_back(j);
skipmap.push_back(j);
}
}
}
vector< vector<RotatedRect> > qrMarkers;
for (int i=0; i<combinemap.size(); i++){
//cout << "combinemap[" << i << "] candidates=" << combinemap[i].size() << endl;
//If we find 3 candidates, We see if the area ratios add up.
if (combinemap[i].size()==3){
vector<double> ratios(3);
ratios[0] = rectCandidates[combinemap[i][0]].size.area();
ratios[1] = rectCandidates[combinemap[i][1]].size.area();
ratios[2] = rectCandidates[combinemap[i][2]].size.area();
//Sort the ratios from small to large
vector<size_t> r_index;
vector<double> r_sorted;
sort(ratios, r_sorted, r_index);
//Compute the ratio with the biggest area and the middle, then the smallest
double r_m = r_sorted[2]/r_sorted[1]; //Idaelly 2.18
double r_s = r_sorted[2]/r_sorted[0]; //Ideally 4.75
//cout << "ratios [middle/big]=" << r_m << " [small/big]=" << r_s << endl;
//Check if the ratios are okay
//Big to middle first
if (r_m < aim_ratio_big_mid*(1.0-qr_square_ratio_dev) || r_m > aim_ratio_big_mid*(1.0+qr_square_ratio_dev)){
cout << "ratios [middle/big] not good:" << r_m << endl;
continue;
}
//Then check big to small
if (r_s < aim_ratio_big_small*(1.0-qr_square_ratio_dev) || r_s > aim_ratio_big_small*(1.0+qr_square_ratio_dev)){
cout << "ratios [middle/small] not good:" << r_s << endl;
continue;
}
//TODO: check that the angles are within bounds! rrect.angle, pretty easy, but beware of >45deg issues
cout << "Found a QR maker." << endl;
vector<RotatedRect> rects(3);
rects[0] = rectCandidates[combinemap[i][r_index[0]]]; //Smallest
rects[1] = rectCandidates[combinemap[i][r_index[1]]]; //Middle
rects[2] = rectCandidates[combinemap[i][r_index[2]]]; //Biggest
//rectangle(matImage, rects[0].boundingRect(), Scalar(0,255,0), 1);
//rectangle(matImage, rects[1].boundingRect(), Scalar(0,255,0), 1);
//rectangle(matImage, rects[2].boundingRect(), Scalar(0,255,0), 1);
qrMarkers.push_back(rects);
}
}
cout << "Found qrMakers :" << qrMarkers.size() << endl;
if (qrMarkers.size()<3){
cout << "Did not found enough qrMarkers to make up an QR code." << endl;
return "";
}
// *****
// Markers to Codes
// *****
//Now cluster all QR markers, we want 3 markers per QR code.
//We can compute the maximum marker-to-marker distance from the given qr size in inch
double max_m2m_dist = barcode_width_inch*dpi*1.13*1.2; //diagonal distance is 1.13x the width of the entire barcode. 1.2 is then the margin
skipmap.clear(); //Clear it since we used it before
vector< vector <int> > codecandidates(qrMarkers.size());
//Loop over the markers and group the markers
for (int i=0; i<qrMarkers.size(); i++){
//Check if we already done this one
bool skip=false;
for (int s=0; s<skipmap.size(); s++){
if (i==skipmap[s]){
skip=true;
break;
}
}
if (skip){
continue;
}
Point2f ptI = qrMarkers[i][0].center; //Take the center of this marker
//Compare with other markers
for (int j=0; j<qrMarkers.size(); j++){
Point2f ptJ = qrMarkers[j][0].center; //Take the center of this marker
//Compute distance and see if its smaller than our threshold
double d = util::pointDist(ptI, ptJ);
if (d < max_m2m_dist){
//cout << "[" << i << "] to [" << j << "]" << " d=" << d << endl;
//Points are close together, probably part of the same qr code.
codecandidates[i].push_back(j);
skipmap.push_back(j);
}
}
}
vector < vector<RotatedRect> > qrCodes;
for (int i=0; i<codecandidates.size(); i++){
//cout << "codecandidates[" << i << "] candidates=" << codecandidates[i].size() << endl;
//If we find 3 candidates, these markers probably make up a QR code
if (codecandidates[i].size()==3){
cout << "Found a new code!" << endl;
//TODO: somewhere rotate the QR code and sort the 3 feature markers
vector<RotatedRect> rects(3);
rects[0] = qrMarkers[codecandidates[i][0]][0];
rects[1] = qrMarkers[codecandidates[i][1]][0];
rects[2] = qrMarkers[codecandidates[i][2]][0];
qrCodes.push_back(rects);
//rectangle(matImage, rects[0].boundingRect(), Scalar(255,0,0), 1);
//rectangle(matImage, rects[1].boundingRect(), Scalar(255,0,0), 1);
//rectangle(matImage, rects[2].boundingRect(), Scalar(255,0,0), 1);
//Now get the enclosing circle around the markers in this code == DIRTY ==, should crop it out and rotate nicely - TODO
vector<Point2f> ptsQR(3);
ptsQR[0]= rects[0].center;
ptsQR[1]= rects[1].center;
ptsQR[2]= rects[2].center;
Point2f ptCp;
float radius;
cv::minEnclosingCircle(ptsQR, ptCp, radius);
cout << " QR center point ptCp=" << ptCp << " radius=" << radius << endl;
double sizemulti=1.2;
//Now crop it out.
Rect r(Point(ptCp.x-radius*sizemulti, ptCp.y-radius*sizemulti),Size(radius*2*sizemulti,radius*2*sizemulti));
r = util::constrainRectInSize(r, matImage.size());
Mat matBarcode = matImage(r);
//imwrite("QRcode.png", matBarcode);
vector<int> codeType;
codeType.push_back(12); //6=dmtx, 12=qr;
string strBarcode = decode_image_barcode(matBarcode, codeType, 5); //QR CODE
if (strBarcode.empty()){
continue;
}
return strBarcode;
}
}
//imwrite("matImage.png", matImage);
//exit(-1);
return "";
}
std::string bc2D::readDMTX(cv::Mat matImage_in, double dpi, double barcode_width_inch_min, double barcode_width_inch_max, int bin_thres, double ar_add){
cout << "readDMTX()" << endl;
//@TODO: convert 16bit input to 8bit
cv::Mat matImage = matImage_in.clone();
if (ar_add >0) {
// this is used when barcodes do not have a correct aspect ratio (are not square)
//make 10% bigger (NMHN @FIXME)
resize(matImage, matImage, cv::Size(), ar_add, 1, INTER_AREA);
}
bool debugbarcode = false; //FOR PRODUCTION PUT TO FALSE @FIXME
//Mat matImage = imread("/Users/tzaman/Desktop/bc.tif");
//Mat matImage = imread("/Users/tzaman/Desktop/qr.tif");
//Mat matImage = imread("/Users/tzaman/Desktop/20150505_Oslo_Run/20150505_153650_CAM0.tiff");
// Mat matImage = imread("/Users/tzaman/Desktop/20150505_Oslo_Run/20150505_153700_CAM0.tiff");
//Mat matImage = imread("/Users/tzaman/Desktop/20150505_Oslo_Run/20150505_153533_CAM0.tiff");
//Mat matImage = imread("/Users/tzaman/Desktop/20150505_Oslo_Run/20150505_153518_CAM0.tiff");
//Mat matImage = imread("/Users/tzaman/Desktop/20150505_Oslo_Run/20150505_153513_CAM0.tiff");
//Mat matImage = imread("/Users/tzaman/Desktop/20150505_Oslo_Run/20150505_153623_CAM0.tiff");
//Mat matImage = imread("/Users/tzaman/Desktop/20150505_Oslo_Run/20150505_153639_CAM0.tiff");
//Mat matImage = imread("/Users/tzaman/Desktop/20150505_Oslo_Run/20150505_153705_CAM0.tiff");
Mat matImageK; //grayscale image
Mat matImageKblur;
Mat matImageC; //contour image
cvtColor(matImage, matImageK, CV_BGR2GRAY); //Convert RGB to BGR
//cout << "blur_start" << endl;
//Blur it to supress noise and shit
cv::GaussianBlur(matImageK, matImageKblur, cv::Size(0, 0), 1.0);
//cout << "blur_end" << endl;
threshold(matImageKblur, matImageC, bin_thres, 255,THRESH_BINARY);
vector< vector<Point> > contours; // Vector for storing contour
vector<Vec4i> hierarchy;
findContours( matImageC, contours, hierarchy,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE ); // Find the contours in the image
if (debugbarcode){
imwrite("/Users/tzaman/Desktop/bc/_matImageC.tif", matImageC);
//cout << "PREZZEZ KEY" << endl;
//char a;
//cin >> a;
}
double squareness_threshold = 0.15; //f.e. 0.1=10% deviation aspect ratio width/height
double barcode_width_inch = 0.6; //DMTX oslo 0.48inch dmtx (1dim)
//double bc_sizedef_threshold = 0.3; //f.e. 0.1=10% deviation to probable barcode size (1dim)
double bc_margin_extra_inch = 0.05; //add margin to final crop (in inches)
//double hist_thres = 0.60; //f.e. 0.75=75% histgram comparison (with band-stop histogram filter)
////Histogram correspondance params
//int histSize = 16; //from 0 to 255
//float range[] = { 0, 256 } ; //the upper boundary is exclusive
//const float* histRange = { range };
//bool uniform = true; bool accumulate = false;
////Define the band-stop filter (that weights the center, gray, low and the whites and blacks high)
//double idealhist[16]={1.0, 1.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0};
//Caculate barcode dimention from inches and dpi
//double barcode_width_px = dpi*barcode_width_inch;
//Calculate size to add to rect in pixels
Point bc_ptadd(bc_margin_extra_inch*dpi*0.5, bc_margin_extra_inch*dpi*0.5);
Size bc_szadd(bc_margin_extra_inch*dpi, bc_margin_extra_inch*dpi);
//Calculate thresholds
//Aspect ratio thresholds
double ar_th_low = 1.0 - squareness_threshold;
double ar_th_high = 1.0 + squareness_threshold;
//Barcode size thresholds
double bc_th_low = dpi*barcode_width_inch_min; //barcode_width_px * (1-bc_sizedef_threshold);
double bc_th_high = dpi*barcode_width_inch_max; //barcode_width_px * (1+bc_sizedef_threshold);
for( int i = 0; i< contours.size(); i++ ) {// iterate through each contour.
double a=contourArea( contours[i],false); // Find the area of contour
if (a<400){continue;}
//cout << i << endl;
if (contours[i].size()<4){continue;}
RotatedRect rRect = util::minAreaSquare(contours[i]);
//First check for squareness
int w = rRect.size.width;