eyemBarCode.cpp
54.4 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
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
#include "eyemBarCode.h"
static cv::Mat getQRRegion(cv::Mat src, cv::RotatedRect rect, double angle)
{
cv::Point center = rect.center;
// 获得左上角和右下角的角点,而且要保证不超出图片范围,用于抠图
cv::Point TopLeft = cv::Point(cvRound(center.x), cvRound(center.y)) - cv::Point(cvRound(rect.size.height / 2), cvRound(rect.size.width / 2));
TopLeft.x = TopLeft.x > src.cols ? src.cols : TopLeft.x;
TopLeft.x = TopLeft.x < 0 ? 0 : TopLeft.x;
TopLeft.y = TopLeft.y > src.rows ? src.rows : TopLeft.y;
TopLeft.y = TopLeft.y < 0 ? 0 : TopLeft.y;
int after_width, after_height;
if (TopLeft.x + rect.size.width > src.cols) {
after_width = src.cols - TopLeft.x - 1;
}
else {
after_width = cvRound(rect.size.width) - 1;
}
if (TopLeft.y + rect.size.height > src.rows) {
after_height = src.rows - TopLeft.y - 1;
}
else {
after_height = cvRound(rect.size.height) - 1;
}
// 获得二维码的位置
cv::Rect RoiRect = cv::Rect(TopLeft.x, TopLeft.y, after_width, after_height);
// dst是被旋转的图片,roi为输出图片,mask为掩模
cv::Mat mask, roi, dst;
cv::Mat image;
// 建立中介图像辅助处理图像
std::vector<cv::Point> contour;
// 获得矩形的四个点
cv::Point2f points[4];
rect.points(points);
for (int i = 0; i < 4; i++)
contour.push_back(points[i]);
std::vector<std::vector<cv::Point>> contours;
contours.push_back(contour);
// 再中介图像中画出轮廓
drawContours(mask, contours, 0, cv::Scalar(255, 255, 255), -1);
// 通过mask掩膜将src中特定位置的像素拷贝到dst中。
src.copyTo(dst, mask);
// 旋转
cv::Mat M = getRotationMatrix2D(center, angle, 1);
warpAffine(dst, image, M, src.size());
// 截图
return image(RoiRect);
}
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;
}
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 = 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, 25);
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);
}
//如果未解码,判断可能是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)));
//一维码识别
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));
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
}
}
}
}
//解码成功
breakLoop:
{
if (strResult != std::string())
{
bDecode = true;
}
}
}
}
//判断是否解码
if (bDecode)
{
decodeResults.push_back(DecodeResult(waitAreas[i].angle, ptResult, strResult, strResultType));
cv::putText(showMat, strResult, ptResult, cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(0, 0, 255));
}
}
//离开线程锁
mtx.unlock();
}
static int calcHist(cv::Mat src)
{
const int histSize = 256;
float range[] = { 0,255 };
const float* histRange = { range };
//calculate the histogram
cv::Mat hist;
cv::calcHist(&src, 1, 0, cv::Mat(), hist, 1, &histSize, &histRange);
//calculate the background pixels
int maxIdx[2] = { 255,255 };
cv::minMaxIdx(hist, NULL, NULL, NULL, maxIdx);
return maxIdx[0];
}
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, tpImage.iDepth, tpImage.vpImage);
if (src.empty()) {
return FUNC_IMAGE_NOT_EXIST;
}
//提取ROI
src = src(cv::Rect(tpRoi.iXs, tpRoi.iYs, tpRoi.iWidth, tpRoi.iHeight));
//真实图像数据与尺寸
cv::Mat realSrc = src.clone();
int iRealX = realSrc.cols, iRealY = realSrc.rows, iRealBlockSize = iBlockSize;
//降采样
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 iX = src.cols, iY = src.rows;
//测试用
if (dScaleUpAndDown != 1.)
{
//太小则不考虑缩小窗口尺寸
if (iBlockSize > 3)
{
iBlockSize = cvRound((double)(iBlockSize + 1)*dScaleUpAndDown) % 2 == 0 ? cvRound((double)(iBlockSize + 1)*dScaleUpAndDown) - 1 : cvRound((double)(iBlockSize + 1)*dScaleUpAndDown) - 1;
}
}
//高斯滤波去噪
cv::Mat srcPrev, binary, mask;
//确定识别类型
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;
//检测热点图,s1用来检测一维码;s2用来检测二维码(条码来说会比背景值小,二维码来说会比背景值大)
cv::Mat s1(iY, iX, CV_8UC1, cv::Scalar(0)), s2(iY, iX, CV_8UC1, cv::Scalar(0));
//<//////////////////////通用预处理方式//////////////////////>//
cv::adaptiveThreshold(src, binary, 255, cv::ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY_INV, iBlockSize, 2);
//突出条码部分
cv::morphologyEx(src, srcPrev, cv::MORPH_GRADIENT, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)));
//二值化
cv::Mat srcPrevBin;
cv::threshold(srcPrev, srcPrevBin, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
//略微膨胀覆盖条码
cv::morphologyEx(srcPrevBin, srcPrevBin, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(iBlockSize, iBlockSize)));
//尽量去掉无关区域
cv::bitwise_and(srcPrevBin, binary, binary);
//连通域分析
cv::Mat labels, stats, centroids;
int nccomps = cv::connectedComponentsWithStats(binary, labels, stats, centroids);
//过滤连通域面积及长/宽比例不符合的,允许50%误差
std::vector<uchar> colors(nccomps + 1, 0);
for (int i = 1; i < nccomps; i++) {
colors[i] = 255;
double maxSize = cv::max(stats.ptr<int>(i)[cv::CC_STAT_WIDTH], stats.ptr<int>(i)[cv::CC_STAT_HEIGHT]);
if ((stats.ptr<int>(i)[cv::CC_STAT_AREA] < 15) || (maxSize < ((double)iBlockSize)*(1. - dToleErr)) || (maxSize > 35 * iBlockSize))
{
colors[i] = 0;
}
}
//过滤
cv::parallel_for_(cv::Range(0, iY), [&](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 < iX; x++)
{
int label = labels.ptr<int>(y)[x];
CV_Assert(0 <= label && label <= nccomps);
ptrRow[x] = colors[label];
}
}
});
//膨胀区域
cv::Mat binaryEx;
cv::morphologyEx(binary, binaryEx, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(iBlockSize * 2, iBlockSize * 2)));
//连通域分析
nccomps = cv::connectedComponentsWithStats(binaryEx, labels, stats, centroids);
for (int i = 1; i < nccomps; i++)
{
//角点响应图
cv::Mat harMap;
cv::Rect rec(stats.ptr<int>(i)[cv::CC_STAT_LEFT], stats.ptr<int>(i)[cv::CC_STAT_TOP], stats.ptr<int>(i)[cv::CC_STAT_WIDTH], stats.ptr<int>(i)[cv::CC_STAT_HEIGHT]);
if ((cv::max(rec.size().width, rec.size().height) > 5 * iBlockSize) && (rec.area() > 5 * std::pow(iBlockSize, 2)))
{
cv::cornerHarris(src(rec), harMap, iBlockSize, 3, 0.04);
// 归一化与转换
cv::normalize(harMap, harMap, 0, 255, cv::NORM_MINMAX, CV_32FC1, cv::Mat());
cv::convertScaleAbs(harMap, harMap);
// 尺寸
cv::Size sz = rec.size();
// 用于一维码检测
cv::Mat m1 = harMap < calcHist(harMap);
const uchar *s1ptr = m1.data;
uchar *d1ptr = s1.data;
// 叠加图像
cv::parallel_for_(cv::Range(0, sz.height), [&](const cv::Range& range)->void {
for (int y = range.start; y < range.end; y++) {
for (int x = 0; x < sz.width; x++) {
d1ptr[(x + rec.x) + (y + rec.y)*iX] += s1ptr[(x)+(y)*sz.width];
}
}
});
// 用于二维码检测
cv::Mat m2 = harMap > calcHist(harMap);
const uchar *s2ptr = m2.data;
uchar *d2ptr = s2.data;
// 叠加图像
cv::parallel_for_(cv::Range(0, sz.height), [&](const cv::Range& range)->void {
for (int y = range.start; y < range.end; y++) {
for (int x = 0; x < sz.width; x++) {
d2ptr[(x + rec.x) + (y + rec.y)*iX] += s2ptr[(x)+(y)*sz.width];
}
}
});
}
}
//输出解码结果
std::vector<EyemBarCode> *tpResults = new std::vector<EyemBarCode>();
//解码内容
std::vector<DecodeResult> decodeResults;
//待解码区域,区分条码类型来识别
std::vector<WaitArea> waitAreas;
//判断要增加的识别,从这一步可以进行分开处理
if (addOneDReader)
{
//添加一维码识别
cv::morphologyEx(binary, mask, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(2 * iBlockSize + 1, 2 * iBlockSize + 1)));
//去掉干扰
cv::bitwise_and(s1, mask, s1);
///<进一步去除干扰
cv::morphologyEx(s1, s1, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(5, 5)));
//连通域分析
nccomps = cv::connectedComponentsWithStats(s1, labels, stats, centroids);
std::vector<uchar> colors2(nccomps + 1, 0);
for (int i = 1; i < nccomps; i++) {
colors2[i] = 255;
if ((stats.ptr<int>(i)[cv::CC_STAT_AREA] < std::pow(iBlockSize, 2)))
{
colors2[i] = 0;
}
}
//过滤
cv::parallel_for_(cv::Range(0, iY), [&](const cv::Range& range)->void {
for (int y = range.start; y < range.end; y++)
{
uint8_t *ptrRow = s1.ptr<uint8_t>(y);
for (int x = 0; x < iX; x++)
{
int label = labels.ptr<int>(y)[x];
CV_Assert(0 <= label && label <= nccomps);
ptrRow[x] = colors2[label];
}
}
});
//后续识别
}
//添加二维码识别
if (addTwoDReader)
{
//突出条码部分
cv::morphologyEx(src, srcPrev, cv::MORPH_BLACKHAT, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(2 * iBlockSize + 1, 2 * iBlockSize + 1)));
//二值化,用于分割粘连
cv::Mat srcPrevBin;
cv::threshold(srcPrev, srcPrevBin, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
//
cv::morphologyEx(srcPrevBin, srcPrevBin, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(cvRound((double)iBlockSize / 3.), cvRound((double)iBlockSize / 3.))));
//断裂处连接在一起
cv::morphologyEx(s2, s2, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(2 * iBlockSize + 1, 2 * iBlockSize + 1)));
//去除干扰
cv::bitwise_and(srcPrevBin, s2, s2);
//对图像过滤
cv::Mat labels, stats, centroids;
int nccomps = cv::connectedComponentsWithStats(s2, 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)) && ((double)stats.ptr<int>(i)[cv::CC_STAT_AREA] > std::pow(20 * 1.414* dScaleUpAndDown, 2))))
{
colors[i] = 0;
}
}
//第一次过滤
cv::parallel_for_(cv::Range(0, iY), [&](const cv::Range& range)->void {
for (int y = range.start; y < range.end; y++)
{
uint8_t *ptrRow = s2.ptr<uint8_t>(y);
for (int x = 0; x < iX; 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(s2, contourAll, cv::noArray(), cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
for (int i = 0; i < static_cast<int>(contourAll.size()); i++)
{
cv::RotatedRect rec = cv::minAreaRect(contourAll[i]);
//偏移量
cv::Point2f pts[4];
rec.points(pts);
cv::Point ptStart, ptEnd;
ptStart = cv::Point((pts[0] + pts[3]) / 2.); ptEnd = cv::Point((pts[1] + pts[2]) / 2.);
//满足矩形条件与面积条件
double dRate = cv::min(rec.size.width, rec.size.height) / cv::max(rec.size.height, rec.size.width);
if (dRate >= (1. - dToleErr) && dRate <= (1. + dToleErr) && cv::min(rec.size.width, rec.size.height) > 20)
{
int dynSize = cvRound(cv::max((double)rec.boundingRect().size().height, (double)rec.boundingRect().size().width));
cv::Mat waitArea = src(cv::Range(cv::max(0, cvRound(rec.center.y) - (2 * iBlockSize + dynSize / 2)), cv::min(iY - 1, cvRound(rec.center.y) + (2 * iBlockSize + dynSize / 2))), cv::Range(cv::max(0, cvRound(rec.center.x) - (2 * iBlockSize + dynSize / 2)), cv::min(iX - 1, cvRound(rec.center.x) + (2 * iBlockSize + dynSize / 2))));
//计算响应图
cv::Mat harMap;
cv::cornerHarris(waitArea, harMap, iBlockSize, 3, 0.04);
// 归一化与转换
cv::normalize(harMap, harMap, 0, 255, cv::NORM_MINMAX, CV_32FC1, cv::Mat());
cv::convertScaleAbs(harMap, harMap);
//进一步判断
cv::Mat m2 = harMap > calcHist(harMap);
//用于轮廓检测
std::vector<std::vector<cv::Point>> contours;
findContours(m2, contours, cv::noArray(), cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
//最大轮廓
std::vector<cv::Point> contourMax = contours[0];
for (int cc = 0; cc < contours.size(); cc++)
{
if (cv::contourArea(contours[cc]) > cv::contourArea(contourMax))
{
contourMax = contours[cc];
}
}
//未过滤前
cv::rectangle(showMat, cv::minAreaRect(contourAll[i]).boundingRect(), cv::Scalar(0, 0, 255), 1);
rec = cv::minAreaRect(contourMax);
dRate = cv::min(rec.size.width, rec.size.height) / cv::max(rec.size.height, rec.size.width);
//判断比例
if (dRate >= (1. - dToleErr) && dRate <= (1. + dToleErr) && cv::min(rec.size.width, rec.size.height) > 20)
{
//按照比例过滤
int flags = 0;
double test_line[6]{ 0 };
cv::LineIterator it(binary, ptStart, ptEnd, 4);
uint8_t future_pixel = 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[flags]++;
if (next_pixel != future_pixel)
{
flags++;
future_pixel = 255 - future_pixel;
if (flags == 6) { break; }
}
}
//满足比例
double dRate = cv::min((test_line[0] + test_line[2] + test_line[4]), (test_line[1] + test_line[3] + test_line[5])) / cv::max((test_line[0] + test_line[2] + test_line[4]), (test_line[1] + test_line[3] + test_line[5]));
if (dRate >= (1. - dToleErr) && dRate <= (1. + dToleErr) && flags >= 6)
{
//符合特征
cv::line(showMat, ptStart, ptEnd, cv::Scalar(0, 255, 255), 1);
cv::rectangle(showMat, cv::minAreaRect(contourAll[i]).boundingRect(), cv::Scalar(0, 255, 0), 1);
}
}
}
}
//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 = realSrc(cv::Range(cv::max(0, cvRound(rRect.center.y / dScaleUpAndDown) - cvRound(4.*(double)iBlockSize + dynSize / 2)), cv::min(realSrc.rows - 1, cvRound(rRect.center.y / dScaleUpAndDown) + cvRound(4.*(double)iBlockSize + dynSize / 2))), cv::Range(cv::max(0, cvRound(rRect.center.x / dScaleUpAndDown) - cvRound(4.*(double)iBlockSize + dynSize / 2)), cv::min(realSrc.cols - 1, cvRound(rRect.center.x / dScaleUpAndDown) + cvRound(4.*(double)iBlockSize + dynSize / 2))));
// //处理后再压入识别
// 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);
// //cv::Point2f points[4];
// //rec.points(points);
// //for (int j = 0; j < 4; j++)
// //{
// // cv::line(showMat, points[j], points[(j + 1) % 4], cv::Scalar(0, 165, 255, 255), 1);
// //}
//}
}
//最后解码用原图来解码
//格式化文件名
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::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(iY, iX, CV_8UC1, cv::Scalar(0));
cv::parallel_for_(cv::Range(0, iY), [&](const cv::Range& range)->void {
for (int y = range.start; y < range.end; y++)
{
for (int x = 0; x < iX; x++)
{
if (harMap.ptr<uint8_t>(y)[x] < maxIdx[0])
{
s1.ptr<uint8_t>(y)[x] = 255;
}
else if (harMap.ptr<uint8_t>(y)[x] > maxIdx[0])
{
s2.ptr<uint8_t>(y)[x] = 255;
}
}
}
});
if (addOneDReader)
{
//测试用
cv::morphologyEx(binary, binary, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(iBlockSize, iBlockSize)));
cv::Mat binFilter;
cv::adaptiveThreshold(realSrc, binFilter, 255, cv::ADAPTIVE_THRESH_GAUSSIAN_C, cv::THRESH_BINARY_INV, iBlockSize, 2);
//去掉非条码部分
cv::bitwise_and(binFilter, binary, binFilter);
//连通域分析
cv::Mat labels, stats, centroids;
int nccomps = cv::connectedComponentsWithStats(binFilter, labels, stats, centroids);
//过滤连通域面积及长/宽比例不符合的,允许50%误差
std::vector<uchar> colors(nccomps + 1, 0);
for (int i = 1; i < nccomps; i++) {
colors[i] = 255;
double maxSize = cv::max(stats.ptr<int>(i)[cv::CC_STAT_WIDTH], stats.ptr<int>(i)[cv::CC_STAT_HEIGHT]);
if ((stats.ptr<int>(i)[cv::CC_STAT_AREA] < 15) | (maxSize < iBlockSize*(1. + dToleErr)) | (maxSize > 25 * iBlockSize))
{
colors[i] = 0;
}
}
//过滤
cv::parallel_for_(cv::Range(0, iY), [&](const cv::Range& range)->void {
for (int y = range.start; y < range.end; y++)
{
uint8_t *ptrRow = binFilter.ptr<uint8_t>(y);
for (int x = 0; x < iX; x++)
{
int label = labels.ptr<int>(y)[x];
CV_Assert(0 <= label && label <= nccomps);
ptrRow[x] = colors[label];
}
}
});
cv::Mat back4Filter = binFilter.clone();
//cv::cvtColor(back4Filter, showMat, cv::COLOR_GRAY2BGR);
//用于轮廓检测
std::vector<std::vector<cv::Point>> contourAll, contourFilter;
findContours(binFilter, contourAll, cv::noArray(), cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
//初步过滤
for (int i = 0; i < int(contourAll.size()); i++)
{
cv::RotatedRect rect = cv::minAreaRect(contourAll[i]);
double dRate = (double)cv::max(rect.size.height, rect.size.width) / (double)cv::min(rect.size.height, rect.size.width), rgt = cv::contourArea(contourAll[i]) / rect.size.area();
if (!(cv::min(rect.size.height, rect.size.width) > iBlockSize * 4) && (cv::contourArea(contourAll[i]) / rect.size.area()) > 0.35)
{
contourFilter.push_back(contourAll[i]);
}
else
cv::drawContours(binFilter, contourAll, i, cv::Scalar(0), -1);
}
const float tipLength = 128;
for (int c = 0; c < 8; c++)
{
std::vector<cv::Point> approx;
//符合条件,继续增加比例过滤条件
for (int i = 0; i < int(contourFilter.size()); i++)
{
//首先进行四边形过滤
cv::approxPolyDP(cv::Mat(contourFilter[i]), approx, cv::arcLength(cv::Mat(contourFilter[i]), true)*0.02, true);
if (approx.size() > 10)
{
cv::drawContours(binFilter, contourFilter, i, cv::Scalar(0), -1);
continue;
}
cv::RotatedRect rect = cv::minAreaRect(contourFilter[i]);
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.); ptEnd = cv::Point((pts[1] + pts[2]) / 2.);
}
else
{
ptStart = cv::Point((pts[0] + pts[1]) / 2.); ptEnd = cv::Point((pts[2] + pts[3]) / 2.);
}
ptMid = (ptStart + ptEnd) / 2;
double _angle = std::atan2(-(ptEnd.x - ptStart.x), ptEnd.y - ptStart.y);
cv::Point pt[2];
pt[0] = cv::Point(cvRound(ptMid.x + tipLength * cos(_angle)),
cvRound(ptMid.y + tipLength * sin(_angle)));
pt[1] = cv::Point(cvRound(ptMid.x + tipLength * cos(_angle + CV_PI)),
cvRound(ptMid.y + tipLength * sin(_angle + CV_PI)));
//防止越界
for (int n = 0; n < 2; n++)
{
if (pt[n].x < 0) pt[n].x = 0.f; if (pt[n].x >= iX - 1) pt[n].x = float(iX - 1); if (pt[n].y < 0) pt[n].y = 0.f; if (pt[n].y >= iY - 1) pt[n].y = float(iY - 1);
}
bool bFit = false;
//扫描像素密度,比例接近1:1记录下来,并且黑白间隔数目小大于长度的一半
for (int ii = 0; ii < 2; ii++)
{
int flags = 0;
double test_line[6]{ 0 };
cv::LineIterator it(back4Filter, ptMid, pt[ii], 4);
uint8_t future_pixel = back4Filter.ptr<uint8_t>(ptMid.y)[ptMid.x];
for (int n = 0; n < it.count; n++, ++it)
{
//统计均匀性
uint8_t next_pixel = back4Filter.ptr<uint8_t>(it.pos().y)[it.pos().x];
//统计黑白像素
test_line[flags]++;
if (next_pixel != future_pixel)
{
flags++;
future_pixel = 255 - future_pixel;
if (flags == 6) { break; }
}
}
//满足比例
double dRate = cv::min((test_line[0] + test_line[2] + test_line[4]), (test_line[1] + test_line[3] + test_line[5])) / cv::max((test_line[0] + test_line[2] + test_line[4]), (test_line[1] + test_line[3] + test_line[5]));
if (dRate >= (1. - dToleErr*1.5) && dRate <= (1. + dToleErr*1.5) && flags >= 6)
{
bFit = true;
//符合条码特征
break;
}
}
if (!bFit)
{
//不符合条码特征
cv::drawContours(binFilter, contourFilter, i, cv::Scalar(0), -1);
}
}
findContours(binFilter, contourFilter, cv::noArray(), cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
back4Filter = binFilter;
}
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 (s1.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 >= iX - 1) pt[n].x = float(iX - 1); if (pt[n].y < 0) pt[n].y = 0.f; if (pt[n].y >= iY - 1) pt[n].y = float(iY - 1);
}
//用采样的方式提取待解码区域
cv::LineIterator itStHeight(realSrc, pt[0], pt[1], 4);
cv::LineIterator itEdHeight(realSrc, pt[3], pt[2], 4);
cv::LineIterator itStWidth(realSrc, pt[0], pt[3], 4);
cv::LineIterator itEdWidth(realSrc, 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(realSrc, 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] = realSrc.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]), _angle*180. / PI, true, oneDMats));
}
}
}
}
}
if (addTwoDReader)
{
//断裂处连接在一起
cv::morphologyEx(m2, m2, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(cvRound(iBlockSize*dScaleUpAndDown), cvRound(iBlockSize*dScaleUpAndDown))));
//去掉无关区域
cv::bitwise_and(binary, 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, iY), [&](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 < iX; 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 = realSrc(cv::Range(cv::max(0, cvRound(rRect.center.y / dScaleUpAndDown) - cvRound(4.*(double)iBlockSize*dScaleUpAndDown + dynSize / 2)), cv::min(realSrc.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(realSrc.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);
return FUNC_OK;
}
int eyemCalcDetectParameter(EyemImage tpImage, EyemRect tpRoi, const char *ccFileName, bool bTrainOneD, int iBlockSize, int *ipNum, int *iSymbolMin, int *iSymbolMax)
{
cv::Mat src = cv::Mat(tpImage.iHeight, tpImage.iWidth, tpImage.iDepth, tpImage.vpImage);
if (src.empty()) {
return FUNC_IMAGE_NOT_EXIST;
}
//提取ROI
src = src(cv::Rect(tpRoi.iXs, tpRoi.iYs, tpRoi.iWidth, tpRoi.iHeight));
//用于显示
cv::Mat showMat;
cv::cvtColor(src, showMat, cv::COLOR_GRAY2BGR);
//图像尺寸
int X = src.cols, Y = src.rows;
//高斯滤波去噪
cv::Mat srcPrev, binary;
cv::GaussianBlur(src, srcPrev, cv::Size(iBlockSize, iBlockSize), 0.3);
//计算角点响应
cv::Mat harMap;
cv::cornerHarris(src, harMap, iBlockSize, 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;
}
}
}
});
//允许误差
const double dToleErr = 0.35;
//所有解码内容
std::vector<DecodeResult> decodeResults;
//待解码区域,区分条码类型来识别
std::vector<WaitArea> waitAreas;
//是否是计算一维码参数
if (bTrainOneD)
{
//对于一维码如何确定参数,暂时按照能识别到的个数来判断
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] < 20) | (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(src, binFilter, 255, cv::ADAPTIVE_THRESH_GAUSSIAN_C, cv::THRESH_BINARY_INV, iBlockSize, 5);
//处理断裂一维码
cv::morphologyEx(m1, m1, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(iBlockSize, iBlockSize)));
//用于轮廓检测
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*(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.); ptEnd = cv::Point((pts[1] + pts[2]) / 2.);
}
else
{
ptStart = cv::Point((pts[0] + pts[1]) / 2.); ptEnd = cv::Point((pts[2] + pts[3]) / 2.);
}
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))[cvRound(it.pos().x)] == 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;
}
}
//满足比例
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 / 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(src, pt[0], pt[1], 4);
cv::LineIterator itEdHeight(src, pt[3], pt[2], 4);
cv::LineIterator itStWidth(src, pt[0], pt[3], 4);
cv::LineIterator itEdWidth(src, 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(src, pairStEd[n].PosS, pairStEd[n].PosE, 4);
for (int nn = 0; nn < it.count; nn++, ++it)//列
{
srcSampling.ptr<uint8_t>(0)[nn] = src.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)
{
waitAreas.push_back(WaitArea(cv::Mat(), ptMid, getThreshVal_Otsu_8u(oneDMats[0]), _angle*180. / PI, true, oneDMats));
}
}
}
}
}
else
{
//按照识别到码的定位块尺寸来确定参数,如果是DM码该如何确定参数?
//断裂处连接在一起
cv::morphologyEx(m2, m2, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(iBlockSize, iBlockSize)));
//去掉无关区域
cv::bitwise_and(binary, 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 * 15 * 1.414*(1. + dToleErr)) | (stats.ptr<int>(i)[cv::CC_STAT_HEIGHT] > iBlockSize * 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)) && ((double)rect.size.height > double(8. * iBlockSize)))
{
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, (double)rect.size().width));
//疑似二维码区域
cv::Mat waitArea = src(cv::Range(cv::max(0, cvRound(rRect.center.y) - cvRound(4.*(double)iBlockSize + dynSize / 2)), cv::min(Y - 1, cvRound(rRect.center.y) + cvRound(4.*(double)iBlockSize + dynSize / 2))), cv::Range(cv::max(0, cvRound(rRect.center.x) - cvRound(4.*(double)iBlockSize + dynSize / 2)), cv::min(X - 1, cvRound(rRect.center.x) + cvRound(4.*(double)iBlockSize + dynSize / 2)))).clone();
//处理后再压入识别
waitAreas.push_back(WaitArea(waitArea, cv::Point(cvRound(rRect.center.x), cvRound(rRect.center.y)), 0, 0, false, std::vector<cv::Mat>()));
}
}
std::vector<std::string> hints_ = { "AZTEC","CODABAR","CODE_39","CODE_93","CODE_128","DATA_MATRIX","EAN_8","EAN_13","ITF","MAXICODE","PDF_417","QR_CODE","RSS_14","RSS_EXPANDED","UPC_A","UPC_E","UPC_EAN_EXTENSION" };
//解码
decodeMul(waitAreas, hints_, showMat, decodeResults, iBlockSize, 10, 1.0);
return FUNC_OK;
}
bool eyemDetectAndDecodeFree(IntPtr hObject)
{
std::vector<EyemBarCode> *tpResults = reinterpret_cast<std::vector<EyemBarCode>*>(hObject);
delete tpResults;
tpResults = NULL;
return true;
}