eyemBarCode.cpp
41.1 KB
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
#include "eyemBarCode.h"
#pragma region 内部使用函数
static void split(const std::string &cStrText, const std::string &cStrDelim, std::vector<std::string> &vStrs)
{
char *cpStr = new char[strlen(cStrText.c_str()) + 1];
strcpy(cpStr, cStrText.c_str());
//分割
char *token = NULL, *ptr = NULL;
token = strtok_s(cpStr, cStrDelim.c_str(), &ptr);
while (NULL != token)
{
vStrs.push_back(token);
token = strtok_s(NULL, cStrDelim.c_str(), &ptr);
}
delete[] cpStr;
cpStr = NULL;
}
static void filterByApriltag(cv::Mat &binary, cv::Mat &labels, std::vector<tMap> &vPts, std::vector<uchar> &colors, int nccomps, double dToleErr = 0.5)
{
//图像尺寸
int X = binary.cols, Y = binary.rows;
//背景
colors[0] = 255;
std::vector<tMap> temp;
//水平扫描
for (int c = 0; c < (int)vPts.size(); c++)
{
const uint8_t *ptrRow = binary.ptr<uint8_t>(vPts[c].Pt.y);
//当前可能不是二维码区域
if (ptrRow[vPts[c].Pt.x] == 0 || ptrRow[std::min(vPts[c].Pt.x + 1, X)] == 0 || ptrRow[std::max(vPts[c].Pt.x - 1, 0)] == 0 || \
binary.ptr<uint8_t>(std::max(vPts[c].Pt.y - 1, 0))[vPts[c].Pt.x] == 0 || binary.ptr<uint8_t>(std::min(vPts[c].Pt.y + 1, Y))[vPts[c].Pt.x] == 0)
{
colors[vPts[c].Label] = 0;
continue;
}
uint8_t future_pixel_right = 255;
uint8_t next_pixel;
//终止条件
int flags = 0;
double test_line[6]{ 0 };//0 中间那块;1那两块黑色;2外圈那两块
//向右扫描
for (int x = vPts[c].Pt.x + 1; x < X - 1; x++)
{
//colors为0的不参与统计
if ((colors[labels.ptr<int>(vPts[c].Pt.y)[x]] == 0))
{
continue;
}
next_pixel = ptrRow[x];
//统计黑白像素
test_line[flags]++;
if (next_pixel != future_pixel_right)
{
flags++;
future_pixel_right = 255 - future_pixel_right;
if (flags == 3) { break; }
}
}
uint8_t future_pixel_left = 255;
//向左扫描
for (int x = vPts[c].Pt.x - 1; x >= 1; x--)
{
//colors为0的不参与统计
if ((colors[labels.ptr<int>(vPts[c].Pt.y)[x]] == 0))
{
continue;
}
next_pixel = ptrRow[x];
//统计黑白像素
test_line[flags]++;
if (next_pixel != future_pixel_left)
{
flags++;
future_pixel_left = 255 - future_pixel_left;
if (flags == 6) { break; };
}
}
//判断是否符合条件,[1]/[4]为1:1------[2]/[5]为1:1-----([1]+[4])/([0]+[3])-----约为0.67
double rate = cv::min(test_line[1], test_line[4]) / cv::max(test_line[1], test_line[4]);
if ((rate >= (1. - dToleErr) && rate <= (1. + dToleErr)))
{
rate = cv::min(test_line[2], test_line[5]) / cv::max(test_line[2], test_line[5]);
if ((rate >= (1. - dToleErr) && rate <= (1. + dToleErr)))
{
rate = (test_line[1] + test_line[4]) / (test_line[0] + test_line[3]);
//允许50%的误差
if (rate >= ((2. / 3.)*(1. - dToleErr)) && rate <= ((2. / 3.)*(1. + dToleErr)))
{
temp.push_back(vPts[c]);
}
else
{
colors[vPts[c].Label] = 0;
}
}
else
{
colors[vPts[c].Label] = 0;
}
}
else
{
colors[vPts[c].Label] = 0;
}
}
//垂直扫描
for (int c = 0; c < (int)temp.size(); c++)
{
uint8_t future_pixel_down = 255;
uint8_t next_pixel;
//终止条件
int flags = 0;
double test_line[6]{ 0 };
//向下扫描
for (int y = temp[c].Pt.y + 1; y < Y - 1; y++)
{
//colors为0的不参与统计
if ((colors[labels.ptr<int>(y)[temp[c].Pt.x]] == 0))
{
continue;
}
next_pixel = binary.ptr<uint8_t>(y)[temp[c].Pt.x];
//统计黑白像素
test_line[flags]++;
if (next_pixel != future_pixel_down)
{
flags++;
future_pixel_down = 255 - future_pixel_down;
if (flags == 3) { break; };
}
}
uint8_t future_pixel_up = 255;
//向下扫描
for (int y = temp[c].Pt.y - 1; y >= 1; y--)
{
//colors为0的不参与统计
if ((colors[labels.ptr<int>(y)[temp[c].Pt.x]] == 0))
{
continue;
}
next_pixel = binary.ptr<uint8_t>(y)[temp[c].Pt.x];
//统计黑白像素
test_line[flags]++;
if (next_pixel != future_pixel_up)
{
flags++;
future_pixel_up = 255 - future_pixel_up;
if (flags == 6) { break; };
}
}
//判断是否符合条件,[1]/[4]为1:1------[2]/[5]为1:1-----([1]+[4])/([0]+[3])-----约为0.67
double rate = cv::min(test_line[1], test_line[4]) / cv::max(test_line[1], test_line[4]);
if (rate >= (1. - dToleErr) && rate <= (1 + dToleErr))
{
rate = cv::min(test_line[2], test_line[5]) / cv::max(test_line[2], test_line[5]);
if (rate >= (1. - dToleErr) && rate <= (1 + dToleErr))
{
rate = (test_line[1] + test_line[4]) / (test_line[0] + test_line[3]);
//允许50%的误差
if (rate >= ((2. / 3.)*(1. - dToleErr)) && rate <= ((2. / 3.)*(1. + dToleErr)))
{
//大部分条件均满足,进入候选点
}
else
{
colors[temp[c].Label] = 0;
}
}
else
{
colors[temp[c].Label] = 0;
}
}
else
{
colors[temp[c].Label] = 0;
}
}
colors[0] = 0;
//过滤
cv::parallel_for_(cv::Range(0, Y), [&](const cv::Range& range)->void {
for (int y = range.start; y < range.end; y++)
{
uint8_t *ptrRow = binary.ptr<uint8_t>(y);
for (int x = 0; x < X; x++)
{
int label = labels.ptr<int>(y)[x];
CV_Assert(0 <= label && label <= nccomps);
ptrRow[x] = colors[label];
}
}
});
}
static double getThreshVal_Otsu_8u(const cv::Mat& _src)
{
cv::Size size = _src.size();
int step = (int)_src.step;
if (_src.isContinuous())
{
size.width *= size.height;
size.height = 1;
step = size.width;
}
#ifdef HAVE_IPP
unsigned char thresh = 0;
CV_IPP_RUN_FAST(ipp_getThreshVal_Otsu_8u(_src.ptr(), step, size, thresh), thresh);
#endif
const int N = 256;
int i, j, h[N] = { 0 };
#if CV_ENABLE_UNROLLED
int h_unrolled[3][N] = {};
#endif
for (i = 0; i < size.height; i++)
{
const uchar* src = _src.ptr() + step*i;
j = 0;
#if CV_ENABLE_UNROLLED
for (; j <= size.width - 4; j += 4)
{
int v0 = src[j], v1 = src[j + 1];
h[v0]++; h_unrolled[0][v1]++;
v0 = src[j + 2]; v1 = src[j + 3];
h_unrolled[1][v0]++; h_unrolled[2][v1]++;
}
#endif
for (; j < size.width; j++)
h[src[j]]++;
}
double mu = 0, scale = 1. / (size.width*size.height);
for (i = 0; i < N; i++)
{
#if CV_ENABLE_UNROLLED
h[i] += h_unrolled[0][i] + h_unrolled[1][i] + h_unrolled[2][i];
#endif
mu += i*(double)h[i];
}
mu *= scale;
double mu1 = 0, q1 = 0;
double max_sigma = 0, max_val = 0;
for (i = 0; i < N; i++)
{
double p_i, q2, mu2, sigma;
p_i = h[i] * scale;
mu1 *= q1;
q1 += p_i;
q2 = 1. - q1;
if (std::min(q1, q2) < FLT_EPSILON || std::max(q1, q2) > 1. - FLT_EPSILON)
continue;
mu1 = (mu1 + i*p_i) / q1;
mu2 = (mu - q1*mu1) / q2;
sigma = q1*q2*(mu1 - mu2)*(mu1 - mu2);
if (sigma > max_sigma)
{
max_sigma = sigma;
max_val = i;
}
}
return max_val;
}
#pragma endregion
static bool decode(std::vector<WaitArea> &waitAreas, cv::Mat &showMat, std::vector<DecodeResult> &strDecodeResults, int iBlockSize, const int iRangeC, double dMinorStep)
{
//全部解码成功
bool allDecode = true;
//进入线程锁
mtx.lock();
//处理解码
for (int i = 0; i < waitAreas.size(); i++)
{
//如果已解码则不需要再次进行解码
//if (waitAreas[i].decode) continue;
//解码结果
std::string strDecodeResult = ""; std::string strDecodeResultType = "QR-Code"; cv::Point ptDecodeResult = cv::Point();
//二值化
cv::Mat binary;
//尝试多种参数解码
for (int blockSize = iBlockSize - 2; blockSize <= iBlockSize + 2; blockSize += 2)
{
for (double d = waitAreas[i].C - (double)iRangeC; d <= waitAreas[i].C + (double)iRangeC; d += dMinorStep)
{
cv::adaptiveThreshold(waitAreas[i].waitArea, binary, 255, cv::ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY, blockSize, d);
try {
Ref<LuminanceSource> source = MatSource::create(binary);
Ref<Reader> reader;
reader.reset(new QRCodeReader);
Ref<Binarizer> binarizer(new GlobalHistogramBinarizer(source));
Ref<BinaryBitmap> bitmap(new BinaryBitmap(binarizer));
Ref<Result> result(reader->decode(bitmap, DecodeHints(DecodeHints::TRYHARDER_HINT)));
if (!result.empty())
{
//waitAreas[i].decode = true;
strDecodeResult = result->getText()->getText();
goto breakLoop;
}
}
catch (...) {
//there is something wrong
}
}
}
breakLoop:
{
//做标记
if (strDecodeResult != std::string())
{
cv::putText(showMat, strDecodeResult, waitAreas[i].Pt, cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(0, 0, 255));
strDecodeResults.push_back(DecodeResult(0, waitAreas[i].Pt, strDecodeResult, strDecodeResultType));
}
}
allDecode &= true/*waitAreas[i].decode*/;
}
//离开线程锁
mtx.unlock();
return allDecode;
}
static void decodeMul(std::vector<WaitArea> &waitAreas, std::vector<std::string> &hints, cv::Mat &showMat, std::vector<DecodeResult> &decodeResults, int iBlockSize, const int iRangeC, double dMinorStep)
{
//进入线程锁
mtx.lock();
//处理解码
for (int i = 0; i < waitAreas.size(); i++)
{
bool bDecode = false;
//解码结果
std::string strResult = ""; std::string strResultType = ""; cv::Point ptResult = cv::Point();
//优先当作DM来解码,因为它比较快
if (!waitAreas[i].oneD)
{
//DmtxMessage *msg;
//DmtxRegion *reg;
//DmtxImage *img = NULL;
//img = dmtxImageCreate(waitAreas[i].waitArea.data, waitAreas[i].waitArea.cols, waitAreas[i].waitArea.rows, DmtxPack8bppK);
//DmtxDecode *dec = dmtxDecodeCreate(img, 1);
////超时
//DmtxTime beginTime = dmtxTimeNow();
//DmtxTime timeout = dmtxTimeAdd(beginTime, 15);
//reg = dmtxRegionFindNext(dec, &timeout);
//if (NULL != reg)
//{
// //解码
// msg = dmtxDecodeMatrixRegion(dec, reg, DmtxUndefined);
// if (NULL != msg)
// {
// bDecode = true;
// ptResult = waitAreas[i].Pt;
// strResultType = "DATA_MATRIX";
// strResult = std::string(reinterpret_cast<const char *>(msg->output));
// //销毁资源
// dmtxMessageDestroy(&msg);
// }
// //解码失败
// dmtxRegionDestroy(®);
//}
//dmtxDecodeDestroy(&dec);
//dmtxImageDestroy(&img);
#pragma region 有问题
for (int d = waitAreas[i].C - iRangeC; d <= waitAreas[i].C + 2 * iRangeC; d += (int)dMinorStep)
{
cv::Mat binary;
cv::adaptiveThreshold(waitAreas[i].waitArea, binary, 255, cv::ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY, iBlockSize, d);
DmtxMessage *msg;
DmtxRegion *reg;
DmtxImage *img = NULL;
if (abs(d) < DBL_EPS)
{
img = dmtxImageCreate(waitAreas[i].waitArea.data, waitAreas[i].waitArea.cols, waitAreas[i].waitArea.rows, DmtxPack8bppK);
}
else
{
img = dmtxImageCreate(binary.data, waitAreas[i].waitArea.cols, waitAreas[i].waitArea.rows, DmtxPack8bppK);
}
DmtxDecode *dec = dmtxDecodeCreate(img, 1);
//超时
DmtxTime beginTime = dmtxTimeNow();
DmtxTime timeout = dmtxTimeAdd(beginTime, 15);
reg = dmtxRegionFindNext(dec, &timeout);
if (NULL != reg)
{
//解码
msg = dmtxDecodeMatrixRegion(dec, reg, DmtxUndefined);
if (NULL != msg)
{
bDecode = true;
ptResult = waitAreas[i].Pt;
strResultType = "DATA_MATRIX";
strResult = std::string(reinterpret_cast<const char *>(msg->output));
//销毁资源
dmtxMessageDestroy(&msg);
}
//解码失败
dmtxRegionDestroy(®);
}
dmtxDecodeDestroy(&dec);
dmtxImageDestroy(&img);
//
if (bDecode)
break;
}
#pragma endregion
}
//如果未解码,判断可能是QR或者一维码或者DATA_MATRIX
if (!bDecode)
{
if (waitAreas[i].oneD)
{
//创建解码器
Ref<Reader> reader_;
reader_.reset(Ref<Reader>(new zxing::oned::MultiFormatOneDReader(DecodeHints::CODE_128_HINT | DecodeHints::CODE_39_HINT | DecodeHints::CODE_93_HINT)));
//一维码识别
for (int ii = 0; ii < waitAreas[i].oneDMats.size(); ii++)
{
cv::Mat src = waitAreas[i].oneDMats[ii];
cv::pyrUp(src, src, cv::Size(src.cols * 2, src.rows * 2));
//判断解码结果
double threshVal = getThreshVal_Otsu_8u(src);
for (double c = threshVal - 4 * iRangeC; c < threshVal + 4 * iRangeC; c += dMinorStep)
{
cv::Mat binary;
cv::threshold(src, binary, c, 255, cv::THRESH_BINARY);
try
{
//创建图像
Ref<LuminanceSource> source = MatSource::create(binary);
Ref<Binarizer> binarizer(new GlobalHistogramBinarizer(source));
Ref<BinaryBitmap> bitmap(new BinaryBitmap(binarizer));
//解码
Ref<Result> result(reader_->decode(bitmap, DecodeHints::CODE_128_HINT | DecodeHints::CODE_39_HINT | DecodeHints::CODE_93_HINT));
if (!result.empty())
{
bDecode = true;
ptResult = waitAreas[i].Pt;
strResult = result->getText()->getText();
switch (result->getBarcodeFormat())
{
case NONE:
strResultType = "NONE";
break;
case CODABAR:
strResultType = "CODABAR";
break;
case CODE_39:
strResultType = "CODE_39";
break;
case CODE_93:
strResultType = "CODE_93";
break;
case CODE_128:
strResultType = "CODE_128";
break;
case EAN_8:
strResultType = "EAN_8";
case EAN_13:
strResultType = "EAN_13";
break;
case ITF:
strResultType = "ITF";
break;
case MAXICODE:
strResultType = "MAXICODE";
break;
case RSS_14:
strResultType = "RSS_14";
break;
case RSS_EXPANDED:
strResultType = "RSS_EXPANDED";
break;
case UPC_A:
strResultType = "UPC_A";
break;
case UPC_E:
strResultType = "UPC_E";
break;
case UPC_EAN_EXTENSION:
strResultType = "UPC_EAN_EXTENSION";
break;
default:
break;
}
}
}
catch (...) {
//there is something wrong
}
}
if (bDecode) {
break;
}
}
}
else
{
//添加二维码解码器
std::vector<Ref<Reader>> readers_;
if (std::find(hints.begin(), hints.end(), "QR_CODE") != hints.end()) {
readers_.push_back(Ref<Reader>(new zxing::qrcode::QRCodeReader));
}
if (std::find(hints.begin(), hints.end(), "DATA_MATRIX") != hints.end()) {
readers_.push_back(Ref<Reader>(new zxing::datamatrix::DataMatrixReader));
}
if (std::find(hints.begin(), hints.end(), "AZTEC") != hints.end()) {
readers_.push_back(Ref<Reader>(new zxing::aztec::AztecReader));
}
cv::Mat binary;
cv::Mat src = waitAreas[i].waitArea;
for (unsigned int ii = 0; ii < readers_.size(); ii++) {
//尝试多种参数解码
for (int blockSize = iBlockSize - 2; blockSize <= iBlockSize + 2; blockSize += 2)
{
for (double d = waitAreas[i].C - (double)iRangeC; d <= waitAreas[i].C + (double)iRangeC; d += dMinorStep)
{
cv::adaptiveThreshold(src, binary, 255, cv::ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY, blockSize, d);
try {
//创建图像
Ref<LuminanceSource> source = MatSource::create(binary);
Ref<Binarizer> binarizer(new GlobalHistogramBinarizer(source));
Ref<BinaryBitmap> bitmap(new BinaryBitmap(binarizer));
Ref<Result> result(readers_[ii]->decode(bitmap, zxing::DecodeHints::TRYHARDER_HINT));
//如果解码成功
if (!result.empty())
{
ptResult = waitAreas[i].Pt;
strResult = result->getText()->getText();
switch (result->getBarcodeFormat())
{
case AZTEC:
strResultType = "AZTEC";
break;
case DATA_MATRIX:
strResultType = "DATA_MATRIX";
break;
case QR_CODE:
strResultType = "QR_CODE";
break;
default:
break;
}
goto breakLoop;
}
}
catch (...) {
//there is something wrong
}
}
}
//如果仍未解码
if (!bDecode)
{
cv::Mat srcPyrUp;
cv::pyrUp(src, srcPyrUp, cv::Size(src.cols * 2, src.rows * 2));
for (int blockSize = (2 * iBlockSize + 1) - 2; blockSize <= (2 * iBlockSize + 1) + 2; blockSize += 2)
{
for (double d = waitAreas[i].C - (double)iRangeC; d <= waitAreas[i].C + (double)iRangeC; d += dMinorStep)
{
cv::adaptiveThreshold(srcPyrUp, binary, 255, cv::ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY, blockSize, d);
try {
//创建图像
Ref<LuminanceSource> source = MatSource::create(binary);
Ref<Binarizer> binarizer(new GlobalHistogramBinarizer(source));
Ref<BinaryBitmap> bitmap(new BinaryBitmap(binarizer));
Ref<Result> result(readers_[ii]->decode(bitmap, zxing::DecodeHints::TRYHARDER_HINT));
//如果解码成功
if (!result.empty())
{
ptResult = waitAreas[i].Pt;
strResult = result->getText()->getText();
switch (result->getBarcodeFormat())
{
case AZTEC:
strResultType = "AZTEC";
break;
case DATA_MATRIX:
strResultType = "DATA_MATRIX";
break;
case QR_CODE:
strResultType = "QR_CODE";
break;
default:
break;
}
goto breakLoop;
}
}
catch (...) {
//there is something wrong
}
}
}
}
}
breakLoop:
{
if (strResult != std::string())
{
bDecode = true;
}
}
}
}
//判断是否解码
if (bDecode)
{
decodeResults.push_back(DecodeResult(waitAreas[i].angle, ptResult, strResult, strResultType));
cv::putText(showMat, strResult, ptResult / 2, cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(0, 0, 255));
}
}
//离开线程锁
mtx.unlock();
}
int eyemDetectAndDecode(EyemImage tpImage, EyemRect tpRoi, const char *ccFileName, const char *ccCodeType, IntPtr *hObject, EyemBarCode **hResults, int *ipNum, bool bUseNiBlack, int iBlockSize, const int iRangeC, int iSymbolMin, int iSymbolMax, double dScaleUpAndDown, double dToleErr, double dMinorStep)
{
cv::Mat src = cv::Mat(tpImage.iHeight, tpImage.iWidth, MAKETYPE(tpImage.iDepth, tpImage.iChannels), tpImage.vpImage);
if (src.empty()) {
return FUNC_IMAGE_NOT_EXIST;
}
//转单通道图像
if (src.channels() != 1)
cv::cvtColor(src, src, cv::COLOR_BGR2GRAY);
//提取ROI
src = src(cv::Rect(tpRoi.iXs, tpRoi.iYs, tpRoi.iWidth, tpRoi.iHeight));
//图像原图备份
cv::Mat backup = src.clone();
//降采样
if (dScaleUpAndDown != 1.)
cv::pyrDown(src, src, cv::Size(cvRound(src.cols*dScaleUpAndDown), cvRound(src.rows*dScaleUpAndDown)));
//用于显示
cv::Mat showMat;
cv::cvtColor(src, showMat, cv::COLOR_GRAY2BGR);
//图像尺寸
int X = src.cols, Y = src.rows;
//解码结果
std::vector<EyemBarCode> *tpResults = new std::vector<EyemBarCode>();
//测试用
cv::Mat srcPrev, binary;
//高斯滤波去噪
int ksize = cvRound((iBlockSize + 1)*dScaleUpAndDown) % 2 == 0 ? cvRound((iBlockSize + 1)*dScaleUpAndDown) + 1 : cvRound((iBlockSize + 1)*dScaleUpAndDown);
cv::GaussianBlur(src, srcPrev, cv::Size(ksize, ksize), 0.3);
//条码来说会比背景值小,二维码来说会比背景值大
//计算导数
cv::Mat dx, dy, mag;
cv::Sobel(srcPrev, dx, CV_32F, 1, 0);
cv::Sobel(srcPrev, dy, CV_32F, 0, 1);
//计算梯度幅值
cv::magnitude(dx, dy, mag);
// 归一化
cv::normalize(mag, mag, 0, 255, cv::NORM_MINMAX, CV_32FC1, cv::Mat());
cv::convertScaleAbs(mag, srcPrev);
//二值化
cv::threshold(srcPrev, binary, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
//膨胀
cv::morphologyEx(binary, binary, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(cvRound(iBlockSize*dScaleUpAndDown / 3.), cvRound(iBlockSize*dScaleUpAndDown / 3.))));
//计算角点响应
cv::Mat harMap;
cv::cornerHarris(src, harMap, cvRound(iBlockSize*dScaleUpAndDown), 3, 0.04);//对二维码效果比较好
// 归一化与转换
cv::normalize(harMap, harMap, 0, 255, cv::NORM_MINMAX, CV_32FC1, cv::Mat());
cv::convertScaleAbs(harMap, harMap);
//计算背景像素
const int histSize = 256;
float range[] = { 0,255 };
const float* histRange = { range };
//calculate the histogram
cv::Mat hist;
cv::calcHist(&harMap, 1, 0, cv::Mat(), hist, 1, &histSize, &histRange);
//calculate the background pixels
int maxIdx[2] = { 255,255 };
cv::minMaxIdx(hist, NULL, NULL, NULL, maxIdx);
//m1用于检测一维码;m2用于检测二维码
cv::Mat m1(Y, X, CV_8UC1, cv::Scalar(0)), m2(Y, X, CV_8UC1, cv::Scalar(0));
cv::parallel_for_(cv::Range(0, Y), [&](const cv::Range& range)->void {
for (int y = range.start; y < range.end; y++)
{
for (int x = 0; x < X; x++)
{
if (harMap.ptr<uint8_t>(y)[x] < maxIdx[0])
{
m1.ptr<uint8_t>(y)[x] = 255;
}
else if (harMap.ptr<uint8_t>(y)[x] > maxIdx[0])
{
m2.ptr<uint8_t>(y)[x] = 255;
}
}
}
});
//确定识别类型
std::vector<std::string> hints_;
split(ccCodeType, "|", hints_);
//是否添加一维码检测
bool addOneDReader = std::find(hints_.begin(), hints_.end(), "UPC_A") != hints_.end() ||
std::find(hints_.begin(), hints_.end(), "UPC_E") != hints_.end() ||
std::find(hints_.begin(), hints_.end(), "EAN_8") != hints_.end() ||
std::find(hints_.begin(), hints_.end(), "EAN_13") != hints_.end() ||
std::find(hints_.begin(), hints_.end(), "CODABAR") != hints_.end() ||
std::find(hints_.begin(), hints_.end(), "CODE_39") != hints_.end() ||
std::find(hints_.begin(), hints_.end(), "CODE_93") != hints_.end() ||
std::find(hints_.begin(), hints_.end(), "CODE_128") != hints_.end() ||
std::find(hints_.begin(), hints_.end(), "ITF") != hints_.end() ||
std::find(hints_.begin(), hints_.end(), "RSS_14") != hints_.end() ||
std::find(hints_.begin(), hints_.end(), "RSS_EXPANDED") != hints_.end();
//是否添加二维码检测
bool addTwoDReader = std::find(hints_.begin(), hints_.end(), "QR_CODE") != hints_.end() ||
std::find(hints_.begin(), hints_.end(), "DATA_MATRIX") != hints_.end() ||
std::find(hints_.begin(), hints_.end(), "AZTEC") != hints_.end();
//未设置识别类型
if (!addOneDReader && !addTwoDReader)
return FUNC_CANNOT_CALC;
//所有解码内容
std::vector<DecodeResult> decodeResults;
//待解码区域,区分条码类型来识别
std::vector<WaitArea> waitAreas;
if (addOneDReader)
{
cv::Mat labels, stats, centroids;
int nccomps = cv::connectedComponentsWithStats(m1, labels, stats, centroids, 4);
//过滤连通域面积及长/宽比例不符合的,允许50%误差
std::vector<uchar> colors(nccomps + 1, 0);
for (int i = 1; i < nccomps; i++) {
colors[i] = 255;
if ((stats.ptr<int>(i)[cv::CC_STAT_AREA] < std::pow(iBlockSize*dScaleUpAndDown, 2) * 5) | (m1.ptr<uint8_t>(cvRound(centroids.ptr<double>(i)[1]))[cvRound(centroids.ptr<double>(i)[0])] == 0))
{
colors[i] = 0;
}
}
//过滤
cv::parallel_for_(cv::Range(0, Y), [&](const cv::Range& range)->void {
for (int y = range.start; y < range.end; y++)
{
uint8_t *ptrRow = m1.ptr<uint8_t>(y);
for (int x = 0; x < X; x++)
{
int label = labels.ptr<int>(y)[x];
CV_Assert(0 <= label && label <= nccomps);
ptrRow[x] = colors[label];
}
}
});
//用于过滤非条码部分
cv::Mat binFilter;
cv::adaptiveThreshold(backup, binFilter, 255, cv::ADAPTIVE_THRESH_GAUSSIAN_C, cv::THRESH_BINARY_INV, ksize, 5);
//处理断裂一维码
//cv::morphologyEx(m1, m1, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(cvRound(iBlockSize*dScaleUpAndDown / 3.), cvRound(iBlockSize*dScaleUpAndDown / 3.))));
//用于轮廓检测
std::vector<std::vector<cv::Point>> contourAll, contourFilter;
findContours(m1, contourAll, cv::noArray(), cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
for (int i = 0; i < static_cast<int>(contourAll.size()); i++)
{
cv::RotatedRect rect = cv::minAreaRect(contourAll[i]);
//最大宽度限制
double minLen = cv::min(rect.size.height, rect.size.width);
if (minLen < 8.*iBlockSize*dScaleUpAndDown*(1. + dToleErr))
{
//增加比例过滤条件
cv::Point2f pts[4];
rect.points(pts);
//起点、终点、中点
cv::Point ptStart, ptEnd, ptMid;
if (cv::norm(pts[0] - pts[1]) > cv::norm(pts[1] - pts[2]))
{
ptStart = cv::Point((pts[0] + pts[3]) / 2. / dScaleUpAndDown); ptEnd = cv::Point((pts[1] + pts[2]) / 2. / dScaleUpAndDown);
}
else
{
ptStart = cv::Point((pts[0] + pts[1]) / 2. / dScaleUpAndDown); ptEnd = cv::Point((pts[2] + pts[3]) / 2. / dScaleUpAndDown);
}
ptMid = (ptStart + ptEnd) / 2;
cv::LineIterator it(binFilter, (ptMid + ptEnd) / 2, (ptMid + ptStart) / 2, 4);
double dis = cv::norm((ptMid + ptEnd) / 2 - (ptMid + ptStart) / 2);
uint8_t future_pixel = 255;
//扫描像素密度,比例接近1:1记录下来,并且黑白间隔数目小大于长度的一半
int flag = 0;
double test_line[2]{ 0 };
for (int n = 0; n < it.count; n++, ++it)
{
if (m1.ptr<uint8_t>(cvRound(it.pos().y * dScaleUpAndDown))[cvRound(it.pos().x * dScaleUpAndDown)] == 0) continue;
//统计均匀性
uint8_t next_pixel = binFilter.ptr<uint8_t>(it.pos().y)[it.pos().x];
test_line[next_pixel % 254]++;
if (next_pixel != future_pixel)
{
flag++;
future_pixel = 255 - future_pixel;
}
//showMat.at<cv::Vec3b>(it.pos()) = cv::Vec3b(0, 255, 0);
}
//满足比例
double dRate = cv::min(test_line[0], test_line[1]) / cv::max(test_line[0], test_line[1]);
if (dRate >= (1. - dToleErr) && dRate <= (1. + dToleErr) && flag > cvRound((dis / 4.)*(1. - dToleErr)))
{
cv::Point2f pt[4];
cv::Size size(cvRound(cv::max(rect.size.height, rect.size.width) + iBlockSize*dScaleUpAndDown / 4.), cvRound(cv::min(rect.size.height, rect.size.width)));
//获取roi位置
double _angle = std::atan2((ptEnd.y - ptStart.y), (ptEnd.x - ptStart.x));
float b = (float)cos(_angle)*0.5f;
float a = (float)sin(_angle)*0.5f;
pt[0].x = rect.center.x - a*size.height - b*size.width;
pt[0].y = rect.center.y + b*size.height - a*size.width;
pt[1].x = rect.center.x + a*size.height - b*size.width;
pt[1].y = rect.center.y - b*size.height - a*size.width;
pt[2].x = 2 * rect.center.x - pt[0].x;
pt[2].y = 2 * rect.center.y - pt[0].y;
pt[3].x = 2 * rect.center.x - pt[1].x;
pt[3].y = 2 * rect.center.y - pt[1].y;
//防止越界
for (int n = 0; n < 4; n++)
{
if (pt[n].x < 0) pt[n].x = 0.f; if (pt[n].x >= X - 1) pt[n].x = float(X - 1); if (pt[n].y < 0) pt[n].y = 0.f; if (pt[n].y >= Y - 1) pt[n].y = float(Y - 1);
}
//用采样的方式提取待解码区域
cv::LineIterator itStHeight(backup, pt[0], pt[1], 4);
cv::LineIterator itEdHeight(backup, pt[3], pt[2], 4);
cv::LineIterator itStWidth(backup, pt[0], pt[3], 4);
cv::LineIterator itEdWidth(backup, pt[1], pt[2], 4);
struct Track
{
cv::Point PosS;
cv::Point PosE;
Track() {};
Track(cv::Point PosS, cv::Point PosE) :PosS(PosS), PosE(PosE) {};
};
std::vector<Track> pairStEd(cv::min(itStHeight.count, itEdHeight.count));
for (int n = 0; n < pairStEd.size(); n++, ++itStHeight, ++itEdHeight)
{
pairStEd[n] = Track(itStHeight.pos(), itEdHeight.pos());
}
int iSamplingStep = int(pairStEd.size()) / 4;
//线采样
cv::Mat srcSampling(cv::Size(cv::max(itStWidth.count, itEdWidth.count), 1), CV_8UC1, cv::Scalar(255));
//
std::vector<cv::Mat> oneDMats;
//行
for (int n = 0; n < (int)pairStEd.size(); n += iSamplingStep)
{
cv::LineIterator it(backup, pairStEd[n].PosS, pairStEd[n].PosE, 4);
for (int nn = 0; nn < it.count; nn++, ++it)//列
{
//showMat.at<cv::Vec3b>(it.pos()) = cv::Vec3b(0, 255, 0);
srcSampling.ptr<uint8_t>(0)[nn] = backup.ptr<uint8_t>(it.pos().y)[it.pos().x];
}
//判断是否为二维码
cv::Mat testMat;
cv::threshold(srcSampling, testMat, 0, 255, cv::THRESH_BINARY_INV | cv::THRESH_OTSU);
//
cv::Mat testLabels;
if (cv::connectedComponents(testMat, testLabels) < 6)
{
//判断非二维码
break;
}
//扩展
cv::Mat waitArea;
cv::copyMakeBorder(srcSampling, waitArea, 0, 1, 60, 60, cv::BORDER_REPLICATE);
oneDMats.push_back(waitArea);
}
//存储一维码待解码区域
if ((int)oneDMats.size() > 0)
{
//画图
for (int j = 0; j < 4; j++)
{
cv::line(showMat, pt[j], pt[(j + 1) % 4], cv::Scalar(0, 255, 255), 1);
}
cv::circle(showMat, pt[0], 2, cv::Scalar(255, 0, 0), -1);
cv::circle(showMat, pt[1], 2, cv::Scalar(0, 255, 0), -1);
cv::circle(showMat, pt[2], 2, cv::Scalar(0, 0, 255), -1);
waitAreas.push_back(WaitArea(cv::Mat(), ptMid, getThreshVal_Otsu_8u(oneDMats[0]), rect.angle, true, oneDMats));
}
}
}
}
}
if (addTwoDReader)
{
//测试用
cv::Mat srcFilter;
cv::adaptiveThreshold(src, srcFilter, 255, cv::ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY_INV, 43, 2);
//去掉小于15个像素的
cv::morphologyEx(srcFilter, srcFilter, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(cvRound(iBlockSize*dScaleUpAndDown / 3.), cvRound(iBlockSize*dScaleUpAndDown / 3.))));
//断裂处连接在一起
cv::morphologyEx(m2, m2, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(cvRound(iBlockSize*dScaleUpAndDown), cvRound(iBlockSize*dScaleUpAndDown))));
//去掉无关区域
cv::bitwise_and(srcFilter, m2, m2);
//对二值图像过滤
cv::Mat labels, stats, centroids;
int nccomps = cv::connectedComponentsWithStats(m2, labels, stats, centroids, 4);
//过滤连通域面积及长/宽比例不符合的,允许50%误差
std::vector<uchar> colors(nccomps + 1, 0);
for (int i = 1; i < nccomps; i++) {
colors[i] = 255;
double dRate = (double)stats.ptr<int>(i)[cv::CC_STAT_WIDTH] / (double)stats.ptr<int>(i)[cv::CC_STAT_HEIGHT];
if ((!(dRate >= (1. - dToleErr) && dRate <= (1. + dToleErr))) | (stats.ptr<int>(i)[cv::CC_STAT_WIDTH] > iBlockSize*dScaleUpAndDown * 15 * 1.414*(1. + dToleErr)) | (stats.ptr<int>(i)[cv::CC_STAT_HEIGHT] > iBlockSize*dScaleUpAndDown * 15 * 1.414*(1. + dToleErr))\
| ((double)stats.ptr<int>(i)[cv::CC_STAT_AREA] < std::pow(iBlockSize / 2, 2) * 15))
{
colors[i] = 0;
}
}
//第一次过滤
cv::parallel_for_(cv::Range(0, Y), [&](const cv::Range& range)->void {
for (int y = range.start; y < range.end; y++)
{
uint8_t *ptrRow = m2.ptr<uint8_t>(y);
for (int x = 0; x < X; x++)
{
int label = labels.ptr<int>(y)[x];
CV_Assert(0 <= label && label <= nccomps);
ptrRow[x] = colors[label];
}
}
});
//用于轮廓检测
std::vector<std::vector<cv::Point>> contourAll, contourFilter;
findContours(m2, contourAll, cv::noArray(), cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
for (int i = 0; i < static_cast<int>(contourAll.size()); i++)
{
cv::RotatedRect rect = cv::minAreaRect(contourAll[i]);
//满足矩形条件与面积条件
double dRate = cv::min(rect.size.width, rect.size.height) / cv::max(rect.size.height, rect.size.width);
if (dRate >= (1. - dToleErr) && dRate <= (1. + dToleErr) && ((double)rect.size.width > double(8. * iBlockSize*dScaleUpAndDown)) && ((double)rect.size.height > double(8. * iBlockSize*dScaleUpAndDown)))
{
contourFilter.push_back(contourAll[i]);
}
}
for (int i = 0; i < contourFilter.size(); i++)
{
cv::Rect rect = cv::minAreaRect(contourFilter[i]).boundingRect();
cv::RotatedRect rRect = cv::minAreaRect(contourFilter[i]);
//外包矩形
int dynSize = cvRound(cv::max((double)rect.size().height / dScaleUpAndDown, (double)rect.size().width / dScaleUpAndDown));
//疑似二维码区域
cv::Mat waitArea = backup(cv::Range(cv::max(0, cvRound(rRect.center.y / dScaleUpAndDown) - cvRound(4.*(double)iBlockSize*dScaleUpAndDown + dynSize / 2)), cv::min(backup.rows - 1, cvRound(rRect.center.y / dScaleUpAndDown) + cvRound(4.*(double)iBlockSize*dScaleUpAndDown + dynSize / 2))), cv::Range(cv::max(0, cvRound(rRect.center.x / dScaleUpAndDown) - cvRound(4.*(double)iBlockSize*dScaleUpAndDown + dynSize / 2)), cv::min(backup.cols - 1, cvRound(rRect.center.x / dScaleUpAndDown) + cvRound(4.*(double)iBlockSize*dScaleUpAndDown + dynSize / 2)))).clone();
//处理后再压入识别
waitAreas.push_back(WaitArea(waitArea, cv::Point(cvRound(rRect.center.x / dScaleUpAndDown), cvRound(rRect.center.y / dScaleUpAndDown)), 0, 0, false, std::vector<cv::Mat>()));
//画图
cv::rectangle(showMat, rect, cv::Scalar(0, 255, 0), 1);
}
}
//解码
decodeMul(waitAreas, hints_, showMat, decodeResults, iBlockSize, iRangeC, dMinorStep);
//输出结果
for (int i = 0; i < decodeResults.size(); i++)
{
EyemBarCode tpResult;
tpResult.iCenterX = decodeResults[i].ptResult.x;
tpResult.iCenterY = decodeResults[i].ptResult.y;
tpResult.dAngle = decodeResults[i].dAngle;
//分配内容所需内存
tpResult.lpszText = (char *)CoTaskMemAlloc(512);
if (NULL != tpResult.lpszText)
{
char file[512] = { 0 };
sprintf_s(file, "%s", decodeResults[i].strResultText.c_str());
strcpy(tpResult.lpszText, file);
}
else return FUNC_NOT_ENOUGH_MEM;
//分配码型所需内存
tpResult.lpszType = (char *)CoTaskMemAlloc(512);
if (NULL != tpResult.lpszType)
{
char file[512] = { 0 };
sprintf_s(file, "%s", decodeResults[i].strResultType.c_str());
strcpy(tpResult.lpszType, file);
}
else return FUNC_NOT_ENOUGH_MEM;
//添加结果
tpResults->push_back(tpResult);
}
*hResults = tpResults->data();
*ipNum = static_cast<int>(tpResults->size());
*hObject = reinterpret_cast<IntPtr>(tpResults);
////格式化文件名
//const int bufSize = 32;
//char file[bufSize * 4] = { 0 };
//sprintf_s(file, "D:\\ResOut\\%s-Mark.png", ccFileName);
//cv::imwrite(file, showMat);
return FUNC_OK;
////局部二值化
//cv::adaptiveThreshold(src, binary, 255, cv::ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY_INV, iBlockSize, 2);
////去掉大部分干扰项
//binary &= mask;
////对二值图像过滤
//cv::Mat labels, stats, centroids;
//int nccomps = cv::connectedComponentsWithStats(binary, labels, stats, centroids, 4);
////过滤连通域面积及长/宽比例不符合的,允许50%误差
//std::vector<uchar> colors(nccomps + 1, 0);
//for (int i = 1; i < nccomps; i++) {
// colors[i] = 255;
// if ((stats.ptr<int>(i)[cv::CC_STAT_WIDTH] > iBlockSize * 15 * 1.414*(1. + dToleErr)) | (stats.ptr<int>(i)[cv::CC_STAT_HEIGHT] > iBlockSize * 15 * 1.414*(1. + dToleErr))\
// | (false))
// {
// colors[i] = 0;
// }
//}
////第一次过滤
//cv::parallel_for_(cv::Range(0, Y), [&](const cv::Range& range)->void {
// for (int y = range.start; y < range.end; y++)
// {
// uint8_t *ptrRow = binary.ptr<uint8_t>(y);
// for (int x = 0; x < X; x++)
// {
// int label = labels.ptr<int>(y)[x];
// CV_Assert(0 <= label && label <= nccomps);
// ptrRow[x] = colors[label];
// }
// }
//});
////cv::cvtColor(binary, showMat, cv::COLOR_GRAY2BGR);
//const int iScanRadius = 35;
////最好还是用线扫描的方法,具体扫描全图还是按照中心点来扫看时间
////指定长度十字网格遍历是否满足条件黑白比例在1:1,考虑其他方式去扫描,可能速度上会慢一些,如果区分满足各自条件可能会好一些
////,这样可以将其他不必要的过滤掉,最后再合成一张图;2,扫描宽度,根据宽度流来确定是否属于条码、qr、datamatrix,黑白宽度;
////宽度打开都在一个很小变动范围内,允许50%的误差,宽度密度相较目前判断方式可也确定是否是黑白格分布,考虑到一维条码,八个方向只需满足一个方向即可
////这样可以过滤掉一些孤立长条
////vPts[0].Pt = cv::Point(3610, 2433);
//cv::Mat label(Y, X, CV_8UC1, cv::Scalar(0));
//cv::parallel_for_(cv::Range(0, Y), [&](const cv::Range& range)->void {
// for (int y = range.start; y < range.end; y++)
// {
// for (int x = 0; x < X; x++)
// {
// uint8_t future_pixel = binary.ptr<uint8_t>(y)[x];
// if (!future_pixel)
// {
// continue;
// }
// bool iFlag = 0;
// //判断白色像素部分占整条线的比例
// for (double t = -180; t < 180; t += 45)
// {
// float xx = float(x + iScanRadius * cos(t* 0.01745));
// float yy = float(y + iScanRadius * sin(t* 0.01745));
// //防止越界
// if (xx < 0) xx = 0; if (xx >= X - 1) xx = X - 1; if (yy < 0) yy = 0; if (yy >= Y - 1) yy = Y - 1;
// cv::LineIterator it(binary, cv::Point(x, y), cv::Point(cvRound(xx), cvRound(yy)), 4);
// //扫描像素密度,比例接近1:1记录下来
// int length = 0;
// std::vector<double> test_lines;
// double test_line[2]{ 0 };
// for (int n = 0; n < it.count; n++, ++it)
// {
// //统计相邻由明到暗个数,并且查看均匀性
// uint8_t next_pixel = binary.ptr<uint8_t>(it.pos().y)[it.pos().x];
// test_line[next_pixel % 254]++;
// length++;
// if (next_pixel != future_pixel)
// {
// if (!next_pixel)
// {
// test_lines.push_back(length);
// }
// future_pixel = 255 - future_pixel;
// length = 0;
// }
// }
// if (cv::max(test_line[0], test_line[1]) <= 0) continue;
// //至少存在l个方向满足黑白1:1比例,并且满足黑白交替比例大概在1:1
// double dRate = cv::min(test_line[0], test_line[1]) / cv::max(test_line[0], test_line[1]);
// if (dRate >= (1. - dToleErr) && dRate <= (1. + dToleErr))
// {
// //满足条件,再判断当前方向的宽度是否
// iFlag = true;
// //cv::putText(showMat, "OK", vPts[c].Pt, cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(0, 0, 255));
// //showMat.at<cv::Vec3b>(cv::Point(x, y)) = cv::Vec3b(0, 255, 0);
// label.ptr<uint8_t>(y)[x] = 255;
// break;
// }
// }
// }
// }
//});
//for (int c = 0; c < (int)vPts.size(); c++)
//{
// bool iFlag = 0;
// uint8_t future_pixel = binary.ptr<uint8_t>(vPts[c].Pt.y)[vPts[c].Pt.x];
// //判断白色像素部分占整条线的比例
// for (double t = -180; t < 180; t += 45)
// {
// float x = float(vPts[c].Pt.x + iScanRadius * cos(t* 0.01745));
// float y = float(vPts[c].Pt.y + iScanRadius * sin(t* 0.01745));
// //防止越界
// if (x < 0) x = 0; if (x >= X - 1) x = X - 1; if (y < 0) y = 0; if (y >= Y - 1) y = Y - 1;
// cv::LineIterator it(binary, vPts[c].Pt, cv::Point(cvRound(x), cvRound(y)), 4);
// //扫描像素密度,比例接近1:1记录下来
// //测试用
// std::vector<cv::Point> test_point;
// int length = 0;
// std::vector<double> test_lines;
// double test_line[2]{ 0 };
// for (int n = 0; n < it.count; n++, ++it)
// {
// //统计相邻由明到暗个数,并且查看均匀性
// uint8_t next_pixel = binary.ptr<uint8_t>(it.pos().y)[it.pos().x];
// test_line[next_pixel % 254]++;
// length++;
// if (next_pixel != future_pixel)
// {
// if (length > 1)
// {
// test_lines.push_back(length);
// }
// future_pixel = 255 - future_pixel;
// length = 0;
// }
// //test_point.push_back(it.pos());
// //showMat.at<cv::Vec3b>(it.pos()) = cv::Vec3b(0, 255, 0);
// }
// //至少存在l个方向满足黑白1:1比例,并且满足黑白交替比例大概在1:1
// double dRate = cv::min(test_line[0], test_line[1]) / cv::max(test_line[0], test_line[1]);
// if (dRate >= (1. - dToleErr) && dRate <= (1. + dToleErr) && (test_lines.size() >= T))
// {
// //满足条件,再判断当前方向的宽度是否
// iFlag = true;
// //cv::putText(showMat, "OK", vPts[c].Pt, cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(0, 0, 255));
// //for (int n = 0; n < test_point.size(); n++)
// //{
// // showMat.at<cv::Vec3b>(test_point[n]) = cv::Vec3b(0, 0, 255);
// //}
// //std::cout << "xx" << std::endl;
// }
// }
// //对四个方向进行进一步进行过滤,黑白间隔跨度阈值限定
// if ((!iFlag))
// {
// colors[vPts[c].Label] = 0;
// }
//}
//二次过滤
//cv::parallel_for_(cv::Range(0, Y), [&](const cv::Range& range)->void {
// for (int y = range.start; y < range.end; y++)
// {
// uint8_t *ptrRow = binary.ptr<uint8_t>(y);
// for (int x = 0; x < X; x++)
// {
// int label = labels.ptr<int>(y)[x];
// CV_Assert(0 <= label && label <= nccomps);
// ptrRow[x] = colors[label];
// }
// }
//});
//cv::Mat binPrev;
//cv::morphologyEx(label, binPrev, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(iBlockSize, iBlockSize)));
////用于轮廓检测(最终过滤过的图)
//std::vector<cv::Vec4i> hierarchy;
//std::vector<std::vector<cv::Point>> contourAll, contourFilter;
//findContours(binPrev, contourAll, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
//for (int i = 0; i < static_cast<int>(contourAll.size()); i++)
//{
// cv::RotatedRect rect = cv::minAreaRect(contourAll[i]);
// double dRate = rect.size.width / rect.size.height;
// std::vector<cv::Point> approx;
// cv::approxPolyDP(cv::Mat(contourAll[i]), approx, cv::arcLength(cv::Mat(contourAll[i]), true)*0.02, true);
// //满足四边形条件
// if (dRate >= (1. - dToleErr) && dRate <= (1. + dToleErr) && (approx.size() >= 4 && approx.size() < 8) && (cv::contourArea(contourAll[i]) > std::pow(iBlockSize * 12 * (1. - dToleErr), 2)))
// {
// contourFilter.push_back(contourAll[i]);
// }
//}
//if (contourFilter.size() < 1)
//{
// return FUNC_CANNOT_CALC;
//}
return FUNC_OK;
}
int eyemDetectAndDecodeUseNN(EyemImage tpImage, EyemRect tpRoi, IntPtr *hObject, EyemBarCode **hResults, int *ipNum, int iBlockSize, int iRangeC, double dMinorStep)
{
cv::Mat image = cv::Mat(tpImage.iHeight, tpImage.iWidth, MAKETYPE(tpImage.iDepth, tpImage.iChannels), tpImage.vpImage);
if (image.empty()) {
return FUNC_IMAGE_NOT_EXIST;
}
//识别
std::vector<cv::Rect> points;
auto ret = detector->detect(image, points);
//解码
for (int i = 0; i < ret.size(); i++)
{
cv::Mat dst;
cv::resize(ret[i], dst, cv::Size(140, 140));
std::vector<cv::Mat> scaled = detector->getScaleMap(dst);
}
//画图
if (image.channels() != 3) {
cv::cvtColor(image, image, cv::COLOR_GRAY2BGR);
}
for (auto point : points) {
cv::rectangle(image, point, cv::Scalar(0, 255, 0), 2);
}
return FUNC_OK;
}
int eyemInitNNDataCodeModel(const char *detectorConfigPath, const char *detectorModelPath, const char *superResolutionConfigPath, const char *superResolutionModelPath)
{
try
{
detector = cv::makePtr<NNDetector>(detectorConfigPath, detectorModelPath, superResolutionConfigPath, superResolutionModelPath);
}
catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
return FUNC_CANNOT_CALC;
}
return FUNC_OK;
}
bool eyemDetectAndDecodeFree(IntPtr hObject)
{
std::vector<EyemBarCode> *tpResults = reinterpret_cast<std::vector<EyemBarCode>*>(hObject);
//清空容器
tpResults->clear();
//释放
delete tpResults;
tpResults = NULL;
return true;
}