eyemMisc.cpp
286.7 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
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
#ifdef _WIN32
#include <io.h>
#include <Windows.h>
#elif __linux__
#include <sys/stat.h>
#endif
#include <fstream>
#include "eyemMisc.h"
#pragma region 一些参数计算公式
/* 弦长计算公式
已知半径R。设该弦长所对的圆心角为φ,弦长为C,C=2Rsin(φ/2).
*/
#pragma endregion
#pragma region 内部使用的函数
/** 计算端点坐标
img 输入图像
*/
static void drawLine(cv::InputOutputArray img, cv::Point pt1, cv::Point pt2, const cv::Scalar& color, int thickness, double tipLength, double trackLength, std::vector<cv::Point> &trackLine)
{
const double angle = atan2((double)pt1.y - pt2.y, (double)pt1.x - pt2.x);
cv::Point p(cvRound(pt2.x + tipLength * cos(angle + CV_PI / 2)),
cvRound(pt2.y + tipLength * sin(angle + CV_PI / 2)));
//cv::arrowedLine(img, pt2, p, cv::Scalar(0, 0, 255, 255), 1, 8, 0, 0.4);
p.x = cvRound(pt2.x + tipLength * cos(angle - CV_PI / 2));
p.y = cvRound(pt2.y + tipLength * sin(angle - CV_PI / 2));
//cv::arrowedLine(img, pt2, p, cv::Scalar(0, 0, 255, 255), 1, 8, 0, 0.4);
p = cv::Point(cvRound(pt2.x + tipLength * cos(angle)),
cvRound(pt2.y + tipLength * sin(angle)));
//cv::arrowedLine(img, pt2, p, color, 1, 8, 0, 0.3);
//位置
p = cv::Point(cvRound(pt2.x + trackLength * cos(angle)),
cvRound(pt2.y + trackLength * sin(angle)));
trackLine.push_back(p);
p = cv::Point(cvRound(pt2.x + tipLength * cos(angle + CV_PI)),
cvRound(pt2.y + tipLength * sin(angle + CV_PI)));
//cv::arrowedLine(img, pt2, p, color, 1, 8, 0, 0.3);
//位置
p = cv::Point(cvRound(pt2.x + trackLength * cos(angle + CV_PI)),
cvRound(pt2.y + trackLength * sin(angle + CV_PI)));
trackLine.push_back(p);
}
/** 判断坐标是否在矩形中
_Rect 输入矩形
pt 输入坐标
*/
static inline bool isInRect(std::vector<cv::Point2f> _Rect, cv::Point pt)
{
return cv::pointPolygonTest(_Rect, pt, false) > 0;
}
/** 计算矩形内坐标
_vRect 输入矩形
vPoints 输出坐标
*/
static void calcRotateRect(std::vector<cv::Point2f> &vRect, std::vector<cv::Point> &vPoints)
{
cv::Rect _Rect = cv::RotatedRect(vRect[0], vRect[1], vRect[2]).boundingRect();
for (int y = _Rect.y; y < _Rect.y + _Rect.height; y++)
{
for (int x = _Rect.x; x < _Rect.x + _Rect.width; x++)
{
if (isInRect(vRect, cv::Point(x, y)))
{
vPoints.push_back(cv::Point(x, y));
}
}
}
}
/** 计算旋转矩形
pt 输入坐标
t 输入角度
length 输入长度
width 输入宽度
pts 输出坐标
*/
static void calcRotateRect(cv::Point2f pt, float t, float length, float width, cv::Point2f *pts)
{
float b = (float)cos(t*PI / 180.)*0.5f;
float a = (float)sin(t*PI / 180.)*0.5f;
pts[0].x = (float)(pt.x - a*length * 2 - b*width * 4);
pts[0].y = (float)(pt.y + b*length * 2 - a*width * 4);
pts[1].x = (float)(pt.x + a*length * 2 - b*width * 4);
pts[1].y = (float)(pt.y - b*length * 2 - a*width * 4);
pts[2].x = (float)(2 * pt.x - pts[0].x);
pts[2].y = (float)(2 * pt.y - pts[0].y);
pts[3].x = (float)(2 * pt.x - pts[1].x);
pts[3].y = (float)(2 * pt.y - pts[1].y);
}
/** 获取旋转后的模板
_tplMat 输入图像
t 输入角度
val 填充内容
*/
static cv::Mat getTplMat(cv::Mat &tplMat, double t, int val)
{
const int tplH = tplMat.rows, tplW = tplMat.cols;
int width = cvRound((double)tplH * abs(sin(t * CV_PI / 180.)) + (double)tplW * abs(cos(t * CV_PI / 180.)));
int height = cvRound(ceil((double)tplW * abs(sin(t * CV_PI / 180.)) + (double)tplH * abs(cos(t * CV_PI / 180.))));
cv::Mat matx23f(2, 3, CV_64F);
matx23f = cv::getRotationMatrix2D(cv::Point2f((float)tplW / 2.0f - 0.5f, (float)tplH / 2.0f - 0.5f), t, 1.0);
//由于旋转产生的偏移
matx23f.ptr<double>(0)[2] += (float)(width - tplW) / 2.0;
matx23f.ptr<double>(1)[2] += (float)(height - tplH) / 2.0;
//旋转
cv::Mat tplMatD;
cv::warpAffine(tplMat, tplMatD, matx23f, cv::Size((int)width, (int)height), cv::INTER_LINEAR, cv::BORDER_CONSTANT, val);
return tplMatD;
}
/** 获取旋转后的图像
trackMat 输入图像
t 输入角度
val 填充内容
matx 转换矩阵
*/
static cv::Mat getTrackMat(cv::Mat &trackMat, double t, int val, float *matx)
{
const int tckH = trackMat.rows, tckW = trackMat.cols;
int tckdW = cvRound((double)tckH * abs(sin(t * CV_PI / 180.)) + (double)tckW * abs(cos(t * CV_PI / 180.)));
int tckdH = cvRound(ceil((double)tckW * abs(sin(t * CV_PI / 180.)) + (double)tckH * abs(cos(t * CV_PI / 180.))));
//创建矩阵
cv::Mat matx23f(2, 3, CV_64F);
matx23f = cv::getRotationMatrix2D(cv::Point2f((float)tckW / 2.0f - 0.5f, (float)tckH / 2.0f - 0.5f), t, 1.0);
//由于旋转产生的偏移
matx23f.ptr<double>(0)[2] += (float)(tckdW - tckW) / 2.0;
matx23f.ptr<double>(1)[2] += (float)(tckdH - tckH) / 2.0;
//输出矩阵
matx[0] = (float)matx23f.ptr<double>(0)[0]; matx[1] = (float)matx23f.ptr<double>(0)[1]; matx[2] = (float)matx23f.ptr<double>(0)[2];
matx[3] = (float)matx23f.ptr<double>(1)[0]; matx[4] = (float)matx23f.ptr<double>(1)[1]; matx[5] = (float)matx23f.ptr<double>(1)[2];
//仿射变换
cv::Mat tplMatD;
cv::warpAffine(trackMat, tplMatD, matx23f, cv::Size(tckdW, tckdH), cv::INTER_LINEAR, cv::BORDER_CONSTANT, cv::Scalar(val));
return tplMatD;
}
/** 模板追踪匹配
image 输入图像
tplMat 输入模板
t 方位角
trackWidth 扩充宽度
pts 矩形顶点
val 填充像素
bFinal 是否进行精确位置定位
maxVal 输出最大匹配分数
maxLoc 输出最大匹配坐标
mask 掩膜
*/
static bool findTrackModel(cv::Mat& image, cv::Mat &tplMat, double t, double trackWidth, cv::Point2f *pts, int val, bool bFinal, double &maxVal, cv::Point2f &maxLoc, cv::InputArray mask = cv::noArray())
{
//图像尺寸
int X = image.cols, Y = image.rows;
//旋转矩形
cv::RotatedRect r(pts[0], pts[1], pts[2]);
//待匹配图像
cv::Rect rr(cv::Point2i(cv::max(r.boundingRect().x - cvRound(trackWidth), 0), \
cv::max(r.boundingRect().y - cvRound(trackWidth), 0)), \
cv::Point2i(cv::min(r.boundingRect().x + r.boundingRect().width + cvRound(trackWidth), X), \
cv::min(r.boundingRect().y + r.boundingRect().height + cvRound(trackWidth), Y)));
float matx[6];
cv::Mat trackMat = getTrackMat(image(rr&cv::Rect(0, 0, X, Y)).clone(), -t, val, matx);
if (trackMat.cols <= (tplMat.cols - 1) || trackMat.rows <= (tplMat.rows - 1))
return true;
const int icvTemplateMatchModes[2] = { cv::TM_SQDIFF_NORMED,cv::TM_CCOEFF_NORMED };
//计算匹配位置
std::vector<cv::Mat> tplResults(6);
cv::parallel_for_(cv::Range(0, 2), [&](const cv::Range& range)->void {
for (int m = range.start; m < range.end; m++)
{
cv::Mat tplResult;
cv::matchTemplate(trackMat, tplMat, tplResult, icvTemplateMatchModes[m]);
tplResults[icvTemplateMatchModes[m]] = tplResult;
}
});
//tbb::parallel_for(tbb::blocked_range<int>(0, 2), [&](tbb::blocked_range<int>& range) {
// for (int m = range.begin(); m < range.end(); m++)
// {
// cv::Mat tplResult;
// cv::matchTemplate(trackMats[m], tplMats[m], tplResult, icvTemplateMatchModes[m]);
// tplResults[icvTemplateMatchModes[m]] = tplResult;
// }
//});
cv::Mat tplResult0 = tplResults[5] - tplResults[1];
//计算极值坐标
cv::Point maxyyuloc;
cv::minMaxLoc(tplResult0, NULL, &maxVal, NULL, &maxyyuloc);
//偏移到中心
maxyyuloc += cv::Point(tplMat.cols / 2, tplMat.rows / 2);
//结果坐标限制在理论范围内
if (bFinal)
{
//重新确定位置
cv::Rect rLimit(cv::Point((trackMat.cols - tplMat.cols) / 2, (trackMat.rows - tplMat.rows) / 2), tplMat.size());
//判断区域内有效面积所占比例
if ((float)cv::countNonZero(getTplMat(mask.getMat()(rr&cv::Rect(0, 0, X, Y)), -t, 0)(rLimit)) / (float)rLimit.area() < 0.18) {
//料盘结束
return true;
}
if (!rLimit.contains(maxyyuloc))
{
//可能偏离位置,重新确定位置
do
{
maxyyuloc -= cv::Point(tplMat.cols / 2, tplMat.rows / 2);
tplResult0.ptr<float>(maxyyuloc.y)[maxyyuloc.x] = -1.0;
cv::minMaxLoc(tplResult0, NULL, &maxVal, NULL, &maxyyuloc);
maxyyuloc += cv::Point(tplMat.cols / 2, tplMat.rows / 2);
} while (!rLimit.contains(maxyyuloc));
}
}
//计算旋转前的坐标(即匹配的最终坐标)
maxLoc.x = (float)rr.x + (((float)maxyyuloc.x - matx[2])*matx[4] - ((float)maxyyuloc.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
maxLoc.y = (float)rr.y + (((float)maxyyuloc.x - matx[2])*matx[3] - ((float)maxyyuloc.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
return false;
}
/** 分割字符串
cStrText 输入文本
cStrDelim 输入分隔符
vStrs 输出分割后内容
*/
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;
}
/** 载入模板
trackMat 输入文件名
*/
static void loadTrackModel(const char *fileName, cv::OutputArray tplMat, cv::Point &pt, double &dMatchDeg, const char *callFunc = "")
{
std::string logModule = std::string(callFunc) + "->";
logModule += __func__;
logModule += "(" + std::to_string(*(uint32_t *)(&std::this_thread::get_id())) + "):";
struct stat _Stat;
if (stat(fileName, &_Stat) != 0)
return;
//上锁
logger.t(logModule + "上锁...");
logger.t(logModule + "打开文件...");
FILE *fps = NULL;
fopen_s(&fps, fileName, "r");
//判断文件是否打开
if (NULL == fps)
return;
//获取文件大小
const int _Size = (int)_Stat.st_size;
//分配内存
unsigned char *_Data = (unsigned char *)malloc(_Size);
if (NULL == _Data)
return;
//初始化
memset(_Data, 0, _Size);
//读取数据
logger.t(logModule + "读取二进制数据...");
fread(_Data, sizeof(uint8_t), _Size, fps);
//关闭文件
logger.t(logModule + "关闭文件...");
fclose(fps);
//解锁
logger.t(logModule + "解锁...");
//获取图像数据大小
logger.t(logModule + "拷贝头数据...");
unsigned char _SizeData[8];
memcpy(_SizeData, _Data, 8);
//有效信息长度
const int valSize = std::atoi((const char *)_SizeData);
//文件信息
const int tplSize = _Size - valSize - 8;
//拷贝文件信息
logger.t(logModule + "拷贝文件信息...");
char *tplInfo = new char[tplSize];
memcpy(tplInfo, _Data + valSize + 8, tplSize);
//获取文件信息
logger.t(logModule + "分割字符串...");
std::string line(tplInfo);
std::vector<std::string> hints;
split(line, ",", hints);
//宽,高,坐标,匹配度
logger.t(logModule + "文件信息类型转换...");
int X = std::atoi(hints[2].c_str()), Y = std::atoi(hints[3].c_str());
dMatchDeg = std::atof(hints[4].substr(0, 4).c_str()); pt = cv::Point(std::atoi(hints[0].c_str()), std::atoi(hints[1].c_str()));
//创建图像文件
logger.t(logModule + "创建模板图像...");
tplMat.create(Y, X, CV_8UC1, -1, true);
//拷贝数据
logger.t(logModule + "拷贝图像数据...");
cv::Mat _tplMat = tplMat.getMat();
memcpy(_tplMat.data, _Data + 8, valSize);
//释放内存
logger.t(logModule + "释放内存...");
delete[] tplInfo;
tplInfo = NULL;
//释放文件内存
free(_Data);
_Data = NULL;
}
/** 十进制转二进制数
d 输入十进制数字
*/
static std::string DtoB(int d)
{
return "";
}
/** 获取文件夹内所有文件
filePath 输入文件夹
fileNames 输出文件
*/
static void getFiles(std::string filePath, std::vector<std::string>& fileNames)
{
//文件句柄
intptr_t hFile = 0;
//文件信息
struct _finddata_t fileinfo;
std::string p;
if ((hFile = _findfirst(p.assign(filePath).append("\\*").c_str(), &fileinfo)) != -1)
{
do
{
//如果是目录,迭代之,如果不是,加入列表
if ((fileinfo.attrib & _A_SUBDIR)) {
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
getFiles(p.assign(filePath).append("\\").append(fileinfo.name), fileNames);
}
else {
fileNames.push_back(p.assign(filePath).append("\\").append(fileinfo.name));
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
/** 计算Otsu阈值
hist 输入直方图
*/
static int Otsu(int hist[])
{
// Otsu's threshold algorithm
// C++ code by Jordan Bevik <Jordan.Bevic@qtiworld.com>
// ported to ImageJ plugin by G.Landini
int k, kStar; // k = the current threshold; kStar = optimal threshold
double N1, N; // N1 = # points with intensity <=k; N = total number of points
double BCV, BCVmax; // The current Between Class Variance and maximum BCV
double num, denom; // temporary bookeeping
double Sk; // The total intensity for all histogram points <=k
double S, L = 256; // The total intensity of the image
// Initialize values:
S = N = 0;
for (k = 0; k < L; k++) {
S += (double)k * hist[k]; // Total histogram intensity
N += hist[k]; // Total number of data points
}
Sk = 0;
N1 = hist[0]; // The entry for zero intensity
BCV = 0;
BCVmax = 0;
kStar = 0;
// Look at each possible threshold value,
// calculate the between-class variance, and decide if it's a max
for (k = 1; k < L - 1; k++) { // No need to check endpoints k = 0 or k = L-1
Sk += (double)k * hist[k];
N1 += hist[k];
// The float casting here is to avoid compiler warning about loss of precision and
// will prevent overflow in the case of large saturated images
denom = (double)(N1) * (N - N1); // Maximum value of denom is (N^2)/4 = approx. 3E10
if (denom != 0) {
// Float here is to avoid loss of precision when dividing
num = ((double)N1 / N) * S - Sk; // Maximum value of num = 255*N = approx 8E7
BCV = (num * num) / denom;
}
else
BCV = 0;
if (BCV >= BCVmax) { // Assign the best threshold found so far
BCVmax = BCV;
kStar = k;
}
}
return kStar;
}
/** 计算Otsu阈值
_src 输入图像
*/
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;
}
/** 计算元件尺寸
srcPrev 输入图像
mask 输入掩膜
partSize 输出元件尺寸
*/
static bool checkSize(cv::Mat &srcPrev, cv::Mat &mask, int &partSize)
{
int X = srcPrev.cols, Y = srcPrev.rows;
//for fill backgrounds where the reel is not obvious, the component is not split when the OTSU threshold is selected
cv::morphologyEx(mask, mask, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(75, 75)));
//calculate the histogram
int hist[256];
for (int y = 0; y < 256; y++) hist[y] = 0;
for (int y = 0; y < Y; y++)
{
uchar *uPtr = srcPrev.data + y * X;
for (int x = 0; x < srcPrev.cols; x++, uPtr++)
{
if ((mask.data)[(x)+(y)*X] == 255)
{
hist[*uPtr]++;
}
}
}
int meanThresh = Otsu(hist);
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 ((srcPrev.data)[(x)+(y)*X] <= meanThresh)
{
(srcPrev.data)[(x)+(y)*X] = meanThresh;
}
}
}
});
cv::Mat binary;
cv::threshold(srcPrev, binary, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
//connectivity analysis
cv::Mat m1, m2, m3;
int nccomps = cv::connectedComponentsWithStats(binary, m1, m2, m3);
std::vector<uchar> colors(nccomps + 1, 0);
for (int i = 1; i < nccomps; i++) {
colors[i] = 255;
if ((((int *)m2.data)[(cv::CC_STAT_AREA) + (i)*m2.cols] <= 3))//experience
{
colors[i] = 0;
}
}
//think it's sticky
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++)
{
int label = ((int *)m1.data)[(x)+(y)*m1.cols];
CV_Assert(0 <= label && label <= nccomps);
(binary.data)[(x)+(y)*X] = colors[label];
}
}
});
nccomps = cv::connectedComponentsWithStats(binary, m1, m2, m3);
//
if (nccomps <= 1) return false;
//area of the statistical component
std::vector<int> vHist(nccomps);
for (int y = 0; y < Y; y++)
{
int *uPtr = (int *)m1.data + y * X;
for (int x = 0; x < X; x++, uPtr++)
{
vHist[*uPtr]++;
}
}
std::map<int, int> cAreaMap;
for (const auto& v : vHist)
{
std::map<int, int>::iterator it = cAreaMap.find(v);
if (it != cAreaMap.end())
{
it->second++;
continue;
}
else { cAreaMap.insert(std::make_pair(v, 1)); };
}
struct tMap
{
int Key;
int Value;
tMap(int Key, int Value) :Key(Key), Value(Value) {}
bool operator >(const tMap &te)const
{
return Value > te.Value;
}
};
//get a single component area (accuracy to be tested, assuming non-adhesion accounts for the majority).)
std::vector<tMap> tVector;
std::map<int, int>::iterator it;
for (it = cAreaMap.begin(); it != cAreaMap.end(); it++)
{
tVector.push_back(tMap(it->first, it->second));
}
std::sort(tVector.begin(), tVector.end(), std::greater<tMap>());
if (tVector.size() < 3)
{
return false;
}
mask = binary.clone();
//single component
partSize = cvRound((tVector[0].Key + tVector[1].Key) / 2.);
return partSize >= 20;
}
#pragma endregion
int eyemCountObject(EyemImage tpImage, EyemRect tpRoi, const char *fileName, int *ipReelNum, EyemImage *tpDstImg)
{
cv::Mat src = cv::Mat(tpImage.iHeight, tpImage.iWidth, MAKETYPE(tpImage.iDepth, tpImage.iChannels), tpImage.vpImage).clone();
if (src.empty()) {
return FUNC_IMAGE_NOT_EXIST;
}
//转单通道
if (src.channels() != 1)
cv::cvtColor(src, src, cv::COLOR_BGR2GRAY);
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularPartsE 初始阶段被跳过执行...");
return FUNC_CANNOT_CALC;
}
//图像裁剪
src = src(cv::Rect(tpRoi.iXs, tpRoi.iYs, tpRoi.iWidth, tpRoi.iHeight)).clone();
//image size
int X = src.cols, Y = src.rows;
//去除局部量斑影响(默认亮斑尺寸不会大于15个像素)
cv::Mat srcTmp;
cv::morphologyEx(src, srcTmp, cv::MORPH_ERODE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(15, 15)));
//去除黑斑影响
int m = cvRound(cv::mean(src)[0]);
srcTmp.forEach<uint16_t>([&](uint16_t& pixel, const int *pos)->void {
pixel = pixel == 0 ? m : pixel;
});
//image enhancement
double min, max;
cv::Point maxId;
cv::minMaxLoc(srcTmp, &min, &max, NULL, &maxId);
src.convertTo(src, CV_64FC1);
src -= min;
src /= (max - min);
src *= 65535;
src.convertTo(src, CV_16UC1);
cv::Mat src8U;
src.convertTo(src8U, CV_8UC1, 1 / 255.);
//for show
cv::Mat cc;
cv::cvtColor(src8U, cc, cv::COLOR_GRAY2BGRA);
//set bins
const int histSize = 17;
//range of values
float range[] = { 0,255 };
const float* histRange = { range };
//calculate the histogram
cv::Mat hist;
cv::calcHist(&src8U, 1, 0, cv::Mat(), hist, 1, &histSize, &histRange);
//calculate the background pixels
int maxIdx[2] = { 255,255 };
cv::minMaxIdx(hist, NULL, NULL, NULL, maxIdx);
//background thresh
int backThresh = 15 * (maxIdx[0] - 2);//正常-2
//remove the background
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 ((src8U.data)[(x)+(y)*X] >= backThresh)
{
(src8U.data)[(x)+(y)*X] = backThresh;
}
}
}
});
//increases to target brightness
cc += cv::Scalar((162 - backThresh), (162 - backThresh), (162 - backThresh));
//inv
cv::bitwise_not(src8U, src8U);
cv::Mat binary;
cv::threshold(src8U, binary, (255 - backThresh), 255, cv::THRESH_BINARY);
//connected together
cv::morphologyEx(binary, binary, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(45, 45)));
//find the pallet
std::vector<std::vector<cv::Point>> contoursFilter;
cv::findContours(binary, contoursFilter, cv::RETR_TREE, cv::CHAIN_APPROX_NONE);
//填充内部确定料盘
cv::Mat image = cv::Mat::zeros(src8U.size(), CV_8UC1);
for (int i = 0; i < contoursFilter.size(); i++)
{
if (cv::contourArea(contoursFilter[i]) > 100000)
{
cv::drawContours(image, contoursFilter, i, cv::Scalar(255), -1);
}
}
cv::bitwise_not(src8U, src8U);
//剩下即料盘区域(面积大于100000均认为是料盘)
cv::findContours(image, contoursFilter, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
//区分多个料盘
struct TrayPos
{
int iDir = -1;//0左上1左下2右下3右上
double dBackThresh;
bool bSorted;
cv::Point2f Center;
cv::Mat Tray;
TrayPos() {};
TrayPos(cv::Point2f center, cv::Mat tray, bool bSorted, double dBackThresh) :Center(center), Tray(tray), bSorted(bSorted), dBackThresh(dBackThresh) {}
};
std::vector <TrayPos> trays;
for (int i = 0; i < contoursFilter.size(); i++)
{
//定位中心
cv::Moments mu = cv::moments(contoursFilter[i]);
cv::Point reelCenter(cvRound(mu.m10 / mu.m00), cvRound(mu.m01 / mu.m00));
//掩膜
cv::Mat trayMask = cv::Mat::zeros(Y, X, CV_8UC1);
cv::drawContours(trayMask, contoursFilter, i, cv::Scalar(255), -1);
//
cv::Mat tray = cv::Mat(Y, X, CV_8UC1, backThresh);
src8U.copyTo(tray, trayMask);
trays.push_back(TrayPos(reelCenter, tray, false, backThresh));
}
//判断可能无料,不能100%判断
if (trays.size() < 1)
{
std::string strTrayNum = "无料,";
for (int i = 0; i < 4; i++) {
ipReelNum[i] = 0;
}
return FUNC_CANNOT_CALC;
}
//图像中心
cv::Point reelCenter(X / 2, Y / 2);
//料盘排序
std::vector <TrayPos> sortedTrays;
for (int i = 0; i < trays.size(); i++)
{
//左上角
if (trays[i].Center.x < reelCenter.x&&trays[i].Center.y < reelCenter.y)
{
if (trays[i].bSorted == false)
{
trays[i].iDir = 0;
trays[i].bSorted = true;
sortedTrays.push_back(trays[i]);
}
}
}
for (int i = 0; i < trays.size(); i++)
{
//左下角
if (trays[i].Center.x < reelCenter.x&&trays[i].Center.y > reelCenter.y)
{
if (trays[i].bSorted == false)
{
trays[i].iDir = 1;
trays[i].bSorted = true;
sortedTrays.push_back(trays[i]);
}
}
}
for (int i = 0; i < trays.size(); i++)
{
//右下角
if (trays[i].Center.x > reelCenter.x&&trays[i].Center.y > reelCenter.y)
{
if (trays[i].bSorted == false)
{
trays[i].iDir = 2;
trays[i].bSorted = true;
sortedTrays.push_back(trays[i]);
}
}
}
for (int i = 0; i < trays.size(); i++)
{
//右上角
if (trays[i].Center.x > reelCenter.x&&trays[i].Center.y < reelCenter.y)
{
if (trays[i].bSorted == false)
{
trays[i].iDir = 3;
trays[i].bSorted = true;
sortedTrays.push_back(trays[i]);
}
}
}
//计数
std::vector<int> trayNum(4);
const char icvCodeDeltas[3][3][2] = { { { 0, -1 },{ 1, -1 },{ 1, 0 } },{ { 1, 1 },{ 0, 1 },{ -1, 1 } },{ { -1, 0 },{ -1, -1 },{ 0, -1 } } };
//分料盘计数
for (int i = 0; i < sortedTrays.size(); i++)
{
cv::Mat srcPrev;
cv::bitwise_not(sortedTrays[i].Tray, srcPrev);
//二值化可以分别放在两个算法里
cv::Mat sinParts;
cv::threshold(srcPrev, sinParts, (255 - sortedTrays[i].dBackThresh), 255, cv::THRESH_BINARY);
//判断元件尺寸
int sinPartSize;
bool useTrackMethod = checkSize(srcPrev, sinParts, sinPartSize);
//判断大小
cv::Mat m1, m2, m3;
int nccomps = cv::connectedComponentsWithStats(sinParts, m1, m2, m3);
//判断适用哪种算法
if (!useTrackMethod)
{
const int filterSize = 12;
//去掉料盘深色部分干扰
const int winSize = sinPartSize > 15 ? 5 : 3;//对于部分器件过小的窗口会漏料
cv::Mat srcPrevEx;
cv::morphologyEx(srcPrev, srcPrevEx, cv::MORPH_TOPHAT, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(winSize, winSize)));
//二值化元件区域,用OTSU还是其他?
cv::Mat sinPartMask;
cv::threshold(srcPrevEx, sinPartMask, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
//连在一起
cv::morphologyEx(sinPartMask, srcPrevEx, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(5, 5)));
//去除孔洞
cv::morphologyEx(srcPrevEx, srcPrevEx, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(21, 21)));
//去除深色部分备份
cv::Mat removeDark = srcPrevEx.clone();
//最大外包
cv::morphologyEx(srcPrevEx, srcPrevEx, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(45, 45)));
//定位料盘中心
cv::findContours(srcPrevEx, contoursFilter, cv::RETR_TREE, cv::CHAIN_APPROX_NONE);
image = cv::Scalar(0);
for (int i = 0; i < contoursFilter.size(); i++)
{
cv::drawContours(image, contoursFilter, i, cv::Scalar(255), -1);
}
image -= srcPrevEx;
//获取最大轮廓
cv::findContours(image, contoursFilter, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
if (contoursFilter.size() <= 0)
{
continue;
}
std::vector<cv::Point> contourMax = contoursFilter[0];
for (int i = 1; i < contoursFilter.size(); i++)
{
if (cv::contourArea(contoursFilter[i]) > cv::contourArea(contourMax))
{
contourMax = contoursFilter[i];
}
}
cv::Moments mu = cv::moments(contourMax);
cv::Point2f reelCenter(float(mu.m10 / mu.m00), float(mu.m01 / mu.m00));
//画中心
//计算最大外接圆半径
float tFRadius = 0;
cv::minEnclosingCircle(contourMax, cv::Point2f(), tFRadius);
reelCenter.x = reelCenter.x > 0 && reelCenter.x < X ? reelCenter.x : 0;
reelCenter.y = reelCenter.y > 0 && reelCenter.y < Y ? reelCenter.y : 0;
cv::drawMarker(cc, reelCenter, cv::Scalar(0, 0, 238, 255), 1, 35, 2);
//去掉中心1/3区域
cv::circle(sinPartMask, reelCenter, cvRound(tFRadius / 2), cv::Scalar(0), -1);
//掩膜区域,用于区分处理区域
uchar *upMask = sinPartMask.data;
//最小料不进行粘连判断
cv::Mat mulParts(Y, X, CV_8UC1, cv::Scalar(0));
//
std::vector<uchar> colors(nccomps + 1, 0);
if (sinPartSize >= filterSize)
{
upMask = mulParts.data;
//根据元件大小确定是否进行粘连处理
for (int i = 1; i < nccomps; i++) {
colors[i] = 0;
if (((int *)m2.data)[(cv::CC_STAT_AREA) + (i)*m2.cols] >= 1.6*sinPartSize)//经验值
{
colors[i] = 255;
}
}
//认为是粘连
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++)
{
int label = ((int *)m1.data)[(x)+(y)*m1.cols];
CV_Assert(0 <= label && label <= nccomps);
(mulParts.data)[(x)+(y)*X] = colors[label];
}
}
});
sinParts &= removeDark;
mulParts &= removeDark;
sinParts -= mulParts;
cv::circle(sinParts, reelCenter, cvRound(tFRadius / 2), cv::Scalar(0), -1);
cv::circle(mulParts, reelCenter, cvRound(tFRadius / 2), cv::Scalar(0), -1);
}
//标签图像
unsigned char *pLabelImg = (unsigned char *)malloc(Y*X * sizeof(unsigned char));
memset(pLabelImg, 0, X*Y * sizeof(unsigned char));
cv::Mat lbImage(Y, X, CV_8UC1, pLabelImg);
//区分不同大小器件用不同的图处理
#define upSrc(x, y) (srcPrev.data)[(x) + (y)*X]
//连通域非极大值处理
for (int y = 1; y < Y - 1; y++)
{
for (int x = 1; x < X - 1; x++)
{
//属于连通域内,并且尚未被标记
if (upMask[(x)+(y)*X] != 0 && pLabelImg[(x)+(y)*X] != 255)
{
//生长种子点
auto pixval = upSrc(x, y);
if (pixval >= upSrc((x - 1), (y - 1)) && pixval >= upSrc((x), (y - 1)) && pixval >= upSrc((x + 1), (y - 1))\
&& pixval >= upSrc((x + 1), (y)) && pixval >= upSrc((x + 1), (y + 1)) && pixval >= upSrc((x), (y + 1))\
&& pixval >= upSrc((x - 1), (y + 1)) && pixval >= upSrc((x - 1), (y)))
{
//标记已处理
pLabelImg[(x)+(y)*X] = 255;
unsigned char direction = 0;
unsigned int xx = x;
unsigned int yy = y;
bool growEnd = false;
do
{
for (unsigned int n = 0; n < 3; n++)
{
bool found = false;
for (unsigned char i = 0; i < 3; i++)
{
int nx = xx + icvCodeDeltas[direction][i][0];
int ny = yy + icvCodeDeltas[direction][i][1];
//越界处理
if (nx < 2 || ny < 2 || nx>srcPrev.cols - 2 || ny>srcPrev.rows - 2)
continue;
//考虑多加个条件限制峰值
auto val = upSrc((nx), (ny));
if (val >= pixval&&pLabelImg[(nx)+(ny)*X] != 255)
{
found = true;
xx = nx;
yy = ny;
//next
direction = icvCodeDeltas[direction][i][2];
//标记已处理
pLabelImg[(xx)+(yy)*X] = 255;
break;
}
}
if (!found)
{
direction = (direction + 1) % 4;
}
if (growEnd = (direction == 3))
break;
}
} while (!growEnd);
}
}
}
}
//合并
lbImage += sinPartSize >= filterSize ? sinParts : mulParts;
//粗略计数
cv::Mat labels, stats, centroids;
int numObj = cv::connectedComponentsWithStats(lbImage, labels, stats, centroids);
//清空
memset(pLabelImg, 0, X*Y * sizeof(unsigned char));
//画图
#define dpCent(x,y) ((double *)centroids.data)[(x)+(y)*2]
for (int j = 1; j < numObj; j++)
{
cv::Point ms(cvRound(dpCent(0, j)), cvRound(dpCent(1, j)));
pLabelImg[(ms.x) + (ms.y)*X] = 255;
}
//计数
std::vector<cv::Point> vLocations;
cv::findNonZero(lbImage, vLocations);
for (int c = 0; c < vLocations.size(); c++)
{
cc.at<cv::Vec4b>(vLocations[c]) = cv::Vec4b(0, 0, 200, 255);
cv::circle(cc, vLocations[c], 1, cv::Scalar(0, 255, 0, 255), 1);
}
//cv::putText(cc, std::to_string(sortedTrays[i].iDir), cv::Point(cvRound(reelCenter.x), cvRound(reelCenter.y) - 50), 0, 1.0, cv::Scalar(0, 140, 255, 255), 2);
numObj = (int)vLocations.size();
std::string text = std::to_string(i + 1) + ": Reel Number = ";
text += std::to_string(numObj);
text += " ; PartSize = " + std::to_string(sinPartSize);
cv::putText(cc, text, cv::Point(35, 35 + i * 35), 0, 1.0, cv::Scalar(0, 140, 255, 255), 2);
//
trayNum[sortedTrays[i].iDir] = numObj;
//释放资源
free((void *)pLabelImg);
}
else
{
//采用追踪算法
nccomps = cv::connectedComponentsWithStats(sinParts, m1, m2, m3);
//连在一起
cv::Mat srcPrevEx0;
cv::morphologyEx(sinParts, srcPrevEx0, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(45, 45)));
//定位料盘中心
cv::findContours(srcPrevEx0, contoursFilter, cv::RETR_TREE, cv::CHAIN_APPROX_NONE);
image = cv::Scalar(0);
for (int i = 0; i < contoursFilter.size(); i++)
{
cv::drawContours(image, contoursFilter, i, cv::Scalar(255), -1);
}
image -= srcPrevEx0;
//获取最大轮廓
cv::findContours(image, contoursFilter, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
if (contoursFilter.size() <= 0)
continue;
std::vector<cv::Point> contourMax = contoursFilter[0];
for (int i = 1; i < contoursFilter.size(); i++)
{
if (cv::contourArea(contoursFilter[i]) > cv::contourArea(contourMax))
{
contourMax = contoursFilter[i];
}
}
//计算最大外接圆半径
float tFRadius = 0;
cv::minEnclosingCircle(contourMax, cv::Point2f(), tFRadius);
cv::Moments mu = cv::moments(contourMax);
cv::Point2f reelCenter(float(mu.m10 / mu.m00), float(mu.m01 / mu.m00));
//画中心
reelCenter.x = reelCenter.x > 0 && reelCenter.x < X ? reelCenter.x : 0;
reelCenter.y = reelCenter.y > 0 && reelCenter.y < Y ? reelCenter.y : 0;
cv::drawMarker(cc, reelCenter, cv::Scalar(0, 0, 238, 255), 1, 35, 2);
//包含未粘连器件
image = cv::Scalar(0);
std::vector<uchar> colors(nccomps + 1, 0);
for (int i = 1; i < nccomps; i++) {
colors[i] = 255;
if ((((int *)m2.data)[(cv::CC_STAT_AREA) + (i)*m2.cols] >= 1.5*sinPartSize) || (((int *)m2.data)[(cv::CC_STAT_AREA) + (i)*m2.cols] < 0.4*sinPartSize))//经验值
{
colors[i] = 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++)
{
int label = ((int *)m1.data)[(x)+(y)*m1.cols];
CV_Assert(0 <= label && label <= nccomps);
(image.data)[(x)+(y)*X] = colors[label];
}
}
});
//去掉中心1/3区域
cv::circle(image, reelCenter, cvRound(tFRadius / 3), cv::Scalar(0), -1);
//追踪直至没有单个元件存在
bool bExistSingle = true;
//用于计数
cv::Mat lb4Count(Y, X, CV_8UC1, cv::Scalar(0));
//标签图
unsigned char *ucpTrackLabel = new unsigned char[Y*X]();
cv::Mat trackMat(Y, X, CV_8UC1, ucpTrackLabel);
do
{
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularPartsE 点料阶段被跳过执行...");
break;
}
//不随机挑选起点(考虑换成面积最小的那个)
std::vector<cv::Point> contourMin;
cv::findContours(image, contoursFilter, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
//终止追踪
if (contoursFilter.size() <= 0) break;
//大于等于1个随机挑选
if (contoursFilter.size() > 1)
{
//随机数生成
srand((unsigned)time(NULL));
contourMin = contoursFilter[rand() % (contoursFilter.size() - 1)];
for (int fc = 0; fc < contoursFilter.size(); fc++)
{
if (cv::contourArea(contoursFilter[fc]) > 0.4*sinPartSize)
{
if (cv::contourArea(contoursFilter[fc]) < cv::contourArea(contourMin))
{
contourMin = contoursFilter[fc];
}
}
}
}
else if (contoursFilter.size() == 1)
{
contourMin = contoursFilter[0];
}
//去掉起始位置
std::vector<std::vector<cv::Point>> vTempRect;
vTempRect.push_back(contourMin);
cv::drawContours(image, vTempRect, 0, cv::Scalar(0), -1);
//最小外包矩形
cv::RotatedRect rect = cv::minAreaRect(contourMin);
cv::Point2f points[4];
rect.points(points);
//画图
//for (int j = 0; j < 4; j++)
//{
// cv::line(cc, points[j], points[(j + 1) % 4], cv::Scalar(0, 165, 255, 255), 1);
//}
//追踪起点
cv::Point2f startCenter((points[0].x + points[1].x + points[2].x + points[3].x) / 4.f, (points[0].y + points[1].y + points[2].y + points[3].y) / 4.f);
//打标签
cv::Mat labels;
nccomps = cv::connectedComponents(image, labels);
//去掉已处理的分离器件
std::vector<uchar> labeled(nccomps + 1, 0);
//标记为已追踪过
std::vector<cv::Point> vT = { cv::Point(points[0]),cv::Point(points[1]) ,cv::Point(points[2]) ,cv::Point(points[3]) };
cv::fillConvexPoly(trackMat, vT, cv::Scalar(255));
//起点加入计数
cv::circle(lb4Count, cv::Point(startCenter), 0, cv::Scalar(255), 1);
cv::circle(cc, cv::Point(startCenter), 2, cv::Scalar(0, 255, 0, 255), 1);
///<追踪元件算法
struct Track {
int iLimit, iPartSize;
double dMatchDeg;
cv::Point Pos;
std::vector<cv::Point2f> Rect;
Track() {};
Track(int iLimit, int iPartSize, double dMatchDeg, cv::Point Pos, std::vector<cv::Point2f> Rect) :iLimit(iLimit), iPartSize(iPartSize), dMatchDeg(dMatchDeg), Pos(Pos), Rect(Rect) {};
bool operator >(const Track &te)const
{
return dMatchDeg > te.dMatchDeg;
}
};
//扫描步长
const double dMinorStep = 0.1;
//追踪长宽
const double trackLength = std::max(rect.size.width / 2, rect.size.height / 2), trackWidth = std::min(rect.size.width / 4, rect.size.height / 4);
//起始扫描角度
const double startAngle = atan2((double)startCenter.y - reelCenter.y, (double)startCenter.x - reelCenter.x) * 180 / PI;
//起始扫描半径
const double startRadius = cv::norm(startCenter - reelCenter);
//偏移角度(元件尺寸)
const double dOffset = (2 * asin(2 * trackLength / (2 * startRadius))) * 180 / PI;
//偏移角度(元件间距)
const double dScanRange = 15;
//追踪元件间距(弦长,可以尽量避免因个别器件偏离导致的追踪中断)
double dChordL = .0;
for (double t = startAngle + dOffset / 1.5; t < startAngle + dOffset / 1.5 + dScanRange; t += dMinorStep)
{
float x = float(reelCenter.x + startRadius*cos(t*c));
float y = float(reelCenter.y + startRadius*sin(t*c));
//初次确定元件间距
const double angle = atan2((double)reelCenter.y - y, (double)reelCenter.x - x);
cv::Point p1 = cv::Point(cvRound(x + trackWidth * cos(angle)),
cvRound(y + trackWidth * sin(angle)));
cv::Point p2 = cv::Point(cvRound(x + trackWidth * cos(angle + CV_PI)),
cvRound(y + trackWidth * sin(angle + CV_PI)));
cv::LineIterator it(sinParts, p1, p2, 4);
for (int n = 0; n < it.count; n++, ++it)
{
if ((sinParts.data)[(it.pos().x) + (it.pos().y)*X] == 255)
{
//计算元件间距(弦长)
dChordL = 2.0 * startRadius*sin(((2.0 * asin((cv::norm(startCenter - cv::Point2f(x, y))) / (2.0 * startRadius))) * 180.0 / PI - dOffset / 2.0)*PI / 180.0 / 2.0);
break;
}
}
if (dChordL > 0)
break;
}
//并行处理
//#pragma omp parallel sections
{
//(顺时针)
//#pragma omp section
{
//追踪中心
cv::Point2f trackCenter = cv::Point2f(startCenter.x, startCenter.y);
//追踪角度、半径
double trackAngle = startAngle, trackRadius = startRadius;
//元件本身角度
double trackOffset = dOffset;
//元件间间距
double partDist = (2 * asin(dChordL / (2 * trackRadius))) * 180 / PI;
//外包矩形顶点
cv::Point2f pts[4];
//结束位置
Track trackEndPos;
//开始追踪
bool trackEnd = true;
do
{
bool found = true;
std::vector<Track> vParts;
for (double t = trackAngle + (trackOffset / 2.0 + partDist); t < trackAngle + (trackOffset / 2.0 + partDist) + trackOffset; t += dMinorStep)
{
trackCenter.x = reelCenter.x + (float)trackRadius*(float)cos(t*c);
trackCenter.y = reelCenter.y + (float)trackRadius*(float)sin(t*c);
float b = (float)cos(t*c)*0.5f;
float a = (float)sin(t*c)*0.5f;
pts[0].x = float(trackCenter.x - a*trackLength * 2 - b*trackWidth * 4);
pts[0].y = float(trackCenter.y + b*trackLength * 2 - a*trackWidth * 4);
pts[1].x = float(trackCenter.x + a*trackLength * 2 - b*trackWidth * 4);
pts[1].y = float(trackCenter.y - b*trackLength * 2 - a*trackWidth * 4);
pts[2].x = float(2 * trackCenter.x - pts[0].x);
pts[2].y = float(2 * trackCenter.y - pts[0].y);
pts[3].x = float(2 * trackCenter.x - pts[1].x);
pts[3].y = float(2 * trackCenter.y - pts[1].y);
std::vector<cv::Point> vPoints;
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
//获取内部坐标
calcRotateRect(vRect, vPoints);
//计算灰度值
double dMatch = 0;
for (int v = 0; v < vPoints.size(); v++)
{
if (vPoints[v].x >= 0 && vPoints[v].x <= X&&vPoints[v].y >= 0 && vPoints[v].y <= Y)
{
dMatch += (srcPrev.data)[(vPoints[v].x) + (vPoints[v].y)*X];
}
}
dMatch /= (double)vPoints.size();
//仅扫描一个元件的角度
vParts.push_back(Track(0, 0, dMatch, cv::Point(cvRound(trackCenter.x), cvRound(trackCenter.y)), vRect));
//cv::circle(cc, cv::Point(cvRound(trackCenter.x), cvRound(trackCenter.y)), 0, cv::Scalar(0, 255, 255, 255), 1);
}
if (vParts.size() == 0) continue;
//
trackEndPos = vParts[vParts.size() / 2];
//灰度极值认为是元件
std::sort(vParts.begin(), vParts.end(), std::greater<Track>());
//更新位置
trackCenter = cv::Point(vParts[0].Pos.x, vParts[0].Pos.y);
//更新扫描角度
trackAngle = atan2((double)trackCenter.y - reelCenter.y, (double)trackCenter.x - reelCenter.x) * 180 / PI;
//纵向扫描
vParts.clear();
std::vector<cv::Point> trackLine;
drawLine(cc, reelCenter, trackCenter, cv::Scalar(0, 255, 255, 255), 1, trackLength, trackWidth * 2, trackLine);
//更改纵向扫描方向,分两个方向?
cv::LineIterator it(sinParts, trackLine[0], trackLine[1], 4);
for (int n = 0; n < it.count; n++, ++it)
{
float b = (float)cos(trackAngle*PI / 180.)*0.5f;
float a = (float)sin(trackAngle*PI / 180.)*0.5f;
pts[0].x = (float)(it.pos().x - a*trackLength * 2 - b*trackWidth * 4);
pts[0].y = (float)(it.pos().y + b*trackLength * 2 - a*trackWidth * 4);
pts[1].x = (float)(it.pos().x + a*trackLength * 2 - b*trackWidth * 4);
pts[1].y = (float)(it.pos().y - b*trackLength * 2 - a*trackWidth * 4);
pts[2].x = (float)(2 * it.pos().x - pts[0].x);
pts[2].y = (float)(2 * it.pos().y - pts[0].y);
pts[3].x = (float)(2 * it.pos().x - pts[1].x);
pts[3].y = (float)(2 * it.pos().y - pts[1].y);
std::vector<cv::Point> vPoints;
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
//获取内部坐标
calcRotateRect(vRect, vPoints);
//计算灰度值
int iLimit = 0, iPartSize = 0;
double dMatch = 0;
for (int v = 0; v < vPoints.size(); v++)
{
if (vPoints[v].x >= 0 && vPoints[v].x <= X&&vPoints[v].y >= 0 && vPoints[v].y <= Y)
{
iLimit += ucpTrackLabel[(vPoints[v].x) + (vPoints[v].y)*X];
dMatch += (srcPrev.data)[(vPoints[v].x) + (vPoints[v].y)*X];
if ((sinParts.data)[(vPoints[v].x) + (vPoints[v].y)*X] == 255)
iPartSize++;
}
}
vParts.push_back(Track(iLimit, iPartSize, dMatch, it.pos(), vRect));
//cv::circle(cc, it.pos(), 0, cv::Scalar(255, 0, 0, 255), 1);
}
if (vParts.size() == 0) continue;
//方案二每个点以当前半径画圆,看下个点偏离圆多少
//灰度极值认为是元件(最多问题出现在这里,加个条件判断矩形内是否存在已标记像素)
std::sort(vParts.begin(), vParts.end(), std::greater<Track>());
//更新当前元件位置(必须不与已有元件重合)
Track mac = vParts[0];
if (mac.iLimit != 0)
{
for (int cc = 1; cc < vParts.size(); cc++)
{
if (vParts[cc].iLimit < mac.iLimit)
mac = vParts[cc];
if (mac.iLimit == 0)
break;
}
}
trackCenter = mac.Pos;
//更新扫描半径
trackRadius = cv::norm(trackCenter - reelCenter);
//更新扫描角度
trackAngle = atan2((double)trackCenter.y - reelCenter.y, (double)trackCenter.x - reelCenter.x) * 180 / PI;
//更新偏移量(元件大小)
trackOffset = (2 * asin(2 * trackLength / (2 * trackRadius))) * 180 / PI;
//更新元件间角度
partDist = (2 * asin(dChordL / (2 * trackRadius))) * 180 / PI;
//判断是否结束
if ((mac.iPartSize < sinPartSize / 4) || (trackMat.at<uchar>((cvRound(trackCenter.y)), (cvRound(trackCenter.x))) == 255) || (mac.iLimit / 255) > (rect.size.area() / 4) || (sinParts.at<uchar>((cvRound(trackCenter.y)), (cvRound(trackCenter.x))) == 0))
{
found = false;
//for (int j = 0; j < 4; j++)
//{
// cv::line(cc, trackEndPos.Rect[j], trackEndPos.Rect[(j + 1) % 4], cv::Scalar(0, 0, 255, 255), 1);
//}
//cv::circle(cc, trackCenter, 1, cv::Scalar(0, 255, 0, 255), 1);
}
else
{
//画出最终位置
std::vector<cv::Point> ptPoly;
for (int j = 0; j < 4; j++)
{
ptPoly.push_back(cv::Point(cvRound(mac.Rect[j].x), cvRound(mac.Rect[j].y)));
//cv::line(cc, mac.Rect[j], mac.Rect[(j + 1) % 4], cv::Scalar(0, 255, 0, 255), 1);
}
cv::circle(cc, trackCenter, 2, cv::Scalar(0, 255, 0, 255), 1);
cv::circle(lb4Count, trackCenter, 0, cv::Scalar(255), 1);
//标记Label
cv::fillConvexPoly(trackMat, ptPoly, cv::Scalar(255));
//获得已处理标签
std::vector<cv::Point> vTemp;
calcRotateRect(mac.Rect, vTemp);
for (int p = 0; p < vTemp.size(); p++)
{
if (vTemp[p].x >= 0 && vTemp[p].x <= X&&vTemp[p].y >= 0 && vTemp[p].y <= Y)
{
int label = labels.at<int>(vTemp[p]);
if (label != 0)
{
labeled[label] = 255;
break;
}
}
}
}
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularPartsE 追踪阶段被跳过执行...");
found = false;
}
trackEnd = (!found);
} while (!trackEnd);
}
//#pragma omp section
//逆时针追踪
{
//追踪起点
cv::Point2f trackCenter(startCenter.x, startCenter.y);
//起始扫描角度、半径
double trackAngle = startAngle, trackRadius = startRadius;
//元件本身角度
double trackOffset = dOffset;
//元件间间距
double partDist = (2 * asin(dChordL / (2 * trackRadius))) * 180 / PI;
//当扫描一圈后修正中心位置(待测试)
cv::Point2f pts[4];
//结束位置
Track trackEndPos;
//开始追踪
bool trackEnd = true;
//
do
{
bool found = true;
std::vector<Track> vParts;
for (double t = trackAngle - (partDist + trackOffset / 2.0); t > trackAngle - (partDist + trackOffset / 2.0) - trackOffset; t -= dMinorStep)
{
trackCenter.x = float(reelCenter.x + trackRadius*cos(t*c));
trackCenter.y = float(reelCenter.y + trackRadius*sin(t*c));
float b = (float)cos(t*c)*0.5f;
float a = (float)sin(t*c)*0.5f;
pts[0].x = (float)(trackCenter.x - a*trackLength * 2 - b*trackWidth * 4);
pts[0].y = (float)(trackCenter.y + b*trackLength * 2 - a*trackWidth * 4);
pts[1].x = (float)(trackCenter.x + a*trackLength * 2 - b*trackWidth * 4);
pts[1].y = (float)(trackCenter.y - b*trackLength * 2 - a*trackWidth * 4);
pts[2].x = (float)(2 * trackCenter.x - pts[0].x);
pts[2].y = (float)(2 * trackCenter.y - pts[0].y);
pts[3].x = (float)(2 * trackCenter.x - pts[1].x);
pts[3].y = (float)(2 * trackCenter.y - pts[1].y);
std::vector<cv::Point> vPoints;
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
//获取内部坐标
calcRotateRect(vRect, vPoints);
//计算灰度值
double dMatch = 0;
for (int v = 0; v < vPoints.size(); v++)
{
if (vPoints[v].x >= 0 && vPoints[v].x <= X&&vPoints[v].y >= 0 && vPoints[v].y <= Y)
{
dMatch += (srcPrev.data)[(vPoints[v].x) + (vPoints[v].y)*X];
}
}
dMatch /= (double)vPoints.size();
//仅扫描一个元件的角度
vParts.push_back(Track(0, 0, dMatch, cv::Point(cvRound(trackCenter.x), cvRound(trackCenter.y)), vRect));
//cv::circle(cc, trackCenter, 0, cv::Scalar(0, 255, 255, 255), 1);
}
if (vParts.size() == 0) continue;
//
trackEndPos = vParts[vParts.size() / 2];
//灰度极值认为是元件
std::sort(vParts.begin(), vParts.end(), std::greater<Track>());
//更新位置
trackCenter = cv::Point(vParts[0].Pos.x, vParts[0].Pos.y);
//更新扫描角度
trackAngle = atan2((double)trackCenter.y - reelCenter.y, (double)trackCenter.x - reelCenter.x) * 180 / PI;
//纵向扫描
vParts.clear();
std::vector<cv::Point> trackLine;
drawLine(cc, reelCenter, trackCenter, cv::Scalar(0, 255, 255, 255), 1, trackLength, trackWidth * 2, trackLine);
//更改纵向扫描方向,分两个方向
cv::LineIterator it(sinParts, trackLine[0], trackLine[1], 4);
for (int n = 0; n < it.count; n++, ++it)
{
float b = (float)cos(trackAngle*PI / 180.)*0.5f;
float a = (float)sin(trackAngle*PI / 180.)*0.5f;
pts[0].x = (float)(it.pos().x - a*trackLength * 2 - b*trackWidth * 4);
pts[0].y = (float)(it.pos().y + b*trackLength * 2 - a*trackWidth * 4);
pts[1].x = (float)(it.pos().x + a*trackLength * 2 - b*trackWidth * 4);
pts[1].y = (float)(it.pos().y - b*trackLength * 2 - a*trackWidth * 4);
pts[2].x = (float)(2 * it.pos().x - pts[0].x);
pts[2].y = (float)(2 * it.pos().y - pts[0].y);
pts[3].x = (float)(2 * it.pos().x - pts[1].x);
pts[3].y = (float)(2 * it.pos().y - pts[1].y);
std::vector<cv::Point> vPoints;
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
//获取内部坐标
calcRotateRect(vRect, vPoints);
//计算灰度值
int iLimit = 0, iPartSize = 0;
double dMatch = 0;
for (int v = 0; v < vPoints.size(); v++)
{
if (vPoints[v].x >= 0 && vPoints[v].x <= X&&vPoints[v].y >= 0 && vPoints[v].y <= Y)
{
iLimit += ucpTrackLabel[(vPoints[v].x) + (vPoints[v].y)*X];
dMatch += (srcPrev.data)[(vPoints[v].x) + (vPoints[v].y)*X];
if ((sinParts.data)[(vPoints[v].x) + (vPoints[v].y)*X] == 255)
iPartSize++;
}
}
vParts.push_back(Track(iLimit, iPartSize, dMatch, it.pos(), vRect));
//cv::circle(cc, it.pos(), 0, cv::Scalar(255, 0, 0, 255), 1);
}
if (vParts.size() == 0) continue;
//灰度极值认为是元件
std::sort(vParts.begin(), vParts.end(), std::greater<Track>());
//更新当前元件位置
Track mac = vParts[0];
if (mac.iLimit != 0)
{
for (int cc = 1; cc < vParts.size(); cc++)
{
if (vParts[cc].iLimit < mac.iLimit)
mac = vParts[cc];
if (mac.iLimit == 0)
break;
}
}
trackCenter = mac.Pos;
//更新扫描半径
trackRadius = cv::norm(trackCenter - reelCenter);
//更新扫描角度
trackAngle = atan2((double)trackCenter.y - reelCenter.y, (double)trackCenter.x - reelCenter.x) * 180 / PI;
//更新偏移量
trackOffset = (2 * asin(2 * trackLength / (2 * trackRadius))) * 180 / PI;
//更新追踪角度
partDist = (2 * asin(dChordL / (2 * trackRadius))) * 180 / PI;
//绕完一周后更新料盘中心试试?
//判断是否结束
if (mac.iPartSize < sinPartSize / 4 || (trackMat.at<uchar>((cvRound(trackCenter.y)), (cvRound(trackCenter.x))) == 255) || (mac.iLimit / 255) >(rect.size.area() / 4) || (sinParts.at<uchar>((cvRound(trackCenter.y)), (cvRound(trackCenter.x))) == 0))
{
found = false;
//for (int j = 0; j < 4; j++)
//{
// cv::line(cc, trackEndPos.Rect[j], trackEndPos.Rect[(j + 1) % 4], cv::Scalar(0, 0, 255, 255), 1);
//}
//cv::circle(cc, trackCenter, 1, cv::Scalar(0, 255, 0, 255), 1);
}
else
{
//画出最终位置
std::vector<cv::Point> ptPoly;
for (int j = 0; j < 4; j++)
{
ptPoly.push_back(cv::Point(cvRound(mac.Rect[j].x), cvRound(mac.Rect[j].y)));
//cv::line(cc, mac.Rect[j], mac.Rect[(j + 1) % 4], cv::Scalar(0, 255, 0, 255), 1);
}
//
cv::circle(cc, trackCenter, 2, cv::Scalar(0, 255, 0, 255), 1);
cv::circle(lb4Count, trackCenter, 0, cv::Scalar(255), 1);
//标记Label
cv::fillConvexPoly(trackMat, ptPoly, cv::Scalar(255));
//获得已处理标签
std::vector<cv::Point> vTemp;
calcRotateRect(mac.Rect, vTemp);
for (int p = 0; p < vTemp.size(); p++)
{
if (vTemp[p].x >= 0 && vTemp[p].x <= X&&vTemp[p].y >= 0 && vTemp[p].y <= Y)
{
int label = labels.at<int>(vTemp[p]);
if (label != 0)
{
labeled[label] = 255;
break;
}
}
}
}
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularPartsE 追踪阶段被跳过执行...");
found = false;
}
trackEnd = (!found);
} while (!trackEnd);
}
}
//去掉已标记处理的
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++)
{
int label = ((int *)labels.data)[(x)+(y)*labels.cols];
CV_Assert(0 <= label && label <= nccomps);
if (labeled[label])
{
((int *)(labels.data))[(x)+(y)*X] = 0;
}
}
}
});
image = labels > 0;
//判断是否存在未追踪单个料
bExistSingle = (cv::countNonZero(image) == 0);
} while (!bExistSingle);
//标记料盘编号
//cv::putText(cc, std::to_string(sortedTrays[i].iDir), cv::Point(cvRound(reelCenter.x), cvRound(reelCenter.y) - 50), 0, 1.0, cv::Scalar(0, 140, 255, 255), 2);
//计数
int numObj = cv::countNonZero(lb4Count);
std::string text = std::to_string(i + 1) + ": Reel Number = ";
text += std::to_string(numObj);
text += " ; PartSize = " + std::to_string(sinPartSize);
cv::putText(cc, text, cv::Point(35, 35 + i * 35), 0, 1.0, cv::Scalar(0, 140, 255, 255), 2);
//输出
trayNum[sortedTrays[i].iDir] = numObj;
//释放资源
delete[] ucpTrackLabel;
ucpTrackLabel = NULL;
}
}
//输出结果
const int SizeConst = 4;
//<输出计数结果标记图像
{
for (int i = 0; i < SizeConst; i++) {
ipReelNum[i] = trayNum[i];
}
tpDstImg->iWidth = cc.cols; tpDstImg->iHeight = cc.rows; tpDstImg->iDepth = cc.depth(); tpDstImg->iChannels = cc.channels();
//内存尺寸
int _Size = tpDstImg->iWidth*tpDstImg->iHeight*tpDstImg->iChannels * sizeof(uint8_t);
//分配内存
tpDstImg->vpImage = (uint8_t *)malloc(_Size);
if (NULL == tpDstImg->vpImage)
return FUNC_NOT_ENOUGH_MEM;
memset(tpDstImg->vpImage, 0, _Size);
//拷贝数据
memcpy(tpDstImg->vpImage, cc.data, _Size);
}
return FUNC_OK;
}
int eyemCountObjectIrregularParts(EyemImage tpImage, EyemRect tpRoi, const char *fileName, const char * ccSubType, int *ipReelNum, EyemImage *tpDstImg)
{
cv::Mat src = cv::Mat(tpImage.iHeight, tpImage.iWidth, MAKETYPE(tpImage.iDepth, tpImage.iChannels), tpImage.vpImage).clone();
if (src.empty()) {
return FUNC_IMAGE_NOT_EXIST;
}
//转单通道图像
if (src.channels() != 1)
cv::cvtColor(src, src, cv::COLOR_BGR2GRAY);
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularPartsE 初始阶段被跳过执行...");
return FUNC_CANNOT_CALC;
}
//图像裁剪
src = src(cv::Rect(tpRoi.iXs, tpRoi.iYs, tpRoi.iWidth, tpRoi.iHeight)).clone();
//图像尺寸
int X = src.cols, Y = src.rows;
//去除局部亮斑与黑斑影响(默认亮斑尺寸不会大于15个像素)
cv::Mat srcTmp, srcTmp2;
cv::morphologyEx(src, srcTmp, cv::MORPH_ERODE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(15, 15)));
//去除黑斑影响
int m = cvRound(cv::mean(src)[0]);
srcTmp.forEach<uint16_t>([&](uint16_t& pixel, const int *pos)->void {
pixel = pixel == 0 ? m : pixel;
});
//图像增强
double min, max;
cv::minMaxLoc(srcTmp, &min, &max);
src.convertTo(src, CV_64FC1);
src -= min;
src /= (max - min);
src *= 65535;
src.convertTo(src, CV_16UC1);
//转8位灰度图
cv::Mat src8U;
src.convertTo(src8U, CV_8UC1, 1 / 255.);
//测试用
cv::Mat testmat = src8U.clone();
//用于显示
cv::Mat cc;
cv::cvtColor(src8U, cc, cv::COLOR_GRAY2BGRA);
//设定bin数目
const int histSize = 17;
//设定取值范围
float range[] = { 0,255 };
const float* histRange = { range };
//计算直方图
cv::Mat hist;
cv::calcHist(&src8U, 1, 0, cv::Mat(), hist, 1, &histSize, &histRange);
//计算背景像素
int maxIdx[2] = { 255,255 };
cv::minMaxIdx(hist, NULL, NULL, NULL, maxIdx);
//背景阈值
int backThresh = 15 * (maxIdx[0] - 2);
//去掉背景
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 ((src8U.data)[(x)+(y)*X] >= backThresh) {
(src8U.data)[(x)+(y)*X] = backThresh;
}
}
}
});
//增强到目标亮度方便显示
cc += cv::Scalar((162 - backThresh), (162 - backThresh), (162 - backThresh));
//去掉干扰
cv::Mat binary, srcPrev;
cv::bitwise_not(src8U, srcPrev);
if (strcmp(ccSubType, "IP_SMALL_PARTS") == 0)
{
//优化修改测试
cv::Mat srcMean;
cv::blur(srcPrev, srcMean, cv::Size(7, 7));
cv::Mat srcMinus;
srcMinus = srcPrev - srcMean;
//二值化
cv::threshold(srcMinus, binary, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
//去掉<=1面积的干扰
{
cv::Mat labels, stats, centroids;
int nccomps = cv::connectedComponentsWithStats(binary, labels, stats, centroids);
//过滤连通域面积<=1的
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] <= 1))
{
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::morphologyEx(binary, binary, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)));
//分连通域进行自适应二值化
{
cv::Mat labels, stats, centroids;
int nccomps = cv::connectedComponentsWithStats(binary, labels, stats, centroids);
struct NccompsThresh
{
int ID;
double T;
NccompsThresh(int ID, double T) :ID(ID), T(T) {}
};
std::vector<NccompsThresh> nts;
for (int n = 1; n < nccomps; n++) {
cv::Rect rec(stats.ptr<int>(n)[cv::CC_STAT_LEFT] - 1, stats.ptr<int>(n)[cv::CC_STAT_TOP] - 1, \
stats.ptr<int>(n)[cv::CC_STAT_WIDTH] + 2, stats.ptr<int>(n)[cv::CC_STAT_HEIGHT] + 2);
cv::Mat maskID = labels(rec) == n;
cv::Mat maskSrc = srcMinus(rec);
double min, max;
cv::minMaxLoc(maskSrc, &min, &max, NULL, NULL, maskID);
nts.push_back(NccompsThresh(n, max*0.4));
}
//二值化
cv::Mat loc(Y, X, CV_8UC1, cv::Scalar(0));
for (int y = 1; y < Y - 1; y++)
{
uint8_t *ptrRow = loc.ptr<uint8_t>(y);
for (int x = 1; x < X - 1; x++)
{
int label = labels.ptr<int>(y)[x];
CV_Assert(0 <= label && label <= nccomps);
if (label > 0) {
ptrRow[x] = srcMinus.ptr<uint8_t>(y)[x] > nts[label - 1].T ? 255 : 0;
}
}
}
//去掉太长的干扰
{
cv::Mat labels, stats, centroids;
int nccomps = cv::connectedComponentsWithStats(loc, labels, stats, centroids);
//过滤连通域面积<=1的
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] > 9) || (stats.ptr<int>(i)[cv::CC_STAT_HEIGHT] > 9))
{
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 = loc.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];
}
}
});
}
binary = loc;
}
cv::Mat srcPrevEx; cv::Mat mask;
cv::morphologyEx(srcPrev, srcPrevEx, cv::MORPH_TOPHAT, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)));
cv::threshold(srcPrevEx, mask, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
binary &= mask;
//定位料盘中心
cv::Mat srcPrevLoc;
cv::morphologyEx(binary, srcPrevLoc, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(13, 13)));
cv::Mat image(Y, X, CV_8UC1, cv::Scalar(0));
std::vector<std::vector<cv::Point>> contourAll;
findContours(srcPrevLoc, contourAll, cv::noArray(), cv::RETR_TREE, cv::CHAIN_APPROX_NONE);
for (int n = 0; n < contourAll.size(); n++) {
cv::drawContours(image, contourAll, n, cv::Scalar(255), -1);
}
//寻找最大轮廓
std::vector<cv::Point> contourMax; double contourMaxArea = 0; cv::Point2f center; float radius;
contourMax = contourAll[0]; contourMaxArea = cv::contourArea(contourMax);
for (int i = 1; i < contourAll.size(); i++)
{
double contourArea = cv::contourArea(contourAll[i]);
if (contourArea > contourMaxArea)
{
contourMax = contourAll[i];
contourMaxArea = contourArea;
}
}
//去掉外部干扰
cv::minEnclosingCircle(contourMax, center, radius);
cv::Mat temp(Y, X, CV_8UC1, cv::Scalar(0));
cv::circle(temp, center, cvRound(radius), cv::Scalar(255), -1);
binary &= temp;
image -= srcPrevLoc;
cv::morphologyEx(image, image, cv::MORPH_OPEN, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(11, 11)));
contourAll.resize(0);
findContours(image, contourAll, cv::noArray(), cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
if (contourAll.empty()) {
return FUNC_CANNOT_CALC;
}
//寻找最大轮廓
contourMax = contourAll[0]; contourMaxArea = cv::contourArea(contourMax);
for (int i = 1; i < contourAll.size(); i++)
{
double contourArea = cv::contourArea(contourAll[i]);
if (contourArea > contourMaxArea)
{
contourMax = contourAll[i];
contourMaxArea = contourArea;
}
}
cv::minEnclosingCircle(contourMax, center, radius);
//去除内部干扰
cv::circle(binary, center, cvRound(radius - 15), cv::Scalar(0), -1);
//待处理区域
uchar *upMask = binary.data;
//标签图像
unsigned char *pLabelImg = (unsigned char *)malloc(Y*X * sizeof(unsigned char));
memset(pLabelImg, 0, X*Y * sizeof(unsigned char));
cv::Mat lbImage(Y, X, CV_8UC1, pLabelImg);
//区分不同大小器件用不同的图处理
const char icvCodeDeltas[3][3][2] = { { { 0, -1 },{ 1, -1 },{ 1, 0 } },{ { 1, 1 },{ 0, 1 },{ -1, 1 } },{ { -1, 0 },{ -1, -1 },{ 0, -1 } } };
#define upSrc(x, y) (srcPrev.data)[(x) + (y)*X]
//连通域非极大值处理
for (int y = 1; y < Y - 1; y++)
{
for (int x = 1; x < X - 1; x++)
{
//属于连通域内,并且尚未被标记
if (upMask[(x)+(y)*X] != 0 && pLabelImg[(x)+(y)*X] != 255)
{
//生长种子点
auto pixval = upSrc(x, y);
if (pixval >= upSrc((x - 1), (y - 1)) && pixval >= upSrc((x), (y - 1)) && pixval >= upSrc((x + 1), (y - 1))\
&& pixval >= upSrc((x + 1), (y)) && pixval >= upSrc((x + 1), (y + 1)) && pixval >= upSrc((x), (y + 1))\
&& pixval >= upSrc((x - 1), (y + 1)) && pixval >= upSrc((x - 1), (y)))
{
//标记已处理
pLabelImg[(x)+(y)*X] = 255;
unsigned char direction = 0;
unsigned int xx = x;
unsigned int yy = y;
bool growEnd = false;
do
{
for (unsigned int n = 0; n < 3; n++)
{
bool found = false;
for (unsigned char i = 0; i < 3; i++)
{
int nx = xx + icvCodeDeltas[direction][i][0];
int ny = yy + icvCodeDeltas[direction][i][1];
//越界处理
if (nx < 2 || ny < 2 || nx>srcPrev.cols - 2 || ny>srcPrev.rows - 2)
continue;
//考虑多加个条件限制峰值
auto val = upSrc((nx), (ny));
if (val >= pixval&&pLabelImg[(nx)+(ny)*X] != 255)
{
found = true;
xx = nx;
yy = ny;
//next
direction = icvCodeDeltas[direction][i][2];
//标记已处理
pLabelImg[(xx)+(yy)*X] = 255;
break;
}
}
if (!found)
{
direction = (direction + 1) % 4;
}
if (growEnd = (direction == 3))
break;
}
} while (!growEnd);
}
}
}
}
//粗略计数
cv::Mat labels, stats, centroids;
int numObj = cv::connectedComponentsWithStats(lbImage, labels, stats, centroids);
//坐标图
binary = cv::Scalar(0);
//画图
double *dpCent = (double *)centroids.data; std::vector<cv::Point> forfilter;
for (int j = 1; j < numObj; j++)
{
cv::Point pt(cvRound(centroids.ptr<double_t>(j)[0]), cvRound(centroids.ptr<double_t>(j)[1]));
forfilter.push_back(pt);
binary.at<uchar>(pt) = 255;
}
//过滤
cv::Mat filtermap(Y, X, CV_8UC1, cv::Scalar(0));
for (int i = 0; i < forfilter.size(); i++)
{
cv::Rect rec = cv::Rect(forfilter[i].x - 25, forfilter[i].y - 25, 50, 50)&cv::Rect(0, 0, X, Y);
cv::Mat filter = testmat(rec);
cv::Mat mask = binary(rec);
if (!(testmat.ptr<uint8_t>(forfilter[i].y)[forfilter[i].x] > cv::mean(filter, mask)[0] + 45)) {
filtermap.at<uchar>(forfilter[i]) = 255;
cv::circle(cc, forfilter[i], 1, cv::Scalar(0, 255, 0, 255), 1);
}
}
binary = filtermap;
//释放资源
free((void *)pLabelImg);
}
else if (strcmp(ccSubType, "IP_LARGE_PARTS") == 0)
{
//二值化
cv::threshold(srcPrev, binary, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
cv::morphologyEx(binary, binary, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(75, 75)));
//计算直方图
int hist[256];
for (int y = 0; y < 256; y++) hist[y] = 0;
for (int y = 0; y < Y; y++)
{
uchar *uPtr = srcPrev.data + y * X;
for (int x = 0; x < srcPrev.cols; x++, uPtr++) {
if (binary.ptr<uint8_t>(y)[x] == 255) {
hist[*uPtr]++;
}
}
}
cv::threshold(srcPrev, binary, Otsu(hist), 255, cv::THRESH_BINARY);
//计算元件大小
cv::Mat m1, m2, m3;
int nccomps = cv::connectedComponentsWithStats(binary, m1, m2, m3);
std::vector<uchar> colors0(nccomps + 1, 0);
for (int i = 1; i < nccomps; i++) {
colors0[i] = 255;
if ((((int *)m2.data)[(cv::CC_STAT_AREA) + (i)*m2.cols] <= 2))//经验值
{
colors0[i] = 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++) {
int label = ((int *)m1.data)[(x)+(y)*m1.cols];
CV_Assert(0 <= label && label <= nccomps);
(binary.data)[(x)+(y)*X] = colors0[label];
}
}
});
nccomps = cv::connectedComponentsWithStats(binary, m1, m2, m3);
//
if (nccomps <= 1) return FUNC_CANNOT_CALC;
//统计元件面积
std::vector<int> vHist(nccomps);
for (int y = 0; y < Y; y++)
{
int *uPtr = (int *)m1.data + y * X;
for (int x = 0; x < X; x++, uPtr++) {
vHist[*uPtr]++;
}
}
//统计面积个数
std::map<int, int> cAreaMap;
for (const auto& v : vHist)
{
std::map<int, int>::iterator it = cAreaMap.find(v);
if (it != cAreaMap.end())
{
it->second++;
continue;
}
else { cAreaMap.insert(std::make_pair(v, 1)); };
}
struct tMap
{
int Key;
int Value;
tMap(int Key, int Value) :Key(Key), Value(Value) {}
bool operator >(const tMap &te)const
{
return Value > te.Value;
}
};
//获得单个元器件面积(准确性待测试,假定不粘连占大多数!)
std::vector<tMap> tVector;
std::map<int, int>::iterator it;
for (it = cAreaMap.begin(); it != cAreaMap.end(); it++)
{
tVector.push_back(tMap(it->first, it->second));
}
std::sort(tVector.begin(), tVector.end(), std::greater<tMap>());
if (tVector.size() < 2)
{
return false;
}
//单个元件面积
int sinPartSize = cvRound((tVector[0].Key + tVector[1].Key) / 2.);
//采用追踪算法
nccomps = cv::connectedComponentsWithStats(binary, m1, m2, m3);
//连在一起
cv::Mat srcPrevEx0;
cv::morphologyEx(binary, srcPrevEx0, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(45, 45)));
//定位料盘中心
std::vector<std::vector<cv::Point>> contoursFilter;
cv::findContours(srcPrevEx0, contoursFilter, cv::RETR_TREE, cv::CHAIN_APPROX_NONE);
cv::Mat image = cv::Mat::zeros(src8U.size(), CV_8UC1);
//
for (int i = 0; i < contoursFilter.size(); i++)
{
cv::drawContours(image, contoursFilter, i, cv::Scalar(255), -1);
}
image -= srcPrevEx0;
//2021/08/26增加测试用
cv::morphologyEx(image, image, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(45, 45)));
//获取最大轮廓
cv::findContours(image, contoursFilter, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
if (contoursFilter.size() <= 0)
return FUNC_CANNOT_CALC;
//过滤轮廓
std::vector<cv::Point> contourMax = contoursFilter[0];
for (int i = 1; i < contoursFilter.size(); i++)
{
if (cv::contourArea(contoursFilter[i]) > cv::contourArea(contourMax))
{
contourMax = contoursFilter[i];
}
}
//计算最大外接圆半径
float tFRadius = 0;
cv::minEnclosingCircle(contourMax, cv::Point2f(), tFRadius);
cv::Moments mu = cv::moments(contourMax);
cv::Point2f reelCenter(float(mu.m10 / mu.m00), float(mu.m01 / mu.m00));
//画中心
reelCenter.x = reelCenter.x > 0 && reelCenter.x < X ? reelCenter.x : 0;
reelCenter.y = reelCenter.y > 0 && reelCenter.y < Y ? reelCenter.y : 0;
cv::drawMarker(cc, reelCenter, cv::Scalar(0, 0, 238, 255), 1, 35, 2);
//包含未粘连器件
image = cv::Scalar(0);
std::vector<uchar> colors(nccomps + 1, 0);
for (int i = 1; i < nccomps; i++) {
colors[i] = 255;
if ((((int *)m2.data)[(cv::CC_STAT_AREA) + (i)*m2.cols] >= 1.4*sinPartSize) || (((int *)m2.data)[(cv::CC_STAT_AREA) + (i)*m2.cols] < 0.4*sinPartSize))//经验值
{
colors[i] = 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++) {
int label = ((int *)m1.data)[(x)+(y)*m1.cols];
CV_Assert(0 <= label && label <= nccomps);
(image.data)[(x)+(y)*X] = colors[label];
}
}
});
//去掉中心1/3区域干扰
cv::circle(image, reelCenter, cvRound(tFRadius / 3), cv::Scalar(0), -1);
struct TracingAnchor
{
float Size;
float Length, Height;
cv::Point2f Anchor;
cv::RotatedRect RBox;
TracingAnchor(cv::Point2f Anchor, float Length, float Height, float Size, cv::RotatedRect RBox) :Anchor(Anchor), Length(Length), Height(Height), Size(Size), RBox(RBox) {}
bool operator >(const TracingAnchor &te)const
{
return Size > te.Size;
}
bool operator <(const TracingAnchor &te)const
{
return Size < te.Size;
}
};
std::vector<std::vector<cv::Point>> contourTracing;
cv::findContours(image, contourTracing, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
//所有追踪锚点
std::vector<TracingAnchor> tracingAnchors;
for (auto&contour : contourTracing) {
cv::RotatedRect rbox = cv::minAreaRect(contour);
if (cv::min(rbox.size.width, rbox.size.height) > 2.0f) {
tracingAnchors.push_back(TracingAnchor(rbox.center, cv::max(rbox.size.width, rbox.size.height), cv::min(rbox.size.width, rbox.size.height), rbox.size.area(), rbox));
}
}
//不存在独立元件
if (tracingAnchors.empty()) {
return FUNC_CANNOT_CALC;
}
//尺寸只计算一次
std::sort(tracingAnchors.begin(), tracingAnchors.end(), std::greater<TracingAnchor>());
//
struct Track {
int iLimit, iPartSize;
double dMatchDeg = 0.0;
cv::Point2f Pos;
std::vector<cv::Point2f> Rect;
Track() {};
Track(int iLimit, int iPartSize, double dMatchDeg, cv::Point2f Pos, std::vector<cv::Point2f> Rect) :iLimit(iLimit), iPartSize(iPartSize), dMatchDeg(dMatchDeg), Pos(Pos), Rect(Rect) {};
bool operator >(const Track &te)const
{
return dMatchDeg > te.dMatchDeg;
}
bool operator <(const Track &te)const
{
return dMatchDeg < te.dMatchDeg;
}
};
//缩放比例
float coeff = 1.0f;
//填充值
const int fillVal = 255 - backThresh;
//元件尺寸
const double taLength = tracingAnchors[tracingAnchors.size() / 2].Length; const double taHeight = tracingAnchors[tracingAnchors.size() / 2].Height;
//元件灰度值
double taMaxGray = 0.0;
//标签图
unsigned char *ucpTrackLabel = new unsigned char[Y*X]();
cv::Mat trackMat(Y, X, CV_8UC1, ucpTrackLabel);
//计数图像
cv::Mat lbMat(Y, X, CV_8UC1, cv::Scalar(0));
//定位图像
cv::Mat srcPrevS, tplMat;//模板文件
srcPrev.convertTo(srcPrevS, CV_32F);
//随机打乱顺序(降低计算错误dChordL的可能性,也为了测试在起点信息不同时的稳定性)
std::random_shuffle(tracingAnchors.begin(), tracingAnchors.end());
//开始确定起点(现在是用圆轨迹来追踪,不排除用螺旋线轨迹来追踪)
for (std::vector<TracingAnchor>::iterator itvx = tracingAnchors.begin(); itvx != tracingAnchors.end(); ++itvx) {
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularParts 点料阶段被跳过执行...");
break;
}
//起始位置信息
TracingAnchor ta = (*itvx);
//起始位置坐标
cv::Point2f startCenter(ta.Anchor.x, ta.Anchor.y);
//最小外包矩形
cv::Point2f _pts[4];
ta.RBox.points(_pts);
//已做标记(TODO:考虑增加判断哪些是起点哪些不是)
if (trackMat.ptr<uint8_t>(cvRound(startCenter.y))[cvRound(startCenter.x)] == 255) {
continue;
}
//获取模板图像(是否每次起点都计算模板,如果元件变形过大是否还会有用?)
if (tplMat.empty())
{
float tDist = ta.Height / 2.0f;
//理论范围扩展
cv::Rect _rLimits = cv::Rect(cv::Point2i(cvRound((float)ta.RBox.boundingRect2f().tl().x - tDist),
cvRound((float)ta.RBox.boundingRect2f().tl().y - tDist)), cv::Point2i(cvRound((float)ta.RBox.boundingRect2f().br().x + tDist),
cvRound((float)ta.RBox.boundingRect2f().br().y + tDist))
)&cv::Rect(0, 0, X, Y);
//确定元件位置根据旋转后的位置确定(前提是料盘中心定位的准确)
double t = atan2((double)startCenter.y - reelCenter.y, (double)startCenter.x - reelCenter.x) * 180.0 / PI;
//计算旋转角度
cv::Mat traceMat = srcPrev(_rLimits);
//这里计算得出的模板不是很对
float matx[6];
tplMat = getTrackMat(traceMat, t + 90.0, 0, matx);
//变换后的坐标
cv::Point2f __pts[4];
for (int j = 0; j < 4; j++)
{
__pts[j].x = matx[0] * (_pts[j].x - (float)_rLimits.x) + matx[1] * (_pts[j].y - (float)_rLimits.y) + matx[2];
__pts[j].y = matx[3] * (_pts[j].x - (float)_rLimits.x) + matx[4] * (_pts[j].y - (float)_rLimits.y) + matx[5];
}
cv::Point2f __ptsc((__pts[0].x + __pts[1].x + __pts[2].x + __pts[3].x) / 4.0f, (__pts[0].y + __pts[1].y + __pts[2].y + __pts[3].y) / 4.0f);
//确定各顶点方位
struct DIR {
int i = -1;
cv::Point2f pt;
DIR() {};
DIR(int i, cv::Point2f pt) :i(i), pt(pt) {};
};
auto _dir_l = std::vector<DIR>(); auto _dir_r = std::vector<DIR>();
for (int j = 0; j < 4; j++)
{
if (__pts[j].x < __ptsc.x) {
_dir_l.push_back(DIR(j, __pts[j]));
}
else {
_dir_r.push_back(DIR(j, __pts[j]));
}
}
//重新选点计算模板
if (_dir_l.size() != _dir_r.size()) {
continue;
}
//确定顶点方向
cv::Point2f p0, p1, p2, p3;
if (_dir_l[0].pt.y < _dir_l[1].pt.y) {
p0 = _pts[_dir_l[0].i];
p1 = _pts[_dir_l[1].i];
}
else {
p0 = _pts[_dir_l[1].i];
p1 = _pts[_dir_l[0].i];
}
if (_dir_r[0].pt.y > _dir_r[1].pt.y) {
p2 = _pts[_dir_r[0].i];
p3 = _pts[_dir_r[1].i];
}
else {
p2 = _pts[_dir_r[1].i];
p3 = _pts[_dir_r[0].i];
}
//计算精确角度
cv::Point2f p01((p0.x + p1.x) / 2.0f, (p0.y + p1.y) / 2.0f), p23((p2.x + p3.x) / 2.0f, (p2.y + p3.y) / 2.0f);
double realT = atan2((double)p23.y - (double)p01.y, (double)p23.x - (double)p01.x) * 180.0 / PI;
cv::Mat realTplMat = getTrackMat(traceMat, realT, 0, matx);
cv::Point2f __mpts[4];
for (int j = 0; j < 4; j++)
{
__mpts[j].x = matx[0] * (_pts[j].x - (float)_rLimits.x) + matx[1] * (_pts[j].y - (float)_rLimits.y) + matx[2];
__mpts[j].y = matx[3] * (_pts[j].x - (float)_rLimits.x) + matx[4] * (_pts[j].y - (float)_rLimits.y) + matx[5];
}
cv::Rect _rr(cvFloor(std::min(std::min(std::min(__mpts[0].x, __mpts[1].x), __mpts[2].x), __mpts[3].x)),
cvFloor(std::min(std::min(std::min(__mpts[0].y, __mpts[1].y), __mpts[2].y), __mpts[3].y)),
cvCeil(std::max(std::max(std::max(__mpts[0].x, __mpts[1].x), __mpts[2].x), __mpts[3].x)),
cvCeil(std::max(std::max(std::max(__mpts[0].y, __mpts[1].y), __mpts[2].y), __mpts[3].y))); _rr.width -= _rr.x - 1; _rr.height -= _rr.y - 1;
//最终模板
tplMat = realTplMat(_rr).clone();
//缩放比例
if (MIN(tplMat.size().width, tplMat.size().height) < 12.0) {
coeff = 2.0f;
}
//最大值
cv::minMaxLoc(tplMat, NULL, &taMaxGray);
}
//标记为已追踪过
std::vector<cv::Point> vT = { cv::Point(_pts[0]),cv::Point(_pts[1]) ,cv::Point(_pts[2]) ,cv::Point(_pts[3]) };
cv::fillConvexPoly(trackMat, vT, cv::Scalar(255));
//标记计数
lbMat.ptr<uint8_t>(cvRound(startCenter.y))[cvRound(startCenter.x)] = 255;
//标记当前位置
cv::drawMarker(cc, cv::Point(startCenter), cv::Scalar(0, 255, 0, 255), cv::MARKER_DIAMOND, 5);
//扫描步长
const double dMinorStep = 0.1;
//追踪长宽
const double trackLength = taLength / 2.0, trackWidth = taHeight / 4.0;//是否用较小尺寸的窗口
//起始扫描角度
const double startAngle = atan2((double)startCenter.y - reelCenter.y, (double)startCenter.x - reelCenter.x) * 180.0 / PI;
//起始扫描半径
const double startRadius = cv::norm(startCenter - reelCenter);
//偏移角度(元件尺寸)
const double dOffset = (2.0 * asin(2.0 * trackLength / (2.0 * startRadius))) * 180.0 / PI;
//扫描角度(默认15度范围内存在元件)
const double dScanRange = 15.0;
//追踪元件间距(弦长,可以尽量避免因个别器件偏离导致的追踪中断)
double dChordL = .0;
for (double t = startAngle + dOffset / 1.5; t < startAngle + dScanRange; t += dMinorStep)
{
float x = float(reelCenter.x + startRadius*cos(t*c));
float y = float(reelCenter.y + startRadius*sin(t*c));
//防止超出图像范围
if (cvRound(x) < 0 || (cvRound(x) > X - 1) || cvRound(y) < 0 || (cvRound(y) > Y - 1)) {
break;
}
//确定是否是下一个元件
if (trackMat.ptr<uint8_t>(cvRound(y))[cvRound(x)] == 255) {
continue;
}
//初次确定元件间距
const double angle = atan2((double)reelCenter.y - y, (double)reelCenter.x - x);
cv::Point p1 = cv::Point(cvRound(x + trackWidth * cos(angle)),
cvRound(y + trackWidth * sin(angle)));
cv::Point p2 = cv::Point(cvRound(x + trackWidth * cos(angle + CV_PI)),
cvRound(y + trackWidth * sin(angle + CV_PI)));
#ifdef _DEBUG
cv::line(cc, p1, p2, cv::Scalar(0, 215, 255, 255), 1);
#endif
cv::LineIterator it(binary, p1, p2, 4);
for (int n = 0; n < it.count; n++, ++it)
{
if (binary.ptr<uint8_t>(it.pos().y)[it.pos().x] == 255)
{
//计算元件间距(弦长)
dChordL = 2.0 * startRadius*sin(((2.0 * asin((cv::norm(startCenter - cv::Point2f(x, y))) / (2.0 * startRadius))) * 180.0 / PI - dOffset / 2.0)*PI / 180.0 / 2.0);
break;
}
}
if (dChordL > 2.1)
break;
}
//没确定出元件间距一般为结尾或单个元件,继续从下一个起点计算弦长并开始追踪
if (dChordL <= 2.1) {
continue;
}
//顺时针(是否并行取决于在windows下运行还是树莓派上)
{
//追踪中心
cv::Point2f trackCenter = cv::Point2f(startCenter.x, startCenter.y);
//追踪角度、半径
double trackAngle = startAngle, trackRadius = startRadius;
//元件本身所占角度
double trackOffset = dOffset;
//元件间间距
double partDist = (2.0 * asin(dChordL / (2.0 * trackRadius))) * 180.0 / PI;
//开始追踪
bool trackEnd = true;
do
{
bool found = true; bool trayEnd = false;
std::vector<Track> vParts;
for (double t = trackAngle + (trackOffset + partDist - trackOffset / 12.0); t < trackAngle + (trackOffset + partDist - trackOffset / 12.0) + trackOffset / 6.0; t += dMinorStep)
{
cv::Point2f predicPos;
predicPos.x = reelCenter.x + (float)trackRadius*(float)cos((trackAngle + (trackOffset + partDist))*c);
predicPos.y = reelCenter.y + (float)trackRadius*(float)sin((trackAngle + (trackOffset + partDist))*c);
//如果追踪到图像外则追踪终止
if (cvRound(predicPos.x) < 0 || (cvRound(predicPos.x) > X - 1) || cvRound(predicPos.y) < 0 || (cvRound(predicPos.y) > Y - 1)) {
trayEnd = true;
break;
}
//感兴趣区域(向外扩展了一个元件,防止中心定位出现偏差或者料盘本身变形导致的偏差)
cv::Point2f predictBox[4];
calcRotateRect(predicPos, (float)(trackAngle + (trackOffset + partDist)), (float)trackLength + (float)trackLength, (float)trackWidth + (float)trackWidth, predictBox);
cv::RotatedRect r(predictBox[0], predictBox[1], predictBox[2]);
cv::Rect rLimits = r.boundingRect()&cv::Rect(0, 0, X, Y);
//获取感兴趣区域
float matx[6];
cv::Mat traceMat = getTrackMat(srcPrevS(rLimits).clone()
, (trackAngle + (trackOffset + partDist)) + 90.0, fillVal, matx);
//计算原图中的点在旋转后的位置(即在traceMat中的精确位置)
cv::Point2f predictBoxR[4];
for (int j = 0; j < 4; j++)
{
predictBoxR[j].x = matx[0] * (predictBox[j].x - (float)rLimits.x) + matx[1] * (predictBox[j].y - (float)rLimits.y) + matx[2];
predictBoxR[j].y = matx[3] * (predictBox[j].x - (float)rLimits.x) + matx[4] * (predictBox[j].y - (float)rLimits.y) + matx[5];
}
//中点
cv::Point2f predicPosR((predictBoxR[0].x + predictBoxR[1].x + predictBoxR[2].x + predictBoxR[3].x) / 4.0f,
(predictBoxR[0].y + predictBoxR[1].y + predictBoxR[2].y + predictBoxR[3].y) / 4.0f);
//理论区域
cv::Rect tRec = cv::Rect(cv::Point(cvRound((predicPosR.x*2.0f - (float)trackLength*2.0f) / 2.0f),
cvRound((predicPosR.y*2.0f - (float)trackWidth*4.0f) / 2.0f)),
cv::Size(cvRound(trackLength*2.0), cvRound(trackWidth*4.0)))
&cv::Rect(0, 0, traceMat.cols, traceMat.rows);
//高精度理论区域
cv::Rect_<float> tRecF = cv::Rect_<float>(cv::Point2f((predicPosR.x*2.0f - (float)trackLength*2.0f) / 2.0f,
(predicPosR.y*2.0f - (float)trackWidth*4.0f) / 2.0f),
cv::Size2f((float)trackLength*2.0f, (float)trackWidth*4.0f))
&cv::Rect_<float>(0.0f, 0.0f, (float)traceMat.cols, (float)traceMat.rows);
//理论区域向外扩展(即predictBox范围)
cv::Rect rr = cv::Rect(cv::Point(cvRound((double)predicPosR.x - trackLength*2.0),
cvRound((double)predicPosR.y - trackWidth*4.0)), cv::Size(cvRound(trackLength*2.0*2.0),
cvRound(trackWidth*4.0*2.0)))&cv::Rect(0, 0, traceMat.cols, traceMat.rows);
cv::Rect_<float> rrf = cv::Rect2f(cv::Point2f((predicPosR.x*2.0f - (float)trackLength*4.0f) / 2.0f,
(predicPosR.y*2.0f - (float)trackWidth*8.0f) / 2.0f), cv::Size2f((float)trackLength*4.0f, (float)trackWidth*8.0f))
&cv::Rect2f(0.0f, 0.0f, (float)traceMat.cols, (float)traceMat.rows);
//元件尺寸太小放大N倍处理,这样坐标会精细些,考虑元件的80%尺寸作为kernel,防止元件尺寸变化太大
cv::Mat kernel = cv::Mat::ones(cv::Size(cv::max(cvRound((float)(trackLength*2.0) * coeff),
cvRound((float)(trackWidth*4.0) * coeff)), cv::min(cvRound((float)(trackLength*2.0) * coeff),
cvRound((float)(trackWidth*4.0) * coeff))), CV_32FC1);
cv::Mat _traceMat = traceMat.clone();
//放大
if (coeff > 1.0f) {
cv::resize(_traceMat, _traceMat, cv::Size(cvRound(traceMat.size().width * coeff), cvRound(traceMat.size().height * coeff)));
}
//计算最大值(当_traceMat尺寸小于kernel会报错)
cv::Mat dst;
cv::filter2D(_traceMat, dst, CV_32F, kernel);
//归一化
cv::Mat mmRescaling;
cv::normalize(dst, mmRescaling, 1.0, 0.0, cv::NORM_MINMAX);
//模板匹配做辅助判断,为了尽量避免定位出错
cv::Mat _tplMat;
tplMat.convertTo(_tplMat, CV_32FC1);
if (coeff > 1.0f) {
cv::resize(_tplMat, _tplMat, cv::Size(), coeff, coeff);
}
//防止报错
if (_tplMat.cols > _traceMat.cols || _tplMat.rows > _traceMat.rows) {
return FUNC_CANNOT_CALC;
}
//考虑并行计算两个模板结果
cv::Mat tplResult0;
cv::matchTemplate(_traceMat, _tplMat, tplResult0, cv::TM_SQDIFF_NORMED);
int modx = _tplMat.cols % 2, mody = _tplMat.rows % 2;
cv::Mat tplResultMap;
cv::copyMakeBorder(tplResult0, tplResultMap, (_tplMat.rows - mody) / 2, _traceMat.rows - tplResult0.rows - (_tplMat.rows - mody) / 2,
(_tplMat.cols - modx) / 2, _traceMat.cols - tplResult0.cols - (_tplMat.cols - modx) / 2, cv::BORDER_REPLICATE);
//减去模板匹配的结果
mmRescaling -= tplResultMap;
//非极大值抑制
cv::Mat mask;
cv::dilate(mmRescaling, mask, cv::Mat());
cv::compare(mmRescaling, mask, mask, cv::CMP_GE);
cv::Mat non_plateau_mask;
cv::erode(mmRescaling, non_plateau_mask, cv::Mat());
cv::compare(mmRescaling, non_plateau_mask, non_plateau_mask, cv::CMP_GT);
cv::bitwise_and(mask, non_plateau_mask, mask);
//去掉分数过低的
mask &= cv::Mat(mmRescaling > 0.36);
//限定区域(mmRescaling范围内)
cv::Rect _rr = cv::Rect(cvRound(rr.x*coeff), cvRound(rr.y*coeff), cvRound(rr.width*coeff), cvRound(rr.height*coeff));
//候选元件位置
std::vector<cv::Point> candidates;
cv::findNonZero(mask(_rr), candidates);
//过滤
std::vector<Track> _vParts;
for (auto&candidate : candidates) {
cv::Point pt(candidate.x + _rr.x, candidate.y + _rr.y);
float confidence = mmRescaling.ptr<float>(pt.y)[pt.x];
if (confidence > 0.5f) {
_vParts.push_back(Track(0, 0, confidence, cv::Point2f((float)pt.x, (float)pt.y), std::vector<cv::Point2f>()));
}
}
//目标元件在小图中的位置
cv::Point2f maxLox;
//元件位置判断
if (_vParts.size() <= 0) {
//大概率终止
trayEnd = true;
}
else if (_vParts.size() == 1) {
//有可能会出错
maxLox = cv::Point2f(_vParts[0].Pos.x / coeff, _vParts[0].Pos.y / coeff);
if (tRecF.contains(maxLox)) {
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle + (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
}
else {
//这里负责处理意外情况(极大可能是元件偏离过多或者料盘中心定位不准确导致的),
//采用距离理论位置最近的点(两种方式都失效的概率比较低,如果真的失效那就听天由命吧)
cv::Mat _mmRescaling, _tplResultMap;
_mmRescaling = mmRescaling.clone(); _tplResultMap = tplResultMap.clone();
//累加的方式
double maxVal; cv::Point maxLoc;
cv::minMaxLoc(_mmRescaling(_rr), NULL, &maxVal, NULL, &maxLoc);
maxLoc += _rr.tl();
//模板匹配的方式
double minVal; cv::Point minLoc;
cv::minMaxLoc(_tplResultMap(_rr), &minVal, NULL, &minLoc, NULL);
minLoc += _rr.tl();
std::vector<Track> __vParts;
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)maxLoc.x, (float)maxLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)maxLoc.x, (float)maxLoc.y), std::vector<cv::Point2f>()));
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)minLoc.x, (float)minLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)minLoc.x, (float)minLoc.y), std::vector<cv::Point2f>()));
//排序
std::sort(__vParts.begin(), __vParts.end(), std::less<Track>());
//在小图中的位置
maxLox = cv::Point2f(__vParts[0].Pos.x / coeff, __vParts[0].Pos.y / coeff);
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle + (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
#ifdef _DEBUG
for (int j = 0; j < 4; j++)
{
cv::line(cc, predictBox[j], predictBox[(j + 1) % 4], cv::Scalar(0, 0, 255, 255), 1);
}
#endif
}
}
else {
//存在多个峰值,先判断分数最高是否位于理论位置
std::sort(_vParts.begin(), _vParts.end(), std::greater<Track>());
for (auto&_vPart : _vParts) {
maxLox = cv::Point2f(_vPart.Pos.x / coeff, _vPart.Pos.y / coeff);
if (tRecF.contains(maxLox)) {
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle + (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
break;
}
}
//如果不在则选取距离理论位置最近的
if (vParts.empty()) {
//这里负责处理意外情况(极大可能是元件偏离过多或者中心定位不准确)
//,采用距离理论位置最近的点(两种方式都失效的概率比较低)
cv::Mat _mmRescaling, _tplResultMap;
_mmRescaling = mmRescaling.clone(); _tplResultMap = tplResultMap.clone();
//累加的方式
double maxVal; cv::Point maxLoc;
cv::minMaxLoc(_mmRescaling(_rr), NULL, &maxVal, NULL, &maxLoc);
maxLoc += _rr.tl();
//模板匹配的方式
double minVal; cv::Point minLoc;
cv::minMaxLoc(_tplResultMap(_rr), &minVal, NULL, &minLoc, NULL);
minLoc += _rr.tl();
std::vector<Track> __vParts;
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)maxLoc.x, (float)maxLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)maxLoc.x, (float)maxLoc.y), std::vector<cv::Point2f>()));
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)minLoc.x, (float)minLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)minLoc.x, (float)minLoc.y), std::vector<cv::Point2f>()));
//排序
std::sort(__vParts.begin(), __vParts.end(), std::less<Track>());
//在小图中的位置
maxLox = cv::Point2f(__vParts[0].Pos.x / coeff, __vParts[0].Pos.y / coeff);
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle + (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
#ifdef _DEBUG
for (int j = 0; j < 4; j++)
{
cv::line(cc, predictBox[j], predictBox[(j + 1) % 4], cv::Scalar(0, 0, 255, 255), 1);
}
#endif
}
}
if (!vParts.empty()) {
cv::Rect tRec_ = cv::Rect(cv::Point(cvFloor((((float)maxLox.x)*2.0f - (float)trackLength*2.0f) / 2.0f),
cvFloor((((float)maxLox.y)*2.0f - (float)trackWidth*4.0f) / 2.0f)),
cv::Size(cvRound(trackLength*2.0) + 2, cvRound(trackWidth*4.0) + 2))
&cv::Rect(0, 0, traceMat.cols, traceMat.rows);
//当作一种辅助手段,无需设置太严格
double dmax;
cv::minMaxLoc(traceMat(tRec_).clone(), NULL, &dmax);
if (dmax < 0.7*taMaxGray) {
trayEnd = true;
}
}
break;
}
//追踪终止,选取下一个起点
if (trayEnd) {
break;
}
//更新位置
trackCenter = cv::Point2f(vParts[0].Pos.x, vParts[0].Pos.y);
//更新扫描半径
trackRadius = cv::norm(trackCenter - reelCenter);
//更新扫描角度
trackAngle = atan2((double)trackCenter.y - (double)reelCenter.y, (double)trackCenter.x - (double)reelCenter.x) * 180.0 / PI;
//更新偏移量(元件角度大小)
trackOffset = (2 * asin(2 * trackLength / (2 * trackRadius))) * 180.0 / PI;
//更新元件间角度
partDist = (2 * asin(dChordL / (2 * trackRadius))) * 180.0 / PI;
//追踪到了重复的元件
if ((trackCenter.x<0 || trackCenter.x>X - 1 ||
trackCenter.y<0 || trackCenter.y>Y - 1) || trackMat.ptr<uint8_t>(cvRound(trackCenter.y))[cvRound(trackCenter.x)] == 255) {
found = false;
}
else {
//计算元件位置
cv::Point2f pts[4];
calcRotateRect(trackCenter, (float)trackAngle, (float)trackLength, (float)trackWidth, pts);
//标记计数
lbMat.ptr<uint8_t>(cvRound(trackCenter.y))[cvRound(trackCenter.x)] = 255;
//标记为已追踪过
std::vector<cv::Point> vT = { cv::Point(pts[0]),cv::Point(pts[1]) ,cv::Point(pts[2]) ,cv::Point(pts[3]) };
cv::fillConvexPoly(trackMat, vT, cv::Scalar(255));
//用于显示
cv::circle(cc, trackCenter, 2, cv::Scalar(0, 255, 0, 255), 1);
#ifdef _DEBUG
for (int j = 0; j < 4; j++)
{
cv::line(cc, pts[j], pts[(j + 1) % 4], cv::Scalar(14, 173, 238, 255), 1);
}
#endif
}
//清空下一个
vParts.resize(0);
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularPartsE 追踪阶段被跳过执行...");
found = false;
}
trackEnd = (!found);
} while (!trackEnd);
}
//逆时针
{
//追踪起点
cv::Point2f trackCenter(startCenter.x, startCenter.y);
//追踪角度、半径
double trackAngle = startAngle, trackRadius = startRadius;
//元件本身角度
double trackOffset = dOffset;
//元件间间距
double partDist = (2.0 * asin(dChordL / (2.0 * trackRadius))) * 180.0 / PI;
//开始追踪
bool trackEnd = true;
//
do
{
bool found = true; bool trayEnd = false;
std::vector<Track> vParts;
for (double t = trackAngle - (trackOffset + partDist - trackOffset / 12.0); t > trackAngle - (trackOffset + partDist - trackOffset / 12.0) - trackOffset / 6.0; t -= dMinorStep)
{
cv::Point2f predicPos;
predicPos.x = reelCenter.x + (float)trackRadius*(float)cos((trackAngle - (trackOffset + partDist))*c);
predicPos.y = reelCenter.y + (float)trackRadius*(float)sin((trackAngle - (trackOffset + partDist))*c);
//如果追踪到图像外追踪终止
if (cvRound(predicPos.x) < 0 || (cvRound(predicPos.x) > X - 1) || cvRound(predicPos.y) < 0 || (cvRound(predicPos.y) > Y - 1)) {
trayEnd = true;
break;
}
//感兴趣区域(向外扩展了一个元件,防止中心定位出现偏差或者料盘本身变形导致的偏差)
cv::Point2f predicBox[4];
calcRotateRect(predicPos, (float)(trackAngle - (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, predicBox);
cv::RotatedRect r(predicBox[0], predicBox[1], predicBox[2]);
cv::Rect rLimits = r.boundingRect()&cv::Rect(0, 0, X, Y);
//获取感兴趣区域
float matx[6];
cv::Mat traceMat = getTrackMat(srcPrevS(rLimits).clone()
, (trackAngle - (trackOffset + partDist)) + 90.0, fillVal, matx);
//计算原图中的点在旋转后的位置(即在traceMat中的精确位置)
cv::Point2f predictBoxR[4];
for (int j = 0; j < 4; j++)
{
predictBoxR[j].x = matx[0] * (predicBox[j].x - (float)rLimits.x) + matx[1] * (predicBox[j].y - (float)rLimits.y) + matx[2];
predictBoxR[j].y = matx[3] * (predicBox[j].x - (float)rLimits.x) + matx[4] * (predicBox[j].y - (float)rLimits.y) + matx[5];
}
//中点
cv::Point2f predicPosR((predictBoxR[0].x + predictBoxR[1].x + predictBoxR[2].x + predictBoxR[3].x) / 4.0f,
(predictBoxR[0].y + predictBoxR[1].y + predictBoxR[2].y + predictBoxR[3].y) / 4.0f);
//理论区域
cv::Rect tRec = cv::Rect(cv::Point(cvRound((predicPosR.x*2.0f - (float)trackLength*2.0f) / 2.0f),
cvRound((predicPosR.y*2.0f - (float)trackWidth*4.0f) / 2.0f)),
cv::Size(cvRound(trackLength*2.0), cvRound(trackWidth*4.0)))
&cv::Rect(0, 0, traceMat.cols, traceMat.rows);
//高精度理论区域
cv::Rect_<float> tRecF = cv::Rect_<float>(cv::Point2f((predicPosR.x*2.0f - (float)trackLength*2.0f) / 2.0f,
(predicPosR.y*2.0f - (float)trackWidth*4.0f) / 2.0f),
cv::Size2f((float)trackLength*2.0f, (float)trackWidth*4.0f))
&cv::Rect_<float>(0.0f, 0.0f, (float)traceMat.cols, (float)traceMat.rows);
//理论区域向外扩展(即predictBox范围)
cv::Rect rr = cv::Rect(cv::Point(cvRound((double)predicPosR.x - trackLength*2.0),
cvRound((double)predicPosR.y - trackWidth*4.0)), cv::Size(cvRound(trackLength*2.0*2.0),
cvRound(trackWidth*4.0*2.0)))&cv::Rect(0, 0, traceMat.cols, traceMat.rows);
cv::Rect_<float> rrf = cv::Rect2f(cv::Point2f((predicPosR.x*2.0f - (float)trackLength*4.0f) / 2.0f,
(predicPosR.y*2.0f - (float)trackWidth*8.0f) / 2.0f), cv::Size2f((float)trackLength*4.0f, (float)trackWidth*8.0f))
&cv::Rect2f(0.0f, 0.0f, (float)traceMat.cols, (float)traceMat.rows);
//元件尺寸太小放大N倍处理,这样坐标会精细些,元件的80%尺寸作为kernel,防止元件尺寸变化太大
cv::Mat kernel = cv::Mat::ones(cv::Size(cv::max(cvRound((float)(trackLength*2.0) * coeff),
cvRound((float)(trackWidth*4.0) * coeff)), cv::min(cvRound((float)(trackLength*2.0) * coeff),
cvRound((float)(trackWidth*4.0) * coeff))), CV_32FC1);
cv::Mat _traceMat = traceMat.clone();
//放大
if (coeff > 1.0f) {
cv::resize(_traceMat, _traceMat, cv::Size(cvRound(traceMat.size().width * coeff), cvRound(traceMat.size().height * coeff)));
}
//计算最大值(当_traceMat尺寸小于kernel会报错)
cv::Mat dst;
cv::filter2D(_traceMat, dst, CV_32F, kernel);
//归一化
cv::Mat mmRescaling;
cv::normalize(dst, mmRescaling, 1.0, 0.0, cv::NORM_MINMAX);
//模板匹配,为了尽量避免定位出错
cv::Mat _tplMat;
tplMat.convertTo(_tplMat, CV_32FC1);
if (coeff > 1.0f) {
cv::resize(_tplMat, _tplMat, cv::Size(), coeff, coeff);
}
//防止报错
if (_tplMat.cols > _traceMat.cols || _tplMat.rows > _traceMat.rows) {
return FUNC_CANNOT_CALC;
}
//考虑并行计算两个模板结果
cv::Mat tplResult0;
cv::matchTemplate(_traceMat, _tplMat, tplResult0, cv::TM_SQDIFF_NORMED);
int modx = _tplMat.cols % 2, mody = _tplMat.rows % 2;
cv::Mat tplResultMap;
cv::copyMakeBorder(tplResult0, tplResultMap, (_tplMat.rows - mody) / 2, _traceMat.rows - tplResult0.rows - (_tplMat.rows - mody) / 2,
(_tplMat.cols - modx) / 2, _traceMat.cols - tplResult0.cols - (_tplMat.cols - modx) / 2, cv::BORDER_REPLICATE);
//减去模板匹配的结果
mmRescaling -= tplResultMap;
//非极大值抑制
cv::Mat mask;
cv::dilate(mmRescaling, mask, cv::Mat());
cv::compare(mmRescaling, mask, mask, cv::CMP_GE);
cv::Mat non_plateau_mask;
cv::erode(mmRescaling, non_plateau_mask, cv::Mat());
cv::compare(mmRescaling, non_plateau_mask, non_plateau_mask, cv::CMP_GT);
cv::bitwise_and(mask, non_plateau_mask, mask);
//去掉分数过低的
mask &= cv::Mat(mmRescaling > 0.36);
//限定区域(mmRescaling范围内)
cv::Rect _rr = cv::Rect(cvRound(rr.x*coeff), cvRound(rr.y*coeff), cvRound(rr.width*coeff), cvRound(rr.height*coeff));
//候选元件位置
std::vector<cv::Point> candidates;
cv::findNonZero(mask(_rr), candidates);
//过滤
std::vector<Track> _vParts;
for (auto&candidate : candidates) {
cv::Point pt(candidate.x + _rr.x, candidate.y + _rr.y);
float confidence = mmRescaling.ptr<float>(pt.y)[pt.x];
if (confidence > 0.5f) {
_vParts.push_back(Track(0, 0, confidence, cv::Point2f((float)pt.x, (float)pt.y), std::vector<cv::Point2f>()));
}
}
//目标元件在小图中的位置
cv::Point2f maxLox;
//元件位置判断
if (_vParts.size() <= 0) {
//大概率终止
trayEnd = true;
}
else if (_vParts.size() == 1) {
maxLox = cv::Point2f(_vParts[0].Pos.x / coeff, _vParts[0].Pos.y / coeff);
//有可能会出错,当靠的太近可能只存在一个峰值
if (tRecF.contains(maxLox)) {
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle + (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
}
else {
//这里负责处理意外情况(极大可能是元件偏离过多或者中心定位不准确),采用距离理论位置最近的点(两种方式都失效的概率比较低)
cv::Mat _mmRescaling, _tplResultMap;
_mmRescaling = mmRescaling.clone(); _tplResultMap = tplResultMap.clone();
//累加的方式
double maxVal; cv::Point maxLoc;
cv::minMaxLoc(_mmRescaling(_rr), NULL, &maxVal, NULL, &maxLoc);
maxLoc += _rr.tl();
//模板匹配的方式
double minVal; cv::Point minLoc;
cv::minMaxLoc(_tplResultMap(_rr), &minVal, NULL, &minLoc, NULL);
minLoc += _rr.tl();
std::vector<Track> __vParts;
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)maxLoc.x, (float)maxLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)maxLoc.x, (float)maxLoc.y), std::vector<cv::Point2f>()));
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)minLoc.x, (float)minLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)minLoc.x, (float)minLoc.y), std::vector<cv::Point2f>()));
//排序
std::sort(__vParts.begin(), __vParts.end(), std::less<Track>());
//小图中的定位坐标
maxLox = cv::Point2f(__vParts[0].Pos.x / coeff, __vParts[0].Pos.y / coeff);
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle - (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
#ifdef _DEBUG
for (int j = 0; j < 4; j++)
{
cv::line(cc, predicBox[j], predicBox[(j + 1) % 4], cv::Scalar(0, 0, 238, 255), 1);
}
#endif
}
}
else {
//存在定位出错的可能性,先判断分数最高是否位于理论位置
std::sort(_vParts.begin(), _vParts.end(), std::greater<Track>());
for (auto&_vPart : _vParts) {
maxLox = cv::Point2f(_vPart.Pos.x / coeff, _vPart.Pos.y / coeff);
if (tRecF.contains(maxLox)) {
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle - (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
break;
}
}
//如果不在则选取距离理论位置最近的
if (vParts.empty()) {
//这里负责处理意外情况(极大可能是元件偏离过多或者中心定位不准确),采用距离理论位置最近的点(两种方式都失效的概率比较低)
cv::Mat _mmRescaling, _tplResultMap;
_mmRescaling = mmRescaling.clone(); _tplResultMap = tplResultMap.clone();
//累加的方式
double maxVal; cv::Point maxLoc;
cv::minMaxLoc(_mmRescaling(_rr), NULL, &maxVal, NULL, &maxLoc);
maxLoc += _rr.tl();
//模板匹配的方式
double minVal; cv::Point minLoc;
cv::minMaxLoc(_tplResultMap(_rr), &minVal, NULL, &minLoc, NULL);
minLoc += _rr.tl();
std::vector<Track> __vParts;
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)maxLoc.x, (float)maxLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)maxLoc.x, (float)maxLoc.y), std::vector<cv::Point2f>()));
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)minLoc.x, (float)minLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)minLoc.x, (float)minLoc.y), std::vector<cv::Point2f>()));
//排序
std::sort(__vParts.begin(), __vParts.end(), std::less<Track>());
//小图中的位置
maxLox = cv::Point2f(__vParts[0].Pos.x / coeff, __vParts[0].Pos.y / coeff);
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle - (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
#ifdef _DEBUG
for (int j = 0; j < 4; j++)
{
cv::line(cc, predicBox[j], predicBox[(j + 1) % 4], cv::Scalar(0, 0, 238, 255), 1);
}
#endif
}
}
if (!vParts.empty()) {
cv::Rect tRec_ = cv::Rect(cv::Point(cvFloor((((float)maxLox.x)*2.0f - (float)trackLength*2.0f) / 2.0f),
cvFloor((((float)maxLox.y)*2.0f - (float)trackWidth*4.0f) / 2.0f)),
cv::Size(cvRound(trackLength*2.0) + 2, cvRound(trackWidth*4.0) + 2))
&cv::Rect(0, 0, traceMat.cols, traceMat.rows);
//当作一种辅助手段,无需设置太严格
double dmax;
cv::minMaxLoc(traceMat(tRec_).clone(), NULL, &dmax);
if (dmax < 0.7*taMaxGray) {
trayEnd = true;
}
}
break;
}
//接着下一个起点
if (trayEnd) {
break;
}
//更新位置
trackCenter = cv::Point2f(vParts[0].Pos.x, vParts[0].Pos.y);
//更新扫描半径
trackRadius = cv::norm(trackCenter - reelCenter);
//更新扫描角度
trackAngle = atan2((double)trackCenter.y - (double)reelCenter.y, (double)trackCenter.x - (double)reelCenter.x) * 180.0 / PI;
//更新偏移量(元件角度大小)
trackOffset = (2.0 * asin(2.0 * trackLength / (2.0 * trackRadius))) * 180.0 / PI;
//更新元件间角度
partDist = (2.0 * asin(dChordL / (2.0 * trackRadius))) * 180.0 / PI;
//追踪到了重复的元件
if ((trackCenter.x<0 || trackCenter.x>X - 1 ||
trackCenter.y<0 || trackCenter.y>Y - 1) || trackMat.ptr<uint8_t>(cvRound(trackCenter.y))[cvRound(trackCenter.x)] == 255) {
found = false;
}
else {
//计算元件位置
cv::Point2f pts[4];
calcRotateRect(trackCenter, (float)trackAngle, (float)trackLength, (float)trackWidth, pts);
//标记计数
lbMat.ptr<uint8_t>(cvRound(trackCenter.y))[cvRound(trackCenter.x)] = 255;
//标记为已追踪过
std::vector<cv::Point> vT = { cv::Point(pts[0]),cv::Point(pts[1]) ,cv::Point(pts[2]) ,cv::Point(pts[3]) };
cv::fillConvexPoly(trackMat, vT, cv::Scalar(255));
//用于显示
cv::circle(cc, trackCenter, 2, cv::Scalar(0, 255, 0, 255), 1);
#ifdef _DEBUG
for (int j = 0; j < 4; j++)
{
cv::line(cc, pts[j], pts[(j + 1) % 4], cv::Scalar(102, 205, 0, 255), 1);
}
#endif
}
//继续下一个起点
vParts.resize(0);
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularParts 追踪阶段被跳过执行...");
found = false;
}
trackEnd = (!found);
} while (!trackEnd);
}
}
//计数
binary = lbMat.clone();
//释放资源
delete[] ucpTrackLabel;
ucpTrackLabel = NULL;
}
else if (strcmp(ccSubType, "IP_LONG_PARTS") == 0)
{
//二值化
cv::threshold(srcPrev, binary, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
cv::morphologyEx(binary, binary, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(75, 75)));
//计算直方图
int hist[256];
for (int y = 0; y < 256; y++) hist[y] = 0;
for (int y = 0; y < Y; y++)
{
uchar *uPtr = srcPrev.data + y * X;
for (int x = 0; x < srcPrev.cols; x++, uPtr++)
{
if (binary.ptr<uint8_t>(y)[x] == 255) {
hist[*uPtr]++;
}
}
}
cv::threshold(srcPrev, binary, Otsu(hist), 255, cv::THRESH_BINARY);
//去掉料盘深色部分
cv::Mat srcPrevEx;
cv::morphologyEx(srcPrev, srcPrevEx, cv::MORPH_TOPHAT, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)));
cv::threshold(srcPrevEx, srcPrevEx, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
//获得元件区域
cv::morphologyEx(srcPrevEx, srcPrevEx, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(75, 75)));
//去掉干扰
binary &= srcPrevEx;
//将断裂处连接在一起?
cv::morphologyEx(binary, binary, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)));
//计算元件大小
cv::Mat m1, m2, m3;
int nccomps = cv::connectedComponentsWithStats(binary, m1, m2, m3);
std::vector<uchar> colors0(nccomps + 1, 0);
for (int i = 1; i < nccomps; i++) {
colors0[i] = 255;
if ((((int *)m2.data)[(cv::CC_STAT_AREA) + (i)*m2.cols] <= 2))//经验值
{
colors0[i] = 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++) {
int label = ((int *)m1.data)[(x)+(y)*m1.cols];
CV_Assert(0 <= label && label <= nccomps);
(binary.data)[(x)+(y)*X] = colors0[label];
}
}
});
nccomps = cv::connectedComponentsWithStats(binary, m1, m2, m3);
//不存在独立元件
if (nccomps <= 1) return FUNC_CANNOT_CALC;
//统计元件面积
std::vector<int> vHist(nccomps);
for (int y = 0; y < Y; y++)
{
int *uPtr = (int *)m1.data + y * X;
for (int x = 0; x < X; x++, uPtr++) {
vHist[*uPtr]++;
}
}
//统计面积个数
std::map<int, int> cAreaMap;
for (const auto& v : vHist)
{
std::map<int, int>::iterator it = cAreaMap.find(v);
if (it != cAreaMap.end())
{
it->second++;
continue;
}
else { cAreaMap.insert(std::make_pair(v, 1)); };
}
struct tMap
{
int Key;
int Value;
tMap(int Key, int Value) :Key(Key), Value(Value) {}
bool operator >(const tMap &te)const
{
return Value > te.Value;
}
};
//获得单个元器件面积(准确性待测试,假定不粘连占大多数!)
std::vector<tMap> tVector;
std::map<int, int>::iterator it;
for (it = cAreaMap.begin(); it != cAreaMap.end(); it++)
{
tVector.push_back(tMap(it->first, it->second));
}
std::sort(tVector.begin(), tVector.end(), std::greater<tMap>());
if (tVector.size() < 2)
{
return FUNC_CANNOT_CALC;
}
//单个元件面积
int sinPartSize = cvRound((tVector[0].Key + tVector[1].Key) / 2.);
//采用追踪算法
nccomps = cv::connectedComponentsWithStats(binary, m1, m2, m3);
//连在一起
cv::Mat srcPrevEx0;
cv::morphologyEx(binary, srcPrevEx0, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(45, 45)));
//定位料盘中心
std::vector<std::vector<cv::Point>> contoursFilter;
cv::findContours(srcPrevEx0, contoursFilter, cv::RETR_TREE, cv::CHAIN_APPROX_NONE);
cv::Mat image = cv::Mat::zeros(src8U.size(), CV_8UC1);
//
for (int i = 0; i < contoursFilter.size(); i++)
{
cv::drawContours(image, contoursFilter, i, cv::Scalar(255), -1);
}
image -= srcPrevEx0;
//2021/08/26增加测试用
cv::morphologyEx(image, image, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(45, 45)));
//获取最大轮廓
cv::findContours(image, contoursFilter, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
if (contoursFilter.size() <= 0)
return FUNC_CANNOT_CALC;
std::vector<cv::Point> contourMax = contoursFilter[0];
for (int i = 1; i < contoursFilter.size(); i++)
{
if (cv::contourArea(contoursFilter[i]) > cv::contourArea(contourMax))
{
contourMax = contoursFilter[i];
}
}
//计算最大外接圆半径
float tFRadius = 0;
cv::minEnclosingCircle(contourMax, cv::Point2f(), tFRadius);
cv::Moments mu = cv::moments(contourMax);
cv::Point2f reelCenter(float(mu.m10 / mu.m00), float(mu.m01 / mu.m00));
//画中心
reelCenter.x = reelCenter.x > 0 && reelCenter.x < X ? reelCenter.x : 0;
reelCenter.y = reelCenter.y > 0 && reelCenter.y < Y ? reelCenter.y : 0;
cv::drawMarker(cc, reelCenter, cv::Scalar(0, 0, 238, 255), 1, 35, 2);
//包含未粘连器件
image = cv::Scalar(0);
std::vector<uchar> colors(nccomps + 1, 0);
for (int i = 1; i < nccomps; i++) {
colors[i] = 255;
if ((((int *)m2.data)[(cv::CC_STAT_AREA) + (i)*m2.cols] >= 1.5*sinPartSize) || (((int *)m2.data)[(cv::CC_STAT_AREA) + (i)*m2.cols] < 0.4*sinPartSize))//经验值
{
colors[i] = 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++)
{
int label = ((int *)m1.data)[(x)+(y)*m1.cols];
CV_Assert(0 <= label && label <= nccomps);
(image.data)[(x)+(y)*X] = colors[label];
}
}
});
//去掉中心1/3区域
cv::circle(image, reelCenter, cvRound(tFRadius / 3), cv::Scalar(0), -1);
//追踪锚点
struct TracingAnchor
{
float Size;
float Length, Height;
cv::Point2f Anchor;
cv::RotatedRect RBox;
TracingAnchor(cv::Point2f Anchor, float Length, float Height, float Size, cv::RotatedRect RBox) :Anchor(Anchor), Length(Length), Height(Height), Size(Size), RBox(RBox) {}
bool operator >(const TracingAnchor &te)const
{
return Size > te.Size;
}
bool operator <(const TracingAnchor &te)const
{
return Size < te.Size;
}
};
std::vector<std::vector<cv::Point>> contourTracing;
cv::findContours(image, contourTracing, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
//所有追踪锚点
std::vector<TracingAnchor> tracingAnchors;
for (auto&contour : contourTracing) {
cv::RotatedRect rbox = cv::minAreaRect(contour);
if (cv::min(rbox.size.width, rbox.size.height) > 2.0f) {
tracingAnchors.push_back(TracingAnchor(rbox.center, cv::max(rbox.size.width, rbox.size.height), cv::min(rbox.size.width, rbox.size.height), rbox.size.area(), rbox));
}
}
//不存在独立元件
if (tracingAnchors.empty()) {
return FUNC_CANNOT_CALC;
}
//尺寸只计算一次
std::sort(tracingAnchors.begin(), tracingAnchors.end(), std::greater<TracingAnchor>());
//
struct Track {
int iLimit, iPartSize;
double dMatchDeg = 0.0;
cv::Point2f Pos;
std::vector<cv::Point2f> Rect;
Track() {};
Track(int iLimit, int iPartSize, double dMatchDeg, cv::Point2f Pos, std::vector<cv::Point2f> Rect) :iLimit(iLimit), iPartSize(iPartSize), dMatchDeg(dMatchDeg), Pos(Pos), Rect(Rect) {};
bool operator >(const Track &te)const
{
return dMatchDeg > te.dMatchDeg;
}
bool operator <(const Track &te)const
{
return dMatchDeg < te.dMatchDeg;
}
};
//缩放比例
float coeff = 1.0f;
//填充值
const int fillVal = 255 - backThresh;
//元件尺寸
const double taLength = tracingAnchors[tracingAnchors.size() / 2].Length; const double taHeight = tracingAnchors[tracingAnchors.size() / 2].Height;
//元件灰度值
double taMaxGray = 0.0;
//标签图
unsigned char *ucpTrackLabel = new unsigned char[Y*X]();
cv::Mat trackMat(Y, X, CV_8UC1, ucpTrackLabel);
//计数图像
cv::Mat lbMat(Y, X, CV_8UC1, cv::Scalar(0));
//定位图像
cv::Mat srcPrevS, tplMat;//模板文件
srcPrev.convertTo(srcPrevS, CV_32F);
//随机打乱顺序(降低计算错误dChordL的可能性,也为了测试在起点信息不同时的稳定性)
std::random_shuffle(tracingAnchors.begin(), tracingAnchors.end());
//开始确定起点(现在是用圆轨迹来追踪,不排除用螺旋线轨迹来追踪)
for (std::vector<TracingAnchor>::iterator itvx = tracingAnchors.begin(); itvx != tracingAnchors.end(); ++itvx) {
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularParts 点料阶段被跳过执行...");
break;
}
//起始位置信息
TracingAnchor ta = (*itvx);
//起始位置坐标
cv::Point2f startCenter(ta.Anchor.x, ta.Anchor.y);
//最小外包矩形
cv::Point2f _pts[4];
ta.RBox.points(_pts);
//已做标记(TODO:考虑增加判断哪些是起点哪些不是)
if (trackMat.ptr<uint8_t>(cvRound(startCenter.y))[cvRound(startCenter.x)] == 255) {
continue;
}
//获取模板图像(是否每次起点都计算模板,如果元件变形过大是否还会有用?)
if (tplMat.empty())
{
float tDist = ta.Height / 2.0f;
//理论范围扩展
cv::Rect _rLimits = cv::Rect(cv::Point2i(cvRound((float)ta.RBox.boundingRect2f().tl().x - tDist),
cvRound((float)ta.RBox.boundingRect2f().tl().y - tDist)), cv::Point2i(cvRound((float)ta.RBox.boundingRect2f().br().x + tDist),
cvRound((float)ta.RBox.boundingRect2f().br().y + tDist))
)&cv::Rect(0, 0, X, Y);
//确定元件位置根据旋转后的位置确定(前提是料盘中心定位的准确)
double t = atan2((double)startCenter.y - reelCenter.y, (double)startCenter.x - reelCenter.x) * 180.0 / PI;
//计算旋转角度
cv::Mat traceMat = srcPrev(_rLimits);
//这里计算得出的模板不是很对,但是对于太小的元件最小外包矩形会不对
float matx[6];
tplMat = getTrackMat(traceMat, t + 90.0, 0, matx);
//变换后的坐标
cv::Point2f __pts[4];
for (int j = 0; j < 4; j++)
{
__pts[j].x = matx[0] * (_pts[j].x - (float)_rLimits.x) + matx[1] * (_pts[j].y - (float)_rLimits.y) + matx[2];
__pts[j].y = matx[3] * (_pts[j].x - (float)_rLimits.x) + matx[4] * (_pts[j].y - (float)_rLimits.y) + matx[5];
}
//中点
cv::Point2f __ptsc((__pts[0].x + __pts[1].x + __pts[2].x + __pts[3].x) / 4.0f, (__pts[0].y + __pts[1].y + __pts[2].y + __pts[3].y) / 4.0f);
//元件区域坐标
cv::Point2f __mpts[4];
__mpts[0].x = __ptsc.x - ta.Length / 2.0f; __mpts[0].y = __ptsc.y - ta.Height / 2.0f;
__mpts[1].x = __ptsc.x + ta.Length / 2.0f; __mpts[1].y = __ptsc.y - ta.Height / 2.0f;
__mpts[2].x = __ptsc.x - ta.Length / 2.0f; __mpts[2].y = __ptsc.y + ta.Height / 2.0f;
__mpts[3].x = __ptsc.x + ta.Length / 2.0f; __mpts[3].y = __ptsc.y + ta.Height / 2.0f;
//元件区域
cv::Rect _rr(cvFloor(std::min(std::min(std::min(__mpts[0].x, __mpts[1].x), __mpts[2].x), __mpts[3].x)),
cvFloor(std::min(std::min(std::min(__mpts[0].y, __mpts[1].y), __mpts[2].y), __mpts[3].y)),
cvCeil(std::max(std::max(std::max(__mpts[0].x, __mpts[1].x), __mpts[2].x), __mpts[3].x)),
cvCeil(std::max(std::max(std::max(__mpts[0].y, __mpts[1].y), __mpts[2].y), __mpts[3].y))); _rr.width -= _rr.x - 1; _rr.height -= _rr.y - 1;
//最终模板(可能由于太小,angle是错误的)
tplMat = tplMat(_rr).clone();
//缩放比例
if (MIN(tplMat.size().width, tplMat.size().height) < 12.0) {
coeff = 2.0f;
}
//最大值
cv::minMaxLoc(tplMat, NULL, &taMaxGray);
}
//标记为已追踪过
std::vector<cv::Point> vT = { cv::Point(_pts[0]),cv::Point(_pts[1]) ,cv::Point(_pts[2]) ,cv::Point(_pts[3]) };
cv::fillConvexPoly(trackMat, vT, cv::Scalar(255));
//标记计数
lbMat.ptr<uint8_t>(cvRound(startCenter.y))[cvRound(startCenter.x)] = 255;
//标记当前位置
cv::drawMarker(cc, cv::Point(startCenter), cv::Scalar(0, 255, 0, 255), cv::MARKER_DIAMOND, 5);
//扫描步长
const double dMinorStep = 0.1;
//追踪长宽
const double trackLength = taLength / 2.0, trackWidth = taHeight / 4.0;//是否用较小尺寸的窗口
//起始扫描角度
const double startAngle = atan2((double)startCenter.y - reelCenter.y, (double)startCenter.x - reelCenter.x) * 180.0 / PI;
//起始扫描半径
const double startRadius = cv::norm(startCenter - reelCenter);
//偏移角度(元件尺寸)
const double dOffset = (2.0 * asin(2.0 * trackLength / (2.0 * startRadius))) * 180.0 / PI;
//扫描角度(默认15度范围内存在元件)
const double dScanRange = 15.0;
//追踪元件间距(弦长,可以尽量避免因个别器件偏离导致的追踪中断)
double dChordL = .0;
for (double t = startAngle + dOffset / 1.5; t < startAngle + dScanRange; t += dMinorStep)
{
float x = float(reelCenter.x + startRadius*cos(t*c));
float y = float(reelCenter.y + startRadius*sin(t*c));
//防止超出图像范围
if (cvRound(x) < 0 || (cvRound(x) > X - 1) || cvRound(y) < 0 || (cvRound(y) > Y - 1)) {
break;
}
//确定是否是下一个元件
if (trackMat.ptr<uint8_t>(cvRound(y))[cvRound(x)] == 255) {
continue;
}
//初次确定元件间距
const double angle = atan2((double)reelCenter.y - y, (double)reelCenter.x - x);
cv::Point p1 = cv::Point(cvRound(x + trackWidth * cos(angle)),
cvRound(y + trackWidth * sin(angle)));
cv::Point p2 = cv::Point(cvRound(x + trackWidth * cos(angle + CV_PI)),
cvRound(y + trackWidth * sin(angle + CV_PI)));
#ifdef _DEBUG
cv::line(cc, p1, p2, cv::Scalar(0, 215, 255, 255), 1);
#endif
cv::LineIterator it(binary, p1, p2, 4);
for (int n = 0; n < it.count; n++, ++it)
{
if (binary.ptr<uint8_t>(it.pos().y)[it.pos().x] == 255)
{
//计算元件间距(弦长)
dChordL = 2.0 * startRadius*sin(((2.0 * asin((cv::norm(startCenter - cv::Point2f(x, y))) / (2.0 * startRadius))) * 180.0 / PI - dOffset / 2.0)*PI / 180.0 / 2.0);
break;
}
}
if (dChordL > 2.0)
break;
}
//没确定出元件间距一般为结尾处,继续从下一个起点计算弦长并开始追踪
if (dChordL <= 2.0) {
continue;
}
//顺时针(是否并行取决于在windows下运行还是树莓派上)
{
//追踪中心
cv::Point2f trackCenter = cv::Point2f(startCenter.x, startCenter.y);
//追踪角度、半径
double trackAngle = startAngle, trackRadius = startRadius;
//元件本身所占角度
double trackOffset = dOffset;
//元件间间距
double partDist = (2.0 * asin(dChordL / (2.0 * trackRadius))) * 180.0 / PI;
//开始追踪
bool trackEnd = true;
do
{
bool found = true; bool trayEnd = false;
std::vector<Track> vParts;
for (double t = trackAngle + (trackOffset + partDist - trackOffset / 12.0); t < trackAngle + (trackOffset + partDist - trackOffset / 12.0) + trackOffset / 6.0; t += dMinorStep)
{
cv::Point2f predicPos;
predicPos.x = reelCenter.x + (float)trackRadius*(float)cos((trackAngle + (trackOffset + partDist))*c);
predicPos.y = reelCenter.y + (float)trackRadius*(float)sin((trackAngle + (trackOffset + partDist))*c);
//如果追踪到图像外则追踪终止
if (cvRound(predicPos.x) < 0 || (cvRound(predicPos.x) > X - 1) || cvRound(predicPos.y) < 0 || (cvRound(predicPos.y) > Y - 1)) {
trayEnd = true;
break;
}
//感兴趣区域(向外扩展了一个元件,防止中心定位出现偏差或者料盘本身变形导致的偏差)
cv::Point2f predictBox[4];
calcRotateRect(predicPos, (float)(trackAngle + (trackOffset + partDist)), (float)trackLength + (float)trackLength, (float)trackWidth + (float)trackWidth, predictBox);
cv::RotatedRect r(predictBox[0], predictBox[1], predictBox[2]);
cv::Rect rLimits = r.boundingRect()&cv::Rect(0, 0, X, Y);
//获取感兴趣区域
float matx[6];
cv::Mat traceMat = getTrackMat(srcPrevS(rLimits).clone()
, (trackAngle + (trackOffset + partDist)) + 90.0, fillVal, matx);
//计算原图中的点在旋转后的位置(即在traceMat中的精确位置)
cv::Point2f predictBoxR[4];
for (int j = 0; j < 4; j++)
{
predictBoxR[j].x = matx[0] * (predictBox[j].x - (float)rLimits.x) + matx[1] * (predictBox[j].y - (float)rLimits.y) + matx[2];
predictBoxR[j].y = matx[3] * (predictBox[j].x - (float)rLimits.x) + matx[4] * (predictBox[j].y - (float)rLimits.y) + matx[5];
}
//中点
cv::Point2f predicPosR((predictBoxR[0].x + predictBoxR[1].x + predictBoxR[2].x + predictBoxR[3].x) / 4.0f,
(predictBoxR[0].y + predictBoxR[1].y + predictBoxR[2].y + predictBoxR[3].y) / 4.0f);
//理论区域
cv::Rect tRec = cv::Rect(cv::Point(cvRound((predicPosR.x*2.0f - (float)trackLength*2.0f) / 2.0f),
cvRound((predicPosR.y*2.0f - (float)trackWidth*4.0f) / 2.0f)),
cv::Size(cvRound(trackLength*2.0), cvRound(trackWidth*4.0)))
&cv::Rect(0, 0, traceMat.cols, traceMat.rows);
//高精度理论区域
cv::Rect_<float> tRecF = cv::Rect_<float>(cv::Point2f((predicPosR.x*2.0f - (float)trackLength*2.0f) / 2.0f,
(predicPosR.y*2.0f - (float)trackWidth*4.0f) / 2.0f),
cv::Size2f((float)trackLength*2.0f, (float)trackWidth*4.0f))
&cv::Rect_<float>(0.0f, 0.0f, (float)traceMat.cols, (float)traceMat.rows);
//理论区域向外扩展(即predictBox范围)
cv::Rect rr = cv::Rect(cv::Point(cvRound((double)predicPosR.x - trackLength*2.0),
cvRound((double)predicPosR.y - trackWidth*4.0)), cv::Size(cvRound(trackLength*2.0*2.0),
cvRound(trackWidth*4.0*2.0)))&cv::Rect(0, 0, traceMat.cols, traceMat.rows);
cv::Rect_<float> rrf = cv::Rect2f(cv::Point2f((predicPosR.x*2.0f - (float)trackLength*4.0f) / 2.0f,
(predicPosR.y*2.0f - (float)trackWidth*8.0f) / 2.0f), cv::Size2f((float)trackLength*4.0f, (float)trackWidth*8.0f))
&cv::Rect2f(0.0f, 0.0f, (float)traceMat.cols, (float)traceMat.rows);
//元件尺寸太小放大N倍处理,这样坐标会精细些,考虑元件的80%尺寸作为kernel,防止元件尺寸变化太大
cv::Mat kernel = cv::Mat::ones(cv::Size(cv::max(cvRound((float)(trackLength*2.0) * coeff),
cvRound((float)(trackWidth*4.0) * coeff)), cv::min(cvRound((float)(trackLength*2.0) * coeff),
cvRound((float)(trackWidth*4.0) * coeff))), CV_32FC1);
cv::Mat _traceMat = traceMat.clone();
//放大
if (coeff > 1.0f) {
cv::resize(_traceMat, _traceMat, cv::Size(cvRound(traceMat.size().width * coeff), cvRound(traceMat.size().height * coeff)));
}
//计算最大值(当_traceMat尺寸小于kernel会报错)
cv::Mat dst;
cv::filter2D(_traceMat, dst, CV_32F, kernel);
//归一化
cv::Mat mmRescaling;
cv::normalize(dst, mmRescaling, 1.0, 0.0, cv::NORM_MINMAX);
//模板匹配做辅助判断,为了尽量避免定位出错
cv::Mat _tplMat;
tplMat.convertTo(_tplMat, CV_32FC1);
if (coeff > 1.0f) {
cv::resize(_tplMat, _tplMat, cv::Size(), coeff, coeff);
}
//防止报错
if (_tplMat.cols > _traceMat.cols || _tplMat.rows > _traceMat.rows) {
return FUNC_CANNOT_CALC;
}
//考虑并行计算两个模板结果
cv::Mat tplResult0;
cv::matchTemplate(_traceMat, _tplMat, tplResult0, cv::TM_SQDIFF_NORMED);
int modx = _tplMat.cols % 2, mody = _tplMat.rows % 2;
cv::Mat tplResultMap;
cv::copyMakeBorder(tplResult0, tplResultMap, (_tplMat.rows - mody) / 2, _traceMat.rows - tplResult0.rows - (_tplMat.rows - mody) / 2,
(_tplMat.cols - modx) / 2, _traceMat.cols - tplResult0.cols - (_tplMat.cols - modx) / 2, cv::BORDER_REPLICATE);
//减去模板匹配的结果
mmRescaling -= tplResultMap;
//非极大值抑制
cv::Mat mask;
cv::dilate(mmRescaling, mask, cv::Mat());
cv::compare(mmRescaling, mask, mask, cv::CMP_GE);
cv::Mat non_plateau_mask;
cv::erode(mmRescaling, non_plateau_mask, cv::Mat());
cv::compare(mmRescaling, non_plateau_mask, non_plateau_mask, cv::CMP_GT);
cv::bitwise_and(mask, non_plateau_mask, mask);
//去掉分数过低的
mask &= cv::Mat(mmRescaling > 0.36);
//限定区域(mmRescaling范围内)
cv::Rect _rr = cv::Rect(cvRound(rr.x*coeff), cvRound(rr.y*coeff), cvRound(rr.width*coeff), cvRound(rr.height*coeff));
//候选元件位置
std::vector<cv::Point> candidates;
cv::findNonZero(mask(_rr), candidates);
//过滤
std::vector<Track> _vParts;
for (auto&candidate : candidates) {
cv::Point pt(candidate.x + _rr.x, candidate.y + _rr.y);
float confidence = mmRescaling.ptr<float>(pt.y)[pt.x];
if (confidence > 0.5f) {
_vParts.push_back(Track(0, 0, confidence, cv::Point2f((float)pt.x, (float)pt.y), std::vector<cv::Point2f>()));
}
}
//目标元件在小图中的位置
cv::Point2f maxLox;
//元件位置判断
if (_vParts.size() <= 0) {
//大概率终止
trayEnd = true;
}
else if (_vParts.size() == 1) {
//有可能会出错
maxLox = cv::Point2f(_vParts[0].Pos.x / coeff, _vParts[0].Pos.y / coeff);
if (tRecF.contains(maxLox)) {
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle + (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
}
else {
//这里负责处理意外情况(极大可能是元件偏离过多或者料盘中心定位不准确导致的),
//采用距离理论位置最近的点(两种方式都失效的概率比较低,如果真的失效那就听天由命吧)
cv::Mat _mmRescaling, _tplResultMap;
_mmRescaling = mmRescaling.clone(); _tplResultMap = tplResultMap.clone();
//累加的方式
double maxVal; cv::Point maxLoc;
cv::minMaxLoc(_mmRescaling(_rr), NULL, &maxVal, NULL, &maxLoc);
maxLoc += _rr.tl();
//模板匹配的方式
double minVal; cv::Point minLoc;
cv::minMaxLoc(_tplResultMap(_rr), &minVal, NULL, &minLoc, NULL);
minLoc += _rr.tl();
std::vector<Track> __vParts;
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)maxLoc.x, (float)maxLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)maxLoc.x, (float)maxLoc.y), std::vector<cv::Point2f>()));
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)minLoc.x, (float)minLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)minLoc.x, (float)minLoc.y), std::vector<cv::Point2f>()));
//排序
std::sort(__vParts.begin(), __vParts.end(), std::less<Track>());
//在小图中的位置
maxLox = cv::Point2f(__vParts[0].Pos.x / coeff, __vParts[0].Pos.y / coeff);
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle + (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
#ifdef _DEBUG
for (int j = 0; j < 4; j++)
{
cv::line(cc, predictBox[j], predictBox[(j + 1) % 4], cv::Scalar(0, 0, 255, 255), 1);
}
#endif
}
}
else {
//存在多个峰值,先判断分数最高是否位于理论位置
std::sort(_vParts.begin(), _vParts.end(), std::greater<Track>());
for (auto&_vPart : _vParts) {
maxLox = cv::Point2f(_vPart.Pos.x / coeff, _vPart.Pos.y / coeff);
if (tRecF.contains(maxLox)) {
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle + (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
break;
}
}
//如果不在则选取距离理论位置最近的
if (vParts.empty()) {
//这里负责处理意外情况(极大可能是元件偏离过多或者中心定位不准确)
//,采用距离理论位置最近的点(两种方式都失效的概率比较低)
cv::Mat _mmRescaling, _tplResultMap;
_mmRescaling = mmRescaling.clone(); _tplResultMap = tplResultMap.clone();
//累加的方式
double maxVal; cv::Point maxLoc;
cv::minMaxLoc(_mmRescaling(_rr), NULL, &maxVal, NULL, &maxLoc);
maxLoc += _rr.tl();
//模板匹配的方式
double minVal; cv::Point minLoc;
cv::minMaxLoc(_tplResultMap(_rr), &minVal, NULL, &minLoc, NULL);
minLoc += _rr.tl();
std::vector<Track> __vParts;
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)maxLoc.x, (float)maxLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)maxLoc.x, (float)maxLoc.y), std::vector<cv::Point2f>()));
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)minLoc.x, (float)minLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)minLoc.x, (float)minLoc.y), std::vector<cv::Point2f>()));
//排序
std::sort(__vParts.begin(), __vParts.end(), std::less<Track>());
//在小图中的位置
maxLox = cv::Point2f(__vParts[0].Pos.x / coeff, __vParts[0].Pos.y / coeff);
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle + (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
#ifdef _DEBUG
for (int j = 0; j < 4; j++)
{
cv::line(cc, predictBox[j], predictBox[(j + 1) % 4], cv::Scalar(0, 0, 255, 255), 1);
}
#endif
}
}
if (!vParts.empty()) {
cv::Rect tRec_ = cv::Rect(cv::Point(cvFloor((((float)maxLox.x)*2.0f - (float)trackLength*2.0f) / 2.0f),
cvFloor((((float)maxLox.y)*2.0f - (float)trackWidth*4.0f) / 2.0f)),
cv::Size(cvRound(trackLength*2.0) + 2, cvRound(trackWidth*4.0) + 2))
&cv::Rect(0, 0, traceMat.cols, traceMat.rows);
//当作一种辅助手段,无需设置太严格
double dmax;
cv::minMaxLoc(traceMat(tRec_).clone(), NULL, &dmax);
if (dmax < 0.65*taMaxGray) {
trayEnd = true;
}
}
break;
}
//追踪终止,选取下一个起点
if (trayEnd) {
break;
}
//更新位置
trackCenter = cv::Point2f(vParts[0].Pos.x, vParts[0].Pos.y);
//更新扫描半径
trackRadius = cv::norm(trackCenter - reelCenter);
//更新扫描角度
trackAngle = atan2((double)trackCenter.y - (double)reelCenter.y, (double)trackCenter.x - (double)reelCenter.x) * 180.0 / PI;
//更新偏移量(元件角度大小)
trackOffset = (2 * asin(2 * trackLength / (2 * trackRadius))) * 180.0 / PI;
//更新元件间角度
partDist = (2 * asin(dChordL / (2 * trackRadius))) * 180.0 / PI;
//追踪到了重复的元件
if ((trackCenter.x<0 || trackCenter.x>X - 1 ||
trackCenter.y<0 || trackCenter.y>Y - 1) || trackMat.ptr<uint8_t>(cvRound(trackCenter.y))[cvRound(trackCenter.x)] == 255) {
found = false;
}
else {
//计算元件位置
cv::Point2f pts[4];
calcRotateRect(trackCenter, (float)trackAngle, (float)trackLength, (float)trackWidth, pts);
//标记计数
lbMat.ptr<uint8_t>(cvRound(trackCenter.y))[cvRound(trackCenter.x)] = 255;
//标记为已追踪过
std::vector<cv::Point> vT = { cv::Point(pts[0]),cv::Point(pts[1]) ,cv::Point(pts[2]) ,cv::Point(pts[3]) };
cv::fillConvexPoly(trackMat, vT, cv::Scalar(255));
//用于显示
cv::circle(cc, trackCenter, 2, cv::Scalar(0, 255, 0, 255), 1);
#ifdef _DEBUG
for (int j = 0; j < 4; j++)
{
cv::line(cc, pts[j], pts[(j + 1) % 4], cv::Scalar(14, 173, 238, 255), 1);
}
#endif
}
//清空下一个
vParts.resize(0);
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularPartsE 追踪阶段被跳过执行...");
found = false;
}
trackEnd = (!found);
} while (!trackEnd);
}
//逆时针
{
//追踪起点
cv::Point2f trackCenter(startCenter.x, startCenter.y);
//追踪角度、半径
double trackAngle = startAngle, trackRadius = startRadius;
//元件本身角度
double trackOffset = dOffset;
//元件间间距
double partDist = (2.0 * asin(dChordL / (2.0 * trackRadius))) * 180.0 / PI;
//开始追踪
bool trackEnd = true;
//
do
{
bool found = true; bool trayEnd = false;
std::vector<Track> vParts;
for (double t = trackAngle - (trackOffset + partDist - trackOffset / 12.0); t > trackAngle - (trackOffset + partDist - trackOffset / 12.0) - trackOffset / 6.0; t -= dMinorStep)
{
cv::Point2f predicPos;
predicPos.x = reelCenter.x + (float)trackRadius*(float)cos((trackAngle - (trackOffset + partDist))*c);
predicPos.y = reelCenter.y + (float)trackRadius*(float)sin((trackAngle - (trackOffset + partDist))*c);
//如果追踪到图像外追踪终止
if (cvRound(predicPos.x) < 0 || (cvRound(predicPos.x) > X - 1) || cvRound(predicPos.y) < 0 || (cvRound(predicPos.y) > Y - 1)) {
trayEnd = true;
break;
}
//感兴趣区域(向外扩展了一个元件,防止中心定位出现偏差或者料盘本身变形导致的偏差)
cv::Point2f predicBox[4];
calcRotateRect(predicPos, (float)(trackAngle - (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, predicBox);
cv::RotatedRect r(predicBox[0], predicBox[1], predicBox[2]);
cv::Rect rLimits = r.boundingRect()&cv::Rect(0, 0, X, Y);
//获取感兴趣区域
float matx[6];
cv::Mat traceMat = getTrackMat(srcPrevS(rLimits).clone()
, (trackAngle - (trackOffset + partDist)) + 90.0, fillVal, matx);
//计算原图中的点在旋转后的位置(即在traceMat中的精确位置)
cv::Point2f predictBoxR[4];
for (int j = 0; j < 4; j++)
{
predictBoxR[j].x = matx[0] * (predicBox[j].x - (float)rLimits.x) + matx[1] * (predicBox[j].y - (float)rLimits.y) + matx[2];
predictBoxR[j].y = matx[3] * (predicBox[j].x - (float)rLimits.x) + matx[4] * (predicBox[j].y - (float)rLimits.y) + matx[5];
}
//中点
cv::Point2f predicPosR((predictBoxR[0].x + predictBoxR[1].x + predictBoxR[2].x + predictBoxR[3].x) / 4.0f,
(predictBoxR[0].y + predictBoxR[1].y + predictBoxR[2].y + predictBoxR[3].y) / 4.0f);
//理论区域
cv::Rect tRec = cv::Rect(cv::Point(cvRound((predicPosR.x*2.0f - (float)trackLength*2.0f) / 2.0f),
cvRound((predicPosR.y*2.0f - (float)trackWidth*4.0f) / 2.0f)),
cv::Size(cvRound(trackLength*2.0), cvRound(trackWidth*4.0)))
&cv::Rect(0, 0, traceMat.cols, traceMat.rows);
//高精度理论区域
cv::Rect_<float> tRecF = cv::Rect_<float>(cv::Point2f((predicPosR.x*2.0f - (float)trackLength*2.0f) / 2.0f,
(predicPosR.y*2.0f - (float)trackWidth*4.0f) / 2.0f),
cv::Size2f((float)trackLength*2.0f, (float)trackWidth*4.0f))
&cv::Rect_<float>(0.0f, 0.0f, (float)traceMat.cols, (float)traceMat.rows);
//理论区域向外扩展(即predictBox范围)
cv::Rect rr = cv::Rect(cv::Point(cvRound((double)predicPosR.x - trackLength*2.0),
cvRound((double)predicPosR.y - trackWidth*4.0)), cv::Size(cvRound(trackLength*2.0*2.0),
cvRound(trackWidth*4.0*2.0)))&cv::Rect(0, 0, traceMat.cols, traceMat.rows);
cv::Rect_<float> rrf = cv::Rect2f(cv::Point2f((predicPosR.x*2.0f - (float)trackLength*4.0f) / 2.0f,
(predicPosR.y*2.0f - (float)trackWidth*8.0f) / 2.0f), cv::Size2f((float)trackLength*4.0f, (float)trackWidth*8.0f))
&cv::Rect2f(0.0f, 0.0f, (float)traceMat.cols, (float)traceMat.rows);
//元件尺寸太小放大N倍处理,这样坐标会精细些,元件的80%尺寸作为kernel,防止元件尺寸变化太大
cv::Mat kernel = cv::Mat::ones(cv::Size(cv::max(cvRound((float)(trackLength*2.0) * coeff),
cvRound((float)(trackWidth*4.0) * coeff)), cv::min(cvRound((float)(trackLength*2.0) * coeff),
cvRound((float)(trackWidth*4.0) * coeff))), CV_32FC1);
cv::Mat _traceMat = traceMat.clone();
//放大
if (coeff > 1.0f) {
cv::resize(_traceMat, _traceMat, cv::Size(cvRound(traceMat.size().width * coeff), cvRound(traceMat.size().height * coeff)));
}
//计算最大值(当_traceMat尺寸小于kernel会报错)
cv::Mat dst;
cv::filter2D(_traceMat, dst, CV_32F, kernel);
//归一化
cv::Mat mmRescaling;
cv::normalize(dst, mmRescaling, 1.0, 0.0, cv::NORM_MINMAX);
//模板匹配,为了尽量避免定位出错
cv::Mat _tplMat;
tplMat.convertTo(_tplMat, CV_32FC1);
if (coeff > 1.0f) {
cv::resize(_tplMat, _tplMat, cv::Size(), coeff, coeff);
}
//防止报错
if (_tplMat.cols > _traceMat.cols || _tplMat.rows > _traceMat.rows) {
return FUNC_CANNOT_CALC;
}
//考虑并行计算两个模板结果
cv::Mat tplResult0;
cv::matchTemplate(_traceMat, _tplMat, tplResult0, cv::TM_SQDIFF_NORMED);
int modx = _tplMat.cols % 2, mody = _tplMat.rows % 2;
cv::Mat tplResultMap;
cv::copyMakeBorder(tplResult0, tplResultMap, (_tplMat.rows - mody) / 2, _traceMat.rows - tplResult0.rows - (_tplMat.rows - mody) / 2,
(_tplMat.cols - modx) / 2, _traceMat.cols - tplResult0.cols - (_tplMat.cols - modx) / 2, cv::BORDER_REPLICATE);
//减去模板匹配的结果
mmRescaling -= tplResultMap;
//非极大值抑制
cv::Mat mask;
cv::dilate(mmRescaling, mask, cv::Mat());
cv::compare(mmRescaling, mask, mask, cv::CMP_GE);
cv::Mat non_plateau_mask;
cv::erode(mmRescaling, non_plateau_mask, cv::Mat());
cv::compare(mmRescaling, non_plateau_mask, non_plateau_mask, cv::CMP_GT);
cv::bitwise_and(mask, non_plateau_mask, mask);
//去掉分数过低的
mask &= cv::Mat(mmRescaling > 0.36);
//限定区域(mmRescaling范围内)
cv::Rect _rr = cv::Rect(cvRound(rr.x*coeff), cvRound(rr.y*coeff), cvRound(rr.width*coeff), cvRound(rr.height*coeff));
//候选元件位置
std::vector<cv::Point> candidates;
cv::findNonZero(mask(_rr), candidates);
//过滤
std::vector<Track> _vParts;
for (auto&candidate : candidates) {
cv::Point pt(candidate.x + _rr.x, candidate.y + _rr.y);
float confidence = mmRescaling.ptr<float>(pt.y)[pt.x];
if (confidence > 0.5f) {
_vParts.push_back(Track(0, 0, confidence, cv::Point2f((float)pt.x, (float)pt.y), std::vector<cv::Point2f>()));
}
}
//目标元件在小图中的位置
cv::Point2f maxLox;
//元件位置判断
if (_vParts.size() <= 0) {
//大概率终止
trayEnd = true;
}
else if (_vParts.size() == 1) {
maxLox = cv::Point2f(_vParts[0].Pos.x / coeff, _vParts[0].Pos.y / coeff);
//有可能会出错,当靠的太近可能只存在一个峰值
if (tRecF.contains(maxLox)) {
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle + (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
}
else {
//这里负责处理意外情况(极大可能是元件偏离过多或者中心定位不准确),采用距离理论位置最近的点(两种方式都失效的概率比较低)
cv::Mat _mmRescaling, _tplResultMap;
_mmRescaling = mmRescaling.clone(); _tplResultMap = tplResultMap.clone();
//累加的方式
double maxVal; cv::Point maxLoc;
cv::minMaxLoc(_mmRescaling(_rr), NULL, &maxVal, NULL, &maxLoc);
maxLoc += _rr.tl();
//模板匹配的方式
double minVal; cv::Point minLoc;
cv::minMaxLoc(_tplResultMap(_rr), &minVal, NULL, &minLoc, NULL);
minLoc += _rr.tl();
std::vector<Track> __vParts;
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)maxLoc.x, (float)maxLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)maxLoc.x, (float)maxLoc.y), std::vector<cv::Point2f>()));
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)minLoc.x, (float)minLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)minLoc.x, (float)minLoc.y), std::vector<cv::Point2f>()));
//排序
std::sort(__vParts.begin(), __vParts.end(), std::less<Track>());
//小图中的定位坐标
maxLox = cv::Point2f(__vParts[0].Pos.x / coeff, __vParts[0].Pos.y / coeff);
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle - (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
#ifdef _DEBUG
for (int j = 0; j < 4; j++)
{
cv::line(cc, predicBox[j], predicBox[(j + 1) % 4], cv::Scalar(0, 0, 238, 255), 1);
}
#endif
}
}
else {
//存在定位出错的可能性,先判断分数最高是否位于理论位置
std::sort(_vParts.begin(), _vParts.end(), std::greater<Track>());
for (auto&_vPart : _vParts) {
maxLox = cv::Point2f(_vPart.Pos.x / coeff, _vPart.Pos.y / coeff);
if (tRecF.contains(maxLox)) {
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle - (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
break;
}
}
//如果不在则选取距离理论位置最近的
if (vParts.empty()) {
//这里负责处理意外情况(极大可能是元件偏离过多或者中心定位不准确),采用距离理论位置最近的点(两种方式都失效的概率比较低)
cv::Mat _mmRescaling, _tplResultMap;
_mmRescaling = mmRescaling.clone(); _tplResultMap = tplResultMap.clone();
//累加的方式
double maxVal; cv::Point maxLoc;
cv::minMaxLoc(_mmRescaling(_rr), NULL, &maxVal, NULL, &maxLoc);
maxLoc += _rr.tl();
//模板匹配的方式
double minVal; cv::Point minLoc;
cv::minMaxLoc(_tplResultMap(_rr), &minVal, NULL, &minLoc, NULL);
minLoc += _rr.tl();
std::vector<Track> __vParts;
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)maxLoc.x, (float)maxLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)maxLoc.x, (float)maxLoc.y), std::vector<cv::Point2f>()));
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)minLoc.x, (float)minLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)minLoc.x, (float)minLoc.y), std::vector<cv::Point2f>()));
//排序
std::sort(__vParts.begin(), __vParts.end(), std::less<Track>());
//小图中的位置
maxLox = cv::Point2f(__vParts[0].Pos.x / coeff, __vParts[0].Pos.y / coeff);
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle - (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
#ifdef _DEBUG
for (int j = 0; j < 4; j++)
{
cv::line(cc, predicBox[j], predicBox[(j + 1) % 4], cv::Scalar(0, 0, 238, 255), 1);
}
#endif
}
}
if (!vParts.empty()) {
cv::Rect tRec_ = cv::Rect(cv::Point(cvFloor((((float)maxLox.x)*2.0f - (float)trackLength*2.0f) / 2.0f),
cvFloor((((float)maxLox.y)*2.0f - (float)trackWidth*4.0f) / 2.0f)),
cv::Size(cvRound(trackLength*2.0) + 2, cvRound(trackWidth*4.0) + 2))
&cv::Rect(0, 0, traceMat.cols, traceMat.rows);
//当作一种辅助手段,无需设置太严格
double dmax;
cv::minMaxLoc(traceMat(tRec_).clone(), NULL, &dmax);
if (dmax < 0.65*taMaxGray) {
trayEnd = true;
}
}
break;
}
//接着下一个起点
if (trayEnd) {
break;
}
//更新位置
trackCenter = cv::Point2f(vParts[0].Pos.x, vParts[0].Pos.y);
//更新扫描半径
trackRadius = cv::norm(trackCenter - reelCenter);
//更新扫描角度
trackAngle = atan2((double)trackCenter.y - (double)reelCenter.y, (double)trackCenter.x - (double)reelCenter.x) * 180.0 / PI;
//更新偏移量(元件角度大小)
trackOffset = (2.0 * asin(2.0 * trackLength / (2.0 * trackRadius))) * 180.0 / PI;
//更新元件间角度
partDist = (2.0 * asin(dChordL / (2.0 * trackRadius))) * 180.0 / PI;
//追踪到了重复的元件
if ((trackCenter.x<0 || trackCenter.x>X - 1 ||
trackCenter.y<0 || trackCenter.y>Y - 1) || trackMat.ptr<uint8_t>(cvRound(trackCenter.y))[cvRound(trackCenter.x)] == 255) {
found = false;
}
else {
//计算元件位置
cv::Point2f pts[4];
calcRotateRect(trackCenter, (float)trackAngle, (float)trackLength, (float)trackWidth, pts);
//标记计数
lbMat.ptr<uint8_t>(cvRound(trackCenter.y))[cvRound(trackCenter.x)] = 255;
//标记为已追踪过
std::vector<cv::Point> vT = { cv::Point(pts[0]),cv::Point(pts[1]) ,cv::Point(pts[2]) ,cv::Point(pts[3]) };
cv::fillConvexPoly(trackMat, vT, cv::Scalar(255));
//用于显示
cv::circle(cc, trackCenter, 2, cv::Scalar(0, 255, 0, 255), 1);
#ifdef _DEBUG
for (int j = 0; j < 4; j++)
{
cv::line(cc, pts[j], pts[(j + 1) % 4], cv::Scalar(102, 205, 0, 255), 1);
}
#endif
}
//继续下一个起点
vParts.resize(0);
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularParts 追踪阶段被跳过执行...");
found = false;
}
trackEnd = (!found);
} while (!trackEnd);
}
}
//拷贝计数
binary = lbMat.clone();
//释放资源
delete[] ucpTrackLabel;
ucpTrackLabel = NULL;
}
else if (strcmp(ccSubType, "IP_SQUARE_PARTS") == 0)
{
//测试用,对于个别元件需要稍微膨胀一下
cv::morphologyEx(srcPrev, srcPrev, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(2, 2)));
//二值化
cv::threshold(srcPrev, binary, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
cv::morphologyEx(binary, binary, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(75, 75)));
//计算直方图
int hist_[256];
for (int y = 0; y < 256; y++) hist_[y] = 0;
for (int y = 0; y < Y; y++)
{
uchar *uPtr = srcPrev.data + y * X;
for (int x = 0; x < srcPrev.cols; x++, uPtr++) {
if (binary.ptr<uint8_t>(y)[x] == 255) {
hist_[*uPtr]++;
}
}
}
cv::threshold(srcPrev, binary, Otsu(hist_), 255, cv::THRESH_BINARY);
//计算元件大小
cv::Mat m1, m2, m3;
int nccomps = cv::connectedComponentsWithStats(binary, m1, m2, m3);
std::vector<uchar> colors0(nccomps + 1, 0);
for (int i = 1; i < nccomps; i++) {
colors0[i] = 255;
if ((((int *)m2.data)[(cv::CC_STAT_AREA) + (i)*m2.cols] <= 21) || m2.ptr<int>(i)[cv::CC_STAT_WIDTH] * m2.ptr<int>(i)[cv::CC_STAT_HEIGHT] > 400000)//经验值
{
colors0[i] = 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++) {
int label = ((int *)m1.data)[(x)+(y)*m1.cols];
CV_Assert(0 <= label && label <= nccomps);
(binary.data)[(x)+(y)*X] = colors0[label];
}
}
});
nccomps = cv::connectedComponentsWithStats(binary, m1, m2, m3);
//
if (nccomps <= 1) return FUNC_CANNOT_CALC;
//统计元件面积
std::vector<int> vHist(nccomps);
for (int y = 0; y < Y; y++)
{
int *uPtr = (int *)m1.data + y * X;
for (int x = 0; x < X; x++, uPtr++) {
vHist[*uPtr]++;
}
}
//统计面积个数
std::map<int, int> cAreaMap;
for (const auto& v : vHist)
{
std::map<int, int>::iterator it = cAreaMap.find(v);
if (it != cAreaMap.end())
{
it->second++;
continue;
}
else { cAreaMap.insert(std::make_pair(v, 1)); };
}
struct tMap
{
int Key;
int Value;
tMap(int Key, int Value) :Key(Key), Value(Value) {}
bool operator >(const tMap &te)const
{
return Value > te.Value;
}
};
//获得单个元器件面积(准确性待测试,假定不粘连占大多数!)
std::vector<tMap> tVector;
std::map<int, int>::iterator it;
for (it = cAreaMap.begin(); it != cAreaMap.end(); it++)
{
tVector.push_back(tMap(it->first, it->second));
}
std::sort(tVector.begin(), tVector.end(), std::greater<tMap>());
if (tVector.size() < 2)
{
return false;
}
//单个元件面积
int sinPartSize = cvRound((tVector[0].Key + tVector[1].Key) / 2.);
std::vector<uchar> colors(nccomps + 1, 0);
for (int i = 1; i < nccomps; i++) {
colors[i] = 255;
if ((((int *)m2.data)[(cv::CC_STAT_AREA) + (i)*m2.cols] >= 1.35*sinPartSize) || (((int *)m2.data)[(cv::CC_STAT_AREA) + (i)*m2.cols] < 0.45*sinPartSize))//经验值
{
colors[i] = 0;
}
}
std::vector<int> trayCount(nccomps + 1, 0);
Palete pal;
unsigned int colorCount = 0;
for (int i = 1; i < nccomps; i++)
{
colorCount = cvRound((float)m2.ptr<int>(i)[cv::CC_STAT_AREA] / (float)sinPartSize);
CvLabel _label = i;
double r, g, b;
if (!colors[_label] == 0) {
_HSV2RGB_((double)((colorCount * 77) % 360), 1., 1., r, g, b);
}
else {
_HSV2RGB_((double)(((colorCount + 2) * 77) % 360), 1., .5, r, g, b);
}
pal[_label] = CV_RGB(r, g, b);
trayCount[_label] = colorCount;
}
//认为是粘连
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++) {
int label = ((int *)m1.data)[(x)+(y)*m1.cols];
CV_Assert(0 <= label && label <= nccomps);
if (binary.ptr<uint8_t>(y)[x]) {
cc.ptr<cv::Vec4b>(y)[x] = cv::Vec4b((uchar)pal[label].val[0], (uchar)pal[label].val[1], (uchar)pal[label].val[2], 255);
}
binary.ptr<uint8_t>(y)[x] = colors[label];
}
}
});
for (int i = 1; i < nccomps; i++)
{
CvLabel _label = i;
if (trayCount[_label] != 1) {
cv::putText(cc, std::to_string(trayCount[_label]), cv::Point(cvRound(m3.ptr<double>(i)[0]), cvRound(m3.ptr<double>(i)[1])),
cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(0, 0, 255, 255), 1);
}
}
//计数
int totalCount = std::accumulate(trayCount.begin(), trayCount.end(), 0);
//画图显示
std::string text = "Reel Number = " + std::to_string(totalCount);
cv::putText(cc, text, cv::Point(35, 35), 0, 1.0, cv::Scalar(0, 140, 255, 255), 2);
//标记
binary = cv::Scalar(0);
for (int t = 0; t < totalCount; t++) {
binary.ptr<uint8_t>(0)[t] = 255;
}
}
else if (strcmp(ccSubType, "IP_DYNAMIC_PARTS") == 0)
{
double threshold = getThreshVal_Otsu_8u(srcPrev);
//二值化
cv::threshold(srcPrev, binary, threshold + 25, 255, cv::THRESH_BINARY);
//去掉一些干扰
cv::morphologyEx(binary, binary, cv::MORPH_OPEN, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(2, 2)));
cv::Mat labels, stats, centroids;
int nccomps = cv::connectedComponentsWithStats(binary, labels, stats, centroids);
//计算大概面积
cv::Mat statsArea = stats(cv::Range(1, stats.rows), cv::Range(4, 5)).clone();
cv::sort(statsArea, statsArea, cv::SortFlags::SORT_EVERY_COLUMN);
int meanArea = statsArea.ptr<uint32_t>(cvRound(statsArea.rows / 2))[0];
//过滤连通域面积<=maxVal的
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] < meanArea / 4) || (stats.ptr<int>(i)[cv::CC_STAT_AREA] > 4 * meanArea))
{
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::Mat distMap;
cv::distanceTransform(binary, distMap, cv::DIST_L2, 3);
cv::normalize(distMap, distMap, 1, 0, cv::NORM_MINMAX);
distMap.convertTo(distMap, CV_8UC1, 255);
//二值化
cv::threshold(distMap, binary, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
//计算大概区域
cv::Mat mask;
cv::morphologyEx(binary, mask, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(45, 45)));
std::vector<std::vector<cv::Point>> contours;
cv::findContours(mask, contours, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE);
if (contours.empty()) {
return FUNC_CANNOT_CALC;
}
cv::Mat image(Y, X, CV_8UC1, cv::Scalar(0));
for (int n = 0; n < contours.size(); n++) {
cv::drawContours(image, contours, n, cv::Scalar(255), -1);
}
//寻找最大轮廓
std::vector<cv::Point> contourMax; double contourMaxArea = 0; cv::Point2f center; float radius;
contourMax = contours[0]; contourMaxArea = cv::contourArea(contourMax);
for (int i = 1; i < contours.size(); i++)
{
double contourArea = cv::contourArea(contours[i]);
if (contourArea > contourMaxArea)
{
contourMax = contours[i];
contourMaxArea = contourArea;
}
}
//去除外部干扰
cv::minEnclosingCircle(contourMax, center, radius);
cv::Mat maskOut(Y, X, CV_8UC1, cv::Scalar(0));
cv::circle(maskOut, center, cvRound(radius), cv::Scalar(255), -1);
binary &= maskOut;
//
image -= mask;
cv::findContours(image, contours, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE);
if (contours.empty()) {
return FUNC_CANNOT_CALC;
}
contourMax = contours[0]; contourMaxArea = cv::contourArea(contourMax);
for (int i = 1; i < contours.size(); i++)
{
double contourArea = cv::contourArea(contours[i]);
if (contourArea > contourMaxArea)
{
contourMax = contours[i];
contourMaxArea = contourArea;
}
}
//去除内部干扰
cv::minEnclosingCircle(contourMax, center, radius);
cv::circle(binary, cv::Point(center), cvRound(radius - 85), cv::Scalar(0), -1);
cv::Point reelCenter(cvRound(center.x), cvRound(center.y));
cv::drawMarker(cc, reelCenter, cv::Scalar(0, 0, 238, 255), 1, 35, 2);
//计数
nccomps = cv::connectedComponentsWithStats(binary, labels, stats, centroids);
binary = cv::Scalar(0);
for (int j = 1; j < nccomps; j++)
{
cv::Point pt(cvRound(centroids.ptr<double_t>(j)[0]), cvRound(centroids.ptr<double_t>(j)[1]));
if (pt.x > 0 && pt.y > 0 && pt.x < X&&pt.y < Y) {
binary.at<uchar>(pt) = 255;
cv::circle(cc, pt, 2, cv::Scalar(0, 255, 0, 255), 1);
}
}
}
else
{
//先用自动算法点,如果不行判断为散料
int trayNum[4];
int iRet = eyemCountObjectE(tpImage, tpRoi, "", trayNum, tpDstImg);
if (iRet == FUNC_OK) {
//输出结果
for (int i = 0; i < 4; i++) {
//输出结果
ipReelNum[i] = trayNum[i];
break;
}
return FUNC_OK;
}
else {
//判断为散料
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(75, 75)));
//计算直方图
int hist[256];
for (int y = 0; y < 256; y++) hist[y] = 0;
for (int y = 0; y < Y; y++)
{
uchar *uPtr = srcPrev.data + y * X;
for (int x = 0; x < srcPrev.cols; x++, uPtr++)
{
if ((binary.data)[(x)+(y)*X] == 255)
{
hist[*uPtr]++;
}
}
}
cv::threshold(srcPrev, binary, Otsu(hist), 255, cv::THRESH_BINARY);
std::vector<std::vector<cv::Point>> contours, contourFilter;
//连接在一起(散料用)
cv::Mat binaryEx;
cv::morphologyEx(binary, binaryEx, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(75, 75)));
//掩膜
cv::Mat mask(Y, X, CV_8UC1, cv::Scalar(0));
cv::findContours(binaryEx, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
for (int i = 0; i < contours.size(); i++)
{
double contourArea = cv::contourArea(contours[i]);
if (contourArea > 15000)
{
//绘制掩膜
cv::drawContours(mask, contours, i, cv::Scalar(255), -1);
}
}
//粗略计数
cv::Mat labels, stats, centroids;
int numObj = cv::connectedComponentsWithStats(binary&mask, labels, stats, centroids);
//坐标图
binary = cv::Scalar(0);
//画图
double *dpCent = (double *)centroids.data;
for (int j = 1; j < numObj; j++)
{
//面积过滤
if (stats.ptr<int>(j)[cv::CC_STAT_AREA] > 2) {
binary.at<uchar>(cv::Point(cvRound((float)dpCent[(0) + (j) * 2]), cvRound((float)dpCent[(1) + (j) * 2]))) = 255;
}
}
}
}
//计数
std::vector<cv::Point> idx;
cv::findNonZero(binary, idx);
//输出数量
int trayNum = (int)idx.size();
//画图显示
std::string text = "Reel Number = " + std::to_string(trayNum);
cv::putText(cc, text, cv::Point(35, 35), 0, 1.0, cv::Scalar(0, 140, 255, 255), 2);
//<输出结果
const int SizeConst = 4;
//<输出计数结果标记图像
memset(ipReelNum, 0, SizeConst);
ipReelNum[0] = trayNum;
tpDstImg->iWidth = cc.cols; tpDstImg->iHeight = cc.rows; tpDstImg->iDepth = cc.depth(); tpDstImg->iChannels = cc.channels();
//内存尺寸
int _Size = tpDstImg->iWidth*tpDstImg->iHeight*tpDstImg->iChannels * sizeof(uint8_t);
//分配/初始化内存
tpDstImg->vpImage = (uint8_t *)malloc(_Size);
if (NULL == tpDstImg->vpImage)
return FUNC_NOT_ENOUGH_MEM;
memset(tpDstImg->vpImage, 0, _Size);
//拷贝数据
memcpy(tpDstImg->vpImage, cc.data, _Size);
return FUNC_OK;
}
int eyemCountObjectE(EyemImage tpImage, EyemRect tpRoi, const char *fileName, int *ipReelNum, EyemImage *tpDstImg)
{
cv::Mat src = cv::Mat(tpImage.iHeight, tpImage.iWidth, MAKETYPE(tpImage.iDepth, tpImage.iChannels), tpImage.vpImage).clone();
if (src.empty()) {
return FUNC_IMAGE_NOT_EXIST;
}
//转单通道
if (src.channels() != 1)
cv::cvtColor(src, src, cv::COLOR_BGR2GRAY);
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularPartsE 初始阶段被跳过执行...");
return FUNC_CANNOT_CALC;
}
//图像裁剪
src = src(cv::Rect(tpRoi.iXs, tpRoi.iYs, tpRoi.iWidth, tpRoi.iHeight)).clone();
//image size
int X = src.cols, Y = src.rows;
//去除局部量斑影响(默认亮斑尺寸不会大于15个像素)
cv::Mat srcTmp;
cv::morphologyEx(src, srcTmp, cv::MORPH_ERODE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(15, 15)));
//去除黑斑影响
int m = cvRound(cv::mean(src)[0]);
srcTmp.forEach<uint16_t>([&](uint16_t& pixel, const int *pos)->void {
pixel = pixel == 0 ? m : pixel;
});
//图像增强
double min, max;
cv::Point maxId;
cv::minMaxLoc(srcTmp, &min, &max, NULL, &maxId);
src.convertTo(src, CV_64FC1);
src -= min;
src /= (max - min);
src *= 65535;
src.convertTo(src, CV_16UC1);
cv::Mat src8U;
src.convertTo(src8U, CV_8UC1, 1 / 255.);
//显示结果图像
cv::Mat cc;
cv::cvtColor(src8U, cc, cv::COLOR_GRAY2BGRA);
//设置bins
const int histSize = 17;
//range of values
float range[] = { 0,255 };
const float* histRange = { range };
//计算直方图
cv::Mat hist;
cv::calcHist(&src8U, 1, 0, cv::Mat(), hist, 1, &histSize, &histRange);
//计算背景
int maxIdx[2] = { 255,255 };
cv::minMaxIdx(hist, NULL, NULL, NULL, maxIdx);
//背景阈值
int backThresh = 15 * cvRound(((double)maxIdx[0] - 2));//正常-2
//移除背景
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 (src8U.ptr<uint8_t>(y)[x] >= backThresh) {
src8U.ptr<uint8_t>(y)[x] = backThresh;
}
}
}
});
//方便显示
cc += cv::Scalar((162 - backThresh), (162 - backThresh), (162 - backThresh));
//inv
cv::bitwise_not(src8U, src8U);
cv::Mat binary;
cv::threshold(src8U, binary, (255 - backThresh), 255, cv::THRESH_BINARY);
//连接在一起
cv::morphologyEx(binary, binary, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(45, 45)));
//find the pallet
std::vector<std::vector<cv::Point>> contoursFilter;
cv::findContours(binary, contoursFilter, cv::RETR_TREE, cv::CHAIN_APPROX_NONE);
//填充内部确定料盘
cv::Mat image = cv::Mat::zeros(src8U.size(), CV_8UC1);
for (int i = 0; i < contoursFilter.size(); i++)
{
if (cv::contourArea(contoursFilter[i]) > 100000)
{
cv::drawContours(image, contoursFilter, i, cv::Scalar(255), -1);
}
}
cv::bitwise_not(src8U, src8U);
//剩下即料盘区域(面积大于100000均认为是料盘)
cv::findContours(image, contoursFilter, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
//区分多个料盘
struct TrayPos
{
int iDir = -1;//0左上1左下2右下3右上
double dBackThresh;
bool bSorted;
cv::Point2f Center;
cv::Mat Tray;
TrayPos() {};
TrayPos(cv::Point2f center, cv::Mat tray, bool bSorted, double dBackThresh) :Center(center), Tray(tray), bSorted(bSorted), dBackThresh(dBackThresh) {}
};
std::vector <TrayPos> trays;
for (int i = 0; i < contoursFilter.size(); i++)
{
//定位中心
cv::Moments mu = cv::moments(contoursFilter[i]);
cv::Point reelCenter(cvRound(mu.m10 / mu.m00), cvRound(mu.m01 / mu.m00));
//掩膜
cv::Mat trayMask = cv::Mat::zeros(Y, X, CV_8UC1);
cv::drawContours(trayMask, contoursFilter, i, cv::Scalar(255), -1);
//
cv::Mat tray = cv::Mat(Y, X, CV_8UC1, backThresh);
src8U.copyTo(tray, trayMask);
trays.push_back(TrayPos(reelCenter, tray, false, backThresh));
}
//判断可能无料,不能100%判断
if (trays.size() < 1) {
for (int i = 0; i < 4; i++) {
ipReelNum[i] = 0;
}
return FUNC_CANNOT_CALC;
}
//图像中心
cv::Point reelCenter(X / 2, Y / 2);
//料盘排序
std::vector <TrayPos> sortedTrays;
for (int i = 0; i < trays.size(); i++)
{
//左上角
if ((int)trays[i].Center.x <= reelCenter.x && (int)trays[i].Center.y <= reelCenter.y)
{
if (trays[i].bSorted == false)
{
trays[i].iDir = 0;
trays[i].bSorted = true;
sortedTrays.push_back(trays[i]);
}
}
}
for (int i = 0; i < trays.size(); i++)
{
//左下角
if ((int)trays[i].Center.x <= reelCenter.x && (int)trays[i].Center.y >= reelCenter.y)
{
if (trays[i].bSorted == false)
{
trays[i].iDir = 1;
trays[i].bSorted = true;
sortedTrays.push_back(trays[i]);
}
}
}
for (int i = 0; i < trays.size(); i++)
{
//右下角
if ((int)trays[i].Center.x >= reelCenter.x && (int)trays[i].Center.y >= reelCenter.y)
{
if (trays[i].bSorted == false)
{
trays[i].iDir = 2;
trays[i].bSorted = true;
sortedTrays.push_back(trays[i]);
}
}
}
for (int i = 0; i < trays.size(); i++)
{
//右上角
if ((int)trays[i].Center.x >= reelCenter.x && (int)trays[i].Center.y <= reelCenter.y)
{
if (trays[i].bSorted == false)
{
trays[i].iDir = 3;
trays[i].bSorted = true;
sortedTrays.push_back(trays[i]);
}
}
}
//计数
std::vector<int> trayNum(4);
const char icvCodeDeltas[3][3][2] = { { { 0, -1 },{ 1, -1 },{ 1, 0 } },{ { 1, 1 },{ 0, 1 },{ -1, 1 } },{ { -1, 0 },{ -1, -1 },{ 0, -1 } } };
//分料盘计数
for (int i = 0; i < sortedTrays.size(); i++)
{
cv::Mat srcPrev, srcPrevB;
cv::bitwise_not(sortedTrays[i].Tray, srcPrev);
//备份
srcPrevB = srcPrev.clone();
//二值化可以分别放在两个算法里
cv::Mat sinParts;
cv::threshold(srcPrev, sinParts, (255 - sortedTrays[i].dBackThresh), 255, cv::THRESH_BINARY);
//判断元件尺寸
int sinPartSize;
bool useTrackMethod = checkSize(srcPrev, sinParts, sinPartSize);
//判断大小
cv::Mat m1, m2, m3;
int nccomps = cv::connectedComponentsWithStats(sinParts, m1, m2, m3);
//判断适用哪种算法
if (!useTrackMethod)
{
const int filterSize = 12;
//去掉料盘深色部分干扰
const int winSize = sinPartSize > 15 ? 5 : 3;//对于部分器件过小的窗口会漏料
cv::Mat srcPrevEx;
cv::morphologyEx(srcPrev, srcPrevEx, cv::MORPH_TOPHAT, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(winSize, winSize)));
//二值化元件区域,用OTSU还是其他?
cv::Mat sinPartMask;
cv::threshold(srcPrevEx, sinPartMask, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
//连在一起
cv::morphologyEx(sinPartMask, srcPrevEx, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(5, 5)));
//去除孔洞
cv::morphologyEx(srcPrevEx, srcPrevEx, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(21, 21)));
//去除深色部分备份
cv::Mat removeDark = srcPrevEx.clone();
//最大外包
cv::morphologyEx(srcPrevEx, srcPrevEx, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(45, 45)));
//定位料盘中心
cv::findContours(srcPrevEx, contoursFilter, cv::RETR_TREE, cv::CHAIN_APPROX_NONE);
image = cv::Scalar(0);
for (int i = 0; i < contoursFilter.size(); i++)
{
cv::drawContours(image, contoursFilter, i, cv::Scalar(255), -1);
}
image -= srcPrevEx;
//获取最大轮廓
cv::findContours(image, contoursFilter, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
if (contoursFilter.size() <= 0)
{
continue;
}
std::vector<cv::Point> contourMax = contoursFilter[0];
for (int i = 1; i < contoursFilter.size(); i++)
{
if (cv::contourArea(contoursFilter[i]) > cv::contourArea(contourMax))
{
contourMax = contoursFilter[i];
}
}
cv::Moments mu = cv::moments(contourMax);
cv::Point2f reelCenter(float(mu.m10 / mu.m00), float(mu.m01 / mu.m00));
//画中心
//计算最大外接圆半径
float tFRadius = 0;
cv::minEnclosingCircle(contourMax, cv::Point2f(), tFRadius);
reelCenter.x = reelCenter.x > 0 && reelCenter.x < X ? reelCenter.x : 0;
reelCenter.y = reelCenter.y > 0 && reelCenter.y < Y ? reelCenter.y : 0;
cv::drawMarker(cc, reelCenter, cv::Scalar(0, 0, 238, 255), 1, 35, 2);
//去掉中心1/3区域
cv::circle(sinPartMask, reelCenter, cvRound(tFRadius / 2), cv::Scalar(0), -1);
//掩膜区域,用于区分处理区域
uchar *upMask = sinPartMask.data;
//最小料不进行粘连判断
cv::Mat mulParts(Y, X, CV_8UC1, cv::Scalar(0));
//
std::vector<uchar> colors(nccomps + 1, 0);
if (sinPartSize >= filterSize)
{
upMask = mulParts.data;
//根据元件大小确定是否进行粘连处理
for (int i = 1; i < nccomps; i++) {
colors[i] = 0;
if (((int *)m2.data)[(cv::CC_STAT_AREA) + (i)*m2.cols] >= 1.6*sinPartSize)//经验值
{
colors[i] = 255;
}
}
//认为是粘连
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++)
{
int label = ((int *)m1.data)[(x)+(y)*m1.cols];
CV_Assert(0 <= label && label <= nccomps);
(mulParts.data)[(x)+(y)*X] = colors[label];
}
}
});
sinParts &= removeDark;
mulParts &= removeDark;
sinParts -= mulParts;
cv::circle(sinParts, reelCenter, cvRound(tFRadius / 2), cv::Scalar(0), -1);
cv::circle(mulParts, reelCenter, cvRound(tFRadius / 2), cv::Scalar(0), -1);
}
//标签图像
unsigned char *pLabelImg = (unsigned char *)malloc(Y*X * sizeof(unsigned char));
memset(pLabelImg, 0, X*Y * sizeof(unsigned char));
cv::Mat lbImage(Y, X, CV_8UC1, pLabelImg);
//区分不同大小器件用不同的图处理
#define upSrc(x, y) (srcPrev.data)[(x) + (y)*X]
//连通域非极大值处理
for (int y = 1; y < Y - 1; y++)
{
for (int x = 1; x < X - 1; x++)
{
//属于连通域内,并且尚未被标记
if (upMask[(x)+(y)*X] != 0 && pLabelImg[(x)+(y)*X] != 255)
{
//生长种子点
auto pixval = upSrc(x, y);
if (pixval >= upSrc((x - 1), (y - 1)) && pixval >= upSrc((x), (y - 1)) && pixval >= upSrc((x + 1), (y - 1))\
&& pixval >= upSrc((x + 1), (y)) && pixval >= upSrc((x + 1), (y + 1)) && pixval >= upSrc((x), (y + 1))\
&& pixval >= upSrc((x - 1), (y + 1)) && pixval >= upSrc((x - 1), (y)))
{
//标记已处理
pLabelImg[(x)+(y)*X] = 255;
unsigned char direction = 0;
unsigned int xx = x;
unsigned int yy = y;
bool growEnd = false;
do
{
for (unsigned int n = 0; n < 3; n++)
{
bool found = false;
for (unsigned char i = 0; i < 3; i++)
{
int nx = xx + icvCodeDeltas[direction][i][0];
int ny = yy + icvCodeDeltas[direction][i][1];
//越界处理
if (nx < 2 || ny < 2 || nx>srcPrev.cols - 2 || ny>srcPrev.rows - 2)
continue;
//考虑多加个条件限制峰值
auto val = upSrc((nx), (ny));
if (val >= pixval&&pLabelImg[(nx)+(ny)*X] != 255)
{
found = true;
xx = nx;
yy = ny;
//next
direction = icvCodeDeltas[direction][i][2];
//标记已处理
pLabelImg[(xx)+(yy)*X] = 255;
break;
}
}
if (!found)
{
direction = (direction + 1) % 4;
}
if (growEnd = (direction == 3))
break;
}
} while (!growEnd);
}
}
}
}
//合并
lbImage += sinPartSize >= filterSize ? sinParts : mulParts;
//粗略计数
cv::Mat labels, stats, centroids;
int numObj = cv::connectedComponentsWithStats(lbImage, labels, stats, centroids);
//清空
memset(pLabelImg, 0, X*Y * sizeof(unsigned char));
//画图
#define dpCent(x,y) ((double *)centroids.data)[(x)+(y)*2]
for (int j = 1; j < numObj; j++)
{
cv::Point ms(cvRound(dpCent(0, j)), cvRound(dpCent(1, j)));
pLabelImg[(ms.x) + (ms.y)*X] = 255;
}
//计数
std::vector<cv::Point> vLocations;
cv::findNonZero(lbImage, vLocations);
for (int c = 0; c < vLocations.size(); c++)
{
cc.at<cv::Vec4b>(vLocations[c]) = cv::Vec4b(0, 0, 200, 255);
cv::circle(cc, vLocations[c], 1, cv::Scalar(0, 255, 0, 255), 1);
}
//测试用,对已经寻找到的元件进行筛选
//cv::putText(cc, std::to_string(sortedTrays[i].iDir), cv::Point(cvRound(reelCenter.x), cvRound(reelCenter.y) - 50), 0, 1.0, cv::Scalar(0, 140, 255, 255), 2);
numObj = (int)vLocations.size();
std::string text = std::to_string(i + 1) + ": Reel Number = ";
text += std::to_string(numObj);
text += " ; PartSize = " + std::to_string(sinPartSize);
cv::putText(cc, text, cv::Point(35, 35 + i * 35), 0, 1.0, cv::Scalar(0, 140, 255, 255), 2);
//
trayNum[sortedTrays[i].iDir] = numObj;
//释放资源
free((void *)pLabelImg);
}
else
{
//采用追踪算法
nccomps = cv::connectedComponentsWithStats(sinParts, m1, m2, m3);
//连在一起
cv::Mat srcPrevEx0;
cv::morphologyEx(sinParts, srcPrevEx0, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(45, 45)));
//定位料盘中心
cv::findContours(srcPrevEx0, contoursFilter, cv::RETR_TREE, cv::CHAIN_APPROX_NONE);
image = cv::Scalar(0);
for (int i = 0; i < contoursFilter.size(); i++)
{
cv::drawContours(image, contoursFilter, i, cv::Scalar(255), -1);
}
image -= srcPrevEx0;
//获取最大轮廓
cv::findContours(image, contoursFilter, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
if (contoursFilter.size() <= 0)
continue;
std::vector<cv::Point> contourMax = contoursFilter[0];
for (int i = 1; i < contoursFilter.size(); i++)
{
if (cv::contourArea(contoursFilter[i]) > cv::contourArea(contourMax))
{
contourMax = contoursFilter[i];
}
}
//计算最大外接圆半径
float tFRadius = 0;
cv::minEnclosingCircle(contourMax, cv::Point2f(), tFRadius);
cv::Moments mu = cv::moments(contourMax);
cv::Point2f reelCenter(float(mu.m10 / mu.m00), float(mu.m01 / mu.m00));
//画中心
reelCenter.x = reelCenter.x > 0 && reelCenter.x < X ? reelCenter.x : 0;
reelCenter.y = reelCenter.y > 0 && reelCenter.y < Y ? reelCenter.y : 0;
cv::drawMarker(cc, reelCenter, cv::Scalar(0, 0, 238, 255), 1, 35, 2);
//包含未粘连器件
image = cv::Scalar(0);
std::vector<uchar> colors(nccomps + 1, 0);
for (int i = 1; i < nccomps; i++) {
colors[i] = 255;
if ((((int *)m2.data)[(cv::CC_STAT_AREA) + (i)*m2.cols] >= 1.5*sinPartSize) || (((int *)m2.data)[(cv::CC_STAT_AREA) + (i)*m2.cols] < 0.4*sinPartSize))//经验值
{
colors[i] = 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++) {
int label = ((int *)m1.data)[(x)+(y)*m1.cols];
CV_Assert(0 <= label && label <= nccomps);
(image.data)[(x)+(y)*X] = colors[label];
}
}
});
//去掉中心1/3区域
cv::circle(image, reelCenter, cvRound(tFRadius / 3), cv::Scalar(0), -1);
struct TracingAnchor
{
float Size;
float Length, Height;
cv::Point2f Anchor;
cv::RotatedRect RBox;
TracingAnchor(cv::Point2f Anchor, float Length, float Height, float Size, cv::RotatedRect RBox) :Anchor(Anchor), Length(Length), Height(Height), Size(Size), RBox(RBox) {}
bool operator >(const TracingAnchor &te)const
{
return Size > te.Size;
}
bool operator <(const TracingAnchor &te)const
{
return Size < te.Size;
}
};
std::vector<std::vector<cv::Point>> contourTracing;
cv::findContours(image, contourTracing, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
//所有追踪锚点
std::vector<TracingAnchor> tracingAnchors;
for (auto&contour : contourTracing) {
cv::RotatedRect rbox = cv::minAreaRect(contour);
if (cv::min(rbox.size.width, rbox.size.height) > 2.0f) {
tracingAnchors.push_back(TracingAnchor(rbox.center, cv::max(rbox.size.width, rbox.size.height), cv::min(rbox.size.width, rbox.size.height), rbox.size.area(), rbox));
}
}
//不存在独立元件
if (tracingAnchors.empty()) {
return FUNC_CANNOT_CALC;
}
//尺寸只计算一次
std::sort(tracingAnchors.begin(), tracingAnchors.end(), std::greater<TracingAnchor>());
//
struct Track {
int iLimit, iPartSize;
double dMatchDeg = 0.0;
cv::Point2f Pos;
std::vector<cv::Point2f> Rect;
Track() {};
Track(int iLimit, int iPartSize, double dMatchDeg, cv::Point2f Pos, std::vector<cv::Point2f> Rect) :iLimit(iLimit), iPartSize(iPartSize), dMatchDeg(dMatchDeg), Pos(Pos), Rect(Rect) {};
bool operator >(const Track &te)const
{
return dMatchDeg > te.dMatchDeg;
}
bool operator <(const Track &te)const
{
return dMatchDeg < te.dMatchDeg;
}
};
//缩放比例
float coeff = 1.0f;
//填充值
const int fillVal = 255 - backThresh;
//元件尺寸
const double taLength = tracingAnchors[tracingAnchors.size() / 2].Length; const double taHeight = tracingAnchors[tracingAnchors.size() / 2].Height;
//元件灰度值
double taMaxGray = 0.0;
//标签图
unsigned char *ucpTrackLabel = new unsigned char[Y*X]();
cv::Mat trackMat(Y, X, CV_8UC1, ucpTrackLabel);
//计数图像
cv::Mat lbMat(Y, X, CV_8UC1, cv::Scalar(0));
//定位图像
cv::Mat srcPrevS, tplMat;//模板文件
srcPrevB.convertTo(srcPrevS, CV_32F);
//随机打乱顺序(降低计算错误dChordL的可能性,也为了测试在起点信息不同时的稳定性)
std::random_shuffle(tracingAnchors.begin(), tracingAnchors.end());
//开始确定起点(现在是用圆轨迹来追踪,不排除用螺旋线轨迹来追踪)
for (std::vector<TracingAnchor>::iterator itvx = tracingAnchors.begin(); itvx != tracingAnchors.end(); ++itvx) {
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularParts 点料阶段被跳过执行...");
break;
}
//起始位置信息
TracingAnchor ta = (*itvx);
//起始位置坐标
cv::Point2f startCenter(ta.Anchor.x, ta.Anchor.y);
//最小外包矩形
cv::Point2f _pts[4];
ta.RBox.points(_pts);
//已做标记(TODO:考虑增加判断哪些是起点哪些不是)
if (trackMat.ptr<uint8_t>(cvRound(startCenter.y))[cvRound(startCenter.x)] == 255) {
continue;
}
//获取模板图像(是否每次起点都计算模板,如果元件变形过大是否还会有用?)
if (tplMat.empty())
{
float tDist = ta.Height / 2.0f;
//理论范围扩展
cv::Rect _rLimits = cv::Rect(cv::Point2i(cvRound((float)ta.RBox.boundingRect2f().tl().x - tDist),
cvRound((float)ta.RBox.boundingRect2f().tl().y - tDist)), cv::Point2i(cvRound((float)ta.RBox.boundingRect2f().br().x + tDist),
cvRound((float)ta.RBox.boundingRect2f().br().y + tDist))
)&cv::Rect(0, 0, X, Y);
//确定元件位置根据旋转后的位置确定(前提是料盘中心定位的准确)
double t = atan2((double)startCenter.y - reelCenter.y, (double)startCenter.x - reelCenter.x) * 180.0 / PI;
//计算旋转角度
cv::Mat traceMat = srcPrevB(_rLimits);
//这里计算得出的模板不是很对
float matx[6];
tplMat = getTrackMat(traceMat, t + 90.0, 0, matx);
//变换后的坐标
cv::Point2f __pts[4];
for (int j = 0; j < 4; j++)
{
__pts[j].x = matx[0] * (_pts[j].x - (float)_rLimits.x) + matx[1] * (_pts[j].y - (float)_rLimits.y) + matx[2];
__pts[j].y = matx[3] * (_pts[j].x - (float)_rLimits.x) + matx[4] * (_pts[j].y - (float)_rLimits.y) + matx[5];
}
cv::Point2f __ptsc((__pts[0].x + __pts[1].x + __pts[2].x + __pts[3].x) / 4.0f, (__pts[0].y + __pts[1].y + __pts[2].y + __pts[3].y) / 4.0f);
//确定各顶点方位
struct DIR {
int i = -1;
cv::Point2f pt;
DIR() {};
DIR(int i, cv::Point2f pt) :i(i), pt(pt) {};
};
auto _dir_l = std::vector<DIR>(); auto _dir_r = std::vector<DIR>();
for (int j = 0; j < 4; j++)
{
if (__pts[j].x < __ptsc.x) {
_dir_l.push_back(DIR(j, __pts[j]));
}
else {
_dir_r.push_back(DIR(j, __pts[j]));
}
}
//重新选点计算模板
if (_dir_l.size() != _dir_r.size()) {
continue;
}
//确定顶点方向
cv::Point2f p0, p1, p2, p3;
if (_dir_l[0].pt.y < _dir_l[1].pt.y) {
p0 = _pts[_dir_l[0].i];
p1 = _pts[_dir_l[1].i];
}
else {
p0 = _pts[_dir_l[1].i];
p1 = _pts[_dir_l[0].i];
}
if (_dir_r[0].pt.y > _dir_r[1].pt.y) {
p2 = _pts[_dir_r[0].i];
p3 = _pts[_dir_r[1].i];
}
else {
p2 = _pts[_dir_r[1].i];
p3 = _pts[_dir_r[0].i];
}
//计算精确角度
cv::Point2f p01((p0.x + p1.x) / 2.0f, (p0.y + p1.y) / 2.0f), p23((p2.x + p3.x) / 2.0f, (p2.y + p3.y) / 2.0f);
double realT = atan2((double)p23.y - (double)p01.y, (double)p23.x - (double)p01.x) * 180.0 / PI;
cv::Mat realTplMat = getTrackMat(traceMat, realT, 0, matx);
cv::Point2f __mpts[4];
for (int j = 0; j < 4; j++)
{
__mpts[j].x = matx[0] * (_pts[j].x - (float)_rLimits.x) + matx[1] * (_pts[j].y - (float)_rLimits.y) + matx[2];
__mpts[j].y = matx[3] * (_pts[j].x - (float)_rLimits.x) + matx[4] * (_pts[j].y - (float)_rLimits.y) + matx[5];
}
cv::Rect _rr(cvFloor(std::min(std::min(std::min(__mpts[0].x, __mpts[1].x), __mpts[2].x), __mpts[3].x)),
cvFloor(std::min(std::min(std::min(__mpts[0].y, __mpts[1].y), __mpts[2].y), __mpts[3].y)),
cvCeil(std::max(std::max(std::max(__mpts[0].x, __mpts[1].x), __mpts[2].x), __mpts[3].x)),
cvCeil(std::max(std::max(std::max(__mpts[0].y, __mpts[1].y), __mpts[2].y), __mpts[3].y))); _rr.width -= _rr.x - 1; _rr.height -= _rr.y - 1;
//最终模板
tplMat = realTplMat(_rr).clone();
//缩放比例
if (MIN(tplMat.size().width, tplMat.size().height) < 12.0) {
coeff = 2.0f;
}
//最大值
cv::minMaxLoc(tplMat, NULL, &taMaxGray);
}
//标记为已追踪过
std::vector<cv::Point> vT = { cv::Point(_pts[0]),cv::Point(_pts[1]) ,cv::Point(_pts[2]) ,cv::Point(_pts[3]) };
cv::fillConvexPoly(trackMat, vT, cv::Scalar(255));
//标记计数
lbMat.ptr<uint8_t>(cvRound(startCenter.y))[cvRound(startCenter.x)] = 255;
//标记当前位置
cv::drawMarker(cc, cv::Point(startCenter), cv::Scalar(0, 255, 0, 255), cv::MARKER_DIAMOND, 5);
//扫描步长
const double dMinorStep = 0.1;
//追踪长宽
const double trackLength = taLength / 2.0, trackWidth = taHeight / 4.0;//是否用较小尺寸的窗口
//起始扫描角度
const double startAngle = atan2((double)startCenter.y - reelCenter.y, (double)startCenter.x - reelCenter.x) * 180.0 / PI;
//起始扫描半径
const double startRadius = cv::norm(startCenter - reelCenter);
//偏移角度(元件尺寸)
const double dOffset = (2.0 * asin(2.0 * trackLength / (2.0 * startRadius))) * 180.0 / PI;
//扫描角度(默认15度范围内存在元件)
const double dScanRange = 15.0;
//追踪元件间距(弦长,可以尽量避免因个别器件偏离导致的追踪中断)
double dChordL = .0;
for (double t = startAngle + dOffset / 1.5; t < startAngle + dScanRange; t += dMinorStep)
{
float x = float(reelCenter.x + startRadius*cos(t*c));
float y = float(reelCenter.y + startRadius*sin(t*c));
//防止超出图像范围
if (cvRound(x) < 0 || (cvRound(x) > X - 1) || cvRound(y) < 0 || (cvRound(y) > Y - 1)) {
break;
}
//确定是否是下一个元件
if (trackMat.ptr<uint8_t>(cvRound(y))[cvRound(x)] == 255) {
continue;
}
//初次确定元件间距
const double angle = atan2((double)reelCenter.y - y, (double)reelCenter.x - x);
cv::Point p1 = cv::Point(cvRound(x + trackWidth * cos(angle)),
cvRound(y + trackWidth * sin(angle)));
cv::Point p2 = cv::Point(cvRound(x + trackWidth * cos(angle + CV_PI)),
cvRound(y + trackWidth * sin(angle + CV_PI)));
#ifdef _DEBUG
cv::line(cc, p1, p2, cv::Scalar(0, 215, 255, 255), 1);
#endif
cv::LineIterator it(sinParts, p1, p2, 4);
for (int n = 0; n < it.count; n++, ++it)
{
if (sinParts.ptr<uint8_t>(it.pos().y)[it.pos().x] == 255)
{
//计算元件间距(弦长)
dChordL = 2.0 * startRadius*sin(((2.0 * asin((cv::norm(startCenter - cv::Point2f(x, y))) / (2.0 * startRadius))) * 180.0 / PI - dOffset / 2.0)*PI / 180.0 / 2.0);
break;
}
}
if (dChordL > 2.1)
break;
}
//没确定出元件间距一般为结尾或单个元件,继续从下一个起点计算弦长并开始追踪
if (dChordL <= 2.1) {
continue;
}
//顺时针(是否并行取决于在windows下运行还是树莓派上)
{
//追踪中心
cv::Point2f trackCenter = cv::Point2f(startCenter.x, startCenter.y);
//追踪角度、半径
double trackAngle = startAngle, trackRadius = startRadius;
//元件本身所占角度
double trackOffset = dOffset;
//元件间间距
double partDist = (2.0 * asin(dChordL / (2.0 * trackRadius))) * 180.0 / PI;
//开始追踪
bool trackEnd = true;
do
{
bool found = true; bool trayEnd = false;
std::vector<Track> vParts;
for (double t = trackAngle + (trackOffset + partDist - trackOffset / 12.0); t < trackAngle + (trackOffset + partDist - trackOffset / 12.0) + trackOffset / 6.0; t += dMinorStep)
{
cv::Point2f predicPos;
predicPos.x = reelCenter.x + (float)trackRadius*(float)cos((trackAngle + (trackOffset + partDist))*c);
predicPos.y = reelCenter.y + (float)trackRadius*(float)sin((trackAngle + (trackOffset + partDist))*c);
//如果追踪到图像外则追踪终止
if (cvRound(predicPos.x) < 0 || (cvRound(predicPos.x) > X - 1) || cvRound(predicPos.y) < 0 || (cvRound(predicPos.y) > Y - 1)) {
trayEnd = true;
break;
}
//感兴趣区域(向外扩展了一个元件,防止中心定位出现偏差或者料盘本身变形导致的偏差)
cv::Point2f predictBox[4];
calcRotateRect(predicPos, (float)(trackAngle + (trackOffset + partDist)), (float)trackLength + (float)trackLength, (float)trackWidth + (float)trackWidth, predictBox);
cv::RotatedRect r(predictBox[0], predictBox[1], predictBox[2]);
cv::Rect rLimits = r.boundingRect()&cv::Rect(0, 0, X, Y);
//获取感兴趣区域
float matx[6];
cv::Mat traceMat = getTrackMat(srcPrevS(rLimits).clone()
, (trackAngle + (trackOffset + partDist)) + 90.0, fillVal, matx);
//计算原图中的点在旋转后的位置(即在traceMat中的精确位置)
cv::Point2f predictBoxR[4];
for (int j = 0; j < 4; j++)
{
predictBoxR[j].x = matx[0] * (predictBox[j].x - (float)rLimits.x) + matx[1] * (predictBox[j].y - (float)rLimits.y) + matx[2];
predictBoxR[j].y = matx[3] * (predictBox[j].x - (float)rLimits.x) + matx[4] * (predictBox[j].y - (float)rLimits.y) + matx[5];
}
//中点
cv::Point2f predicPosR((predictBoxR[0].x + predictBoxR[1].x + predictBoxR[2].x + predictBoxR[3].x) / 4.0f,
(predictBoxR[0].y + predictBoxR[1].y + predictBoxR[2].y + predictBoxR[3].y) / 4.0f);
//理论区域
cv::Rect tRec = cv::Rect(cv::Point(cvRound((predicPosR.x*2.0f - (float)trackLength*2.0f) / 2.0f),
cvRound((predicPosR.y*2.0f - (float)trackWidth*4.0f) / 2.0f)),
cv::Size(cvRound(trackLength*2.0), cvRound(trackWidth*4.0)))
&cv::Rect(0, 0, traceMat.cols, traceMat.rows);
//高精度理论区域
cv::Rect_<float> tRecF = cv::Rect_<float>(cv::Point2f((predicPosR.x*2.0f - (float)trackLength*2.0f) / 2.0f,
(predicPosR.y*2.0f - (float)trackWidth*4.0f) / 2.0f),
cv::Size2f((float)trackLength*2.0f, (float)trackWidth*4.0f))
&cv::Rect_<float>(0.0f, 0.0f, (float)traceMat.cols, (float)traceMat.rows);
//理论区域向外扩展(即predictBox范围)
cv::Rect rr = cv::Rect(cv::Point(cvRound((double)predicPosR.x - trackLength*2.0),
cvRound((double)predicPosR.y - trackWidth*4.0)), cv::Size(cvRound(trackLength*2.0*2.0),
cvRound(trackWidth*4.0*2.0)))&cv::Rect(0, 0, traceMat.cols, traceMat.rows);
cv::Rect_<float> rrf = cv::Rect2f(cv::Point2f((predicPosR.x*2.0f - (float)trackLength*4.0f) / 2.0f,
(predicPosR.y*2.0f - (float)trackWidth*8.0f) / 2.0f), cv::Size2f((float)trackLength*4.0f, (float)trackWidth*8.0f))
&cv::Rect2f(0.0f, 0.0f, (float)traceMat.cols, (float)traceMat.rows);
//元件尺寸太小放大N倍处理,这样坐标会精细些,考虑元件的80%尺寸作为kernel,防止元件尺寸变化太大
cv::Mat kernel = cv::Mat::ones(cv::Size(cv::max(cvRound((float)(trackLength*2.0) * coeff),
cvRound((float)(trackWidth*4.0) * coeff)), cv::min(cvRound((float)(trackLength*2.0) * coeff),
cvRound((float)(trackWidth*4.0) * coeff))), CV_32FC1);
cv::Mat _traceMat = traceMat.clone();
//放大
if (coeff > 1.0f) {
cv::resize(_traceMat, _traceMat, cv::Size(cvRound(traceMat.size().width * coeff), cvRound(traceMat.size().height * coeff)));
}
//计算最大值(当_traceMat尺寸小于kernel会报错)
cv::Mat dst;
cv::filter2D(_traceMat, dst, CV_32F, kernel);
//归一化
cv::Mat mmRescaling;
cv::normalize(dst, mmRescaling, 1.0, 0.0, cv::NORM_MINMAX);
//模板匹配做辅助判断,为了尽量避免定位出错
cv::Mat _tplMat;
tplMat.convertTo(_tplMat, CV_32FC1);
if (coeff > 1.0f) {
cv::resize(_tplMat, _tplMat, cv::Size(), coeff, coeff);
}
//防止报错
if (_tplMat.cols > _traceMat.cols || _tplMat.rows > _traceMat.rows) {
return FUNC_CANNOT_CALC;
}
//考虑并行计算两个模板结果
cv::Mat tplResult0;
cv::matchTemplate(_traceMat, _tplMat, tplResult0, cv::TM_SQDIFF_NORMED);
int modx = _tplMat.cols % 2, mody = _tplMat.rows % 2;
cv::Mat tplResultMap;
cv::copyMakeBorder(tplResult0, tplResultMap, (_tplMat.rows - mody) / 2, _traceMat.rows - tplResult0.rows - (_tplMat.rows - mody) / 2,
(_tplMat.cols - modx) / 2, _traceMat.cols - tplResult0.cols - (_tplMat.cols - modx) / 2, cv::BORDER_REPLICATE);
//减去模板匹配的结果
mmRescaling -= tplResultMap;
//非极大值抑制
cv::Mat mask;
cv::dilate(mmRescaling, mask, cv::Mat());
cv::compare(mmRescaling, mask, mask, cv::CMP_GE);
cv::Mat non_plateau_mask;
cv::erode(mmRescaling, non_plateau_mask, cv::Mat());
cv::compare(mmRescaling, non_plateau_mask, non_plateau_mask, cv::CMP_GT);
cv::bitwise_and(mask, non_plateau_mask, mask);
//去掉分数过低的
mask &= cv::Mat(mmRescaling > 0.36);
//限定区域(mmRescaling范围内)
cv::Rect _rr = cv::Rect(cvRound(rr.x*coeff), cvRound(rr.y*coeff), cvRound(rr.width*coeff), cvRound(rr.height*coeff));
//候选元件位置
std::vector<cv::Point> candidates;
cv::findNonZero(mask(_rr), candidates);
//过滤
std::vector<Track> _vParts;
for (auto&candidate : candidates) {
cv::Point pt(candidate.x + _rr.x, candidate.y + _rr.y);
float confidence = mmRescaling.ptr<float>(pt.y)[pt.x];
if (confidence > 0.5f) {
_vParts.push_back(Track(0, 0, confidence, cv::Point2f((float)pt.x, (float)pt.y), std::vector<cv::Point2f>()));
}
}
//目标元件在小图中的位置
cv::Point2f maxLox;
//元件位置判断
if (_vParts.size() <= 0) {
//大概率终止
trayEnd = true;
}
else if (_vParts.size() == 1) {
//有可能会出错
maxLox = cv::Point2f(_vParts[0].Pos.x / coeff, _vParts[0].Pos.y / coeff);
if (tRecF.contains(maxLox)) {
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle + (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
}
else {
//这里负责处理意外情况(极大可能是元件偏离过多或者料盘中心定位不准确导致的),
//采用距离理论位置最近的点(两种方式都失效的概率比较低,如果真的失效那就听天由命吧)
cv::Mat _mmRescaling, _tplResultMap;
_mmRescaling = mmRescaling.clone(); _tplResultMap = tplResultMap.clone();
//累加的方式
double maxVal; cv::Point maxLoc;
cv::minMaxLoc(_mmRescaling(_rr), NULL, &maxVal, NULL, &maxLoc);
maxLoc += _rr.tl();
//模板匹配的方式
double minVal; cv::Point minLoc;
cv::minMaxLoc(_tplResultMap(_rr), &minVal, NULL, &minLoc, NULL);
minLoc += _rr.tl();
std::vector<Track> __vParts;
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)maxLoc.x, (float)maxLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)maxLoc.x, (float)maxLoc.y), std::vector<cv::Point2f>()));
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)minLoc.x, (float)minLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)minLoc.x, (float)minLoc.y), std::vector<cv::Point2f>()));
//排序
std::sort(__vParts.begin(), __vParts.end(), std::less<Track>());
//在小图中的位置
maxLox = cv::Point2f(__vParts[0].Pos.x / coeff, __vParts[0].Pos.y / coeff);
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle + (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
#ifdef _DEBUG
for (int j = 0; j < 4; j++)
{
cv::line(cc, predictBox[j], predictBox[(j + 1) % 4], cv::Scalar(0, 0, 255, 255), 1);
}
#endif
}
}
else {
//存在多个峰值,先判断分数最高是否位于理论位置
std::sort(_vParts.begin(), _vParts.end(), std::greater<Track>());
for (auto&_vPart : _vParts) {
maxLox = cv::Point2f(_vPart.Pos.x / coeff, _vPart.Pos.y / coeff);
if (tRecF.contains(maxLox)) {
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle + (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
break;
}
}
//如果不在则选取距离理论位置最近的
if (vParts.empty()) {
//这里负责处理意外情况(极大可能是元件偏离过多或者中心定位不准确)
//,采用距离理论位置最近的点(两种方式都失效的概率比较低)
cv::Mat _mmRescaling, _tplResultMap;
_mmRescaling = mmRescaling.clone(); _tplResultMap = tplResultMap.clone();
//累加的方式
double maxVal; cv::Point maxLoc;
cv::minMaxLoc(_mmRescaling(_rr), NULL, &maxVal, NULL, &maxLoc);
maxLoc += _rr.tl();
//模板匹配的方式
double minVal; cv::Point minLoc;
cv::minMaxLoc(_tplResultMap(_rr), &minVal, NULL, &minLoc, NULL);
minLoc += _rr.tl();
std::vector<Track> __vParts;
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)maxLoc.x, (float)maxLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)maxLoc.x, (float)maxLoc.y), std::vector<cv::Point2f>()));
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)minLoc.x, (float)minLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)minLoc.x, (float)minLoc.y), std::vector<cv::Point2f>()));
//排序
std::sort(__vParts.begin(), __vParts.end(), std::less<Track>());
//在小图中的位置
maxLox = cv::Point2f(__vParts[0].Pos.x / coeff, __vParts[0].Pos.y / coeff);
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle + (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
#ifdef _DEBUG
for (int j = 0; j < 4; j++)
{
cv::line(cc, predictBox[j], predictBox[(j + 1) % 4], cv::Scalar(0, 0, 255, 255), 1);
}
#endif
}
}
if (!vParts.empty()) {
cv::Rect tRec_ = cv::Rect(cv::Point(cvFloor((((float)maxLox.x)*2.0f - (float)trackLength*2.0f) / 2.0f),
cvFloor((((float)maxLox.y)*2.0f - (float)trackWidth*4.0f) / 2.0f)),
cv::Size(cvRound(trackLength*2.0) + 2, cvRound(trackWidth*4.0) + 2))
&cv::Rect(0, 0, traceMat.cols, traceMat.rows);
//当作一种辅助手段,无需设置太严格
double dmax;
cv::minMaxLoc(traceMat(tRec_).clone(), NULL, &dmax);
if (dmax < 0.7*taMaxGray) {
trayEnd = true;
}
}
break;
}
//追踪终止,选取下一个起点
if (trayEnd) {
break;
}
//更新位置
trackCenter = cv::Point2f(vParts[0].Pos.x, vParts[0].Pos.y);
//更新扫描半径
trackRadius = cv::norm(trackCenter - reelCenter);
//更新扫描角度
trackAngle = atan2((double)trackCenter.y - (double)reelCenter.y, (double)trackCenter.x - (double)reelCenter.x) * 180.0 / PI;
//更新偏移量(元件角度大小)
trackOffset = (2 * asin(2 * trackLength / (2 * trackRadius))) * 180.0 / PI;
//更新元件间角度
partDist = (2 * asin(dChordL / (2 * trackRadius))) * 180.0 / PI;
//追踪到了重复的元件
if ((trackCenter.x<0 || trackCenter.x>X - 1 ||
trackCenter.y<0 || trackCenter.y>Y - 1) || trackMat.ptr<uint8_t>(cvRound(trackCenter.y))[cvRound(trackCenter.x)] == 255) {
found = false;
}
else {
//计算元件位置
cv::Point2f pts[4];
calcRotateRect(trackCenter, (float)trackAngle, (float)trackLength, (float)trackWidth, pts);
//标记计数
lbMat.ptr<uint8_t>(cvRound(trackCenter.y))[cvRound(trackCenter.x)] = 255;
//标记为已追踪过
std::vector<cv::Point> vT = { cv::Point(pts[0]),cv::Point(pts[1]) ,cv::Point(pts[2]) ,cv::Point(pts[3]) };
cv::fillConvexPoly(trackMat, vT, cv::Scalar(255));
//用于显示
cv::circle(cc, trackCenter, 2, cv::Scalar(0, 255, 0, 255), 1);
#ifdef _DEBUG
for (int j = 0; j < 4; j++)
{
cv::line(cc, pts[j], pts[(j + 1) % 4], cv::Scalar(14, 173, 238, 255), 1);
}
#endif
}
//清空下一个
vParts.resize(0);
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularPartsE 追踪阶段被跳过执行...");
found = false;
}
trackEnd = (!found);
} while (!trackEnd);
}
//逆时针
{
//追踪起点
cv::Point2f trackCenter(startCenter.x, startCenter.y);
//追踪角度、半径
double trackAngle = startAngle, trackRadius = startRadius;
//元件本身角度
double trackOffset = dOffset;
//元件间间距
double partDist = (2.0 * asin(dChordL / (2.0 * trackRadius))) * 180.0 / PI;
//开始追踪
bool trackEnd = true;
//
do
{
bool found = true; bool trayEnd = false;
std::vector<Track> vParts;
for (double t = trackAngle - (trackOffset + partDist - trackOffset / 12.0); t > trackAngle - (trackOffset + partDist - trackOffset / 12.0) - trackOffset / 6.0; t -= dMinorStep)
{
cv::Point2f predicPos;
predicPos.x = reelCenter.x + (float)trackRadius*(float)cos((trackAngle - (trackOffset + partDist))*c);
predicPos.y = reelCenter.y + (float)trackRadius*(float)sin((trackAngle - (trackOffset + partDist))*c);
//如果追踪到图像外追踪终止
if (cvRound(predicPos.x) < 0 || (cvRound(predicPos.x) > X - 1) || cvRound(predicPos.y) < 0 || (cvRound(predicPos.y) > Y - 1)) {
trayEnd = true;
break;
}
//感兴趣区域(向外扩展了一个元件,防止中心定位出现偏差或者料盘本身变形导致的偏差)
cv::Point2f predicBox[4];
calcRotateRect(predicPos, (float)(trackAngle - (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, predicBox);
cv::RotatedRect r(predicBox[0], predicBox[1], predicBox[2]);
cv::Rect rLimits = r.boundingRect()&cv::Rect(0, 0, X, Y);
//获取感兴趣区域
float matx[6];
cv::Mat traceMat = getTrackMat(srcPrevS(rLimits).clone()
, (trackAngle - (trackOffset + partDist)) + 90.0, fillVal, matx);
//计算原图中的点在旋转后的位置(即在traceMat中的精确位置)
cv::Point2f predictBoxR[4];
for (int j = 0; j < 4; j++)
{
predictBoxR[j].x = matx[0] * (predicBox[j].x - (float)rLimits.x) + matx[1] * (predicBox[j].y - (float)rLimits.y) + matx[2];
predictBoxR[j].y = matx[3] * (predicBox[j].x - (float)rLimits.x) + matx[4] * (predicBox[j].y - (float)rLimits.y) + matx[5];
}
//中点
cv::Point2f predicPosR((predictBoxR[0].x + predictBoxR[1].x + predictBoxR[2].x + predictBoxR[3].x) / 4.0f,
(predictBoxR[0].y + predictBoxR[1].y + predictBoxR[2].y + predictBoxR[3].y) / 4.0f);
//理论区域
cv::Rect tRec = cv::Rect(cv::Point(cvRound((predicPosR.x*2.0f - (float)trackLength*2.0f) / 2.0f),
cvRound((predicPosR.y*2.0f - (float)trackWidth*4.0f) / 2.0f)),
cv::Size(cvRound(trackLength*2.0), cvRound(trackWidth*4.0)))
&cv::Rect(0, 0, traceMat.cols, traceMat.rows);
//高精度理论区域
cv::Rect_<float> tRecF = cv::Rect_<float>(cv::Point2f((predicPosR.x*2.0f - (float)trackLength*2.0f) / 2.0f,
(predicPosR.y*2.0f - (float)trackWidth*4.0f) / 2.0f),
cv::Size2f((float)trackLength*2.0f, (float)trackWidth*4.0f))
&cv::Rect_<float>(0.0f, 0.0f, (float)traceMat.cols, (float)traceMat.rows);
//理论区域向外扩展(即predictBox范围)
cv::Rect rr = cv::Rect(cv::Point(cvRound((double)predicPosR.x - trackLength*2.0),
cvRound((double)predicPosR.y - trackWidth*4.0)), cv::Size(cvRound(trackLength*2.0*2.0),
cvRound(trackWidth*4.0*2.0)))&cv::Rect(0, 0, traceMat.cols, traceMat.rows);
cv::Rect_<float> rrf = cv::Rect2f(cv::Point2f((predicPosR.x*2.0f - (float)trackLength*4.0f) / 2.0f,
(predicPosR.y*2.0f - (float)trackWidth*8.0f) / 2.0f), cv::Size2f((float)trackLength*4.0f, (float)trackWidth*8.0f))
&cv::Rect2f(0.0f, 0.0f, (float)traceMat.cols, (float)traceMat.rows);
//元件尺寸太小放大N倍处理,这样坐标会精细些,元件的80%尺寸作为kernel,防止元件尺寸变化太大
cv::Mat kernel = cv::Mat::ones(cv::Size(cv::max(cvRound((float)(trackLength*2.0) * coeff),
cvRound((float)(trackWidth*4.0) * coeff)), cv::min(cvRound((float)(trackLength*2.0) * coeff),
cvRound((float)(trackWidth*4.0) * coeff))), CV_32FC1);
cv::Mat _traceMat = traceMat.clone();
//放大
if (coeff > 1.0f) {
cv::resize(_traceMat, _traceMat, cv::Size(cvRound(traceMat.size().width * coeff), cvRound(traceMat.size().height * coeff)));
}
//计算最大值(当_traceMat尺寸小于kernel会报错)
cv::Mat dst;
cv::filter2D(_traceMat, dst, CV_32F, kernel);
//归一化
cv::Mat mmRescaling;
cv::normalize(dst, mmRescaling, 1.0, 0.0, cv::NORM_MINMAX);
//模板匹配,为了尽量避免定位出错
cv::Mat _tplMat;
tplMat.convertTo(_tplMat, CV_32FC1);
if (coeff > 1.0f) {
cv::resize(_tplMat, _tplMat, cv::Size(), coeff, coeff);
}
//防止报错
if (_tplMat.cols > _traceMat.cols || _tplMat.rows > _traceMat.rows) {
return FUNC_CANNOT_CALC;
}
//考虑并行计算两个模板结果
cv::Mat tplResult0;
cv::matchTemplate(_traceMat, _tplMat, tplResult0, cv::TM_SQDIFF_NORMED);
int modx = _tplMat.cols % 2, mody = _tplMat.rows % 2;
cv::Mat tplResultMap;
cv::copyMakeBorder(tplResult0, tplResultMap, (_tplMat.rows - mody) / 2, _traceMat.rows - tplResult0.rows - (_tplMat.rows - mody) / 2,
(_tplMat.cols - modx) / 2, _traceMat.cols - tplResult0.cols - (_tplMat.cols - modx) / 2, cv::BORDER_REPLICATE);
//减去模板匹配的结果
mmRescaling -= tplResultMap;
//非极大值抑制
cv::Mat mask;
cv::dilate(mmRescaling, mask, cv::Mat());
cv::compare(mmRescaling, mask, mask, cv::CMP_GE);
cv::Mat non_plateau_mask;
cv::erode(mmRescaling, non_plateau_mask, cv::Mat());
cv::compare(mmRescaling, non_plateau_mask, non_plateau_mask, cv::CMP_GT);
cv::bitwise_and(mask, non_plateau_mask, mask);
//去掉分数过低的
mask &= cv::Mat(mmRescaling > 0.36);
//限定区域(mmRescaling范围内)
cv::Rect _rr = cv::Rect(cvRound(rr.x*coeff), cvRound(rr.y*coeff), cvRound(rr.width*coeff), cvRound(rr.height*coeff));
//候选元件位置
std::vector<cv::Point> candidates;
cv::findNonZero(mask(_rr), candidates);
//过滤
std::vector<Track> _vParts;
for (auto&candidate : candidates) {
cv::Point pt(candidate.x + _rr.x, candidate.y + _rr.y);
float confidence = mmRescaling.ptr<float>(pt.y)[pt.x];
if (confidence > 0.5f) {
_vParts.push_back(Track(0, 0, confidence, cv::Point2f((float)pt.x, (float)pt.y), std::vector<cv::Point2f>()));
}
}
//目标元件在小图中的位置
cv::Point2f maxLox;
//元件位置判断
if (_vParts.size() <= 0) {
//大概率终止
trayEnd = true;
}
else if (_vParts.size() == 1) {
maxLox = cv::Point2f(_vParts[0].Pos.x / coeff, _vParts[0].Pos.y / coeff);
//有可能会出错,当靠的太近可能只存在一个峰值
if (tRecF.contains(maxLox)) {
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle + (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
}
else {
//这里负责处理意外情况(极大可能是元件偏离过多或者中心定位不准确),采用距离理论位置最近的点(两种方式都失效的概率比较低)
cv::Mat _mmRescaling, _tplResultMap;
_mmRescaling = mmRescaling.clone(); _tplResultMap = tplResultMap.clone();
//累加的方式
double maxVal; cv::Point maxLoc;
cv::minMaxLoc(_mmRescaling(_rr), NULL, &maxVal, NULL, &maxLoc);
maxLoc += _rr.tl();
//模板匹配的方式
double minVal; cv::Point minLoc;
cv::minMaxLoc(_tplResultMap(_rr), &minVal, NULL, &minLoc, NULL);
minLoc += _rr.tl();
std::vector<Track> __vParts;
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)maxLoc.x, (float)maxLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)maxLoc.x, (float)maxLoc.y), std::vector<cv::Point2f>()));
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)minLoc.x, (float)minLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)minLoc.x, (float)minLoc.y), std::vector<cv::Point2f>()));
//排序
std::sort(__vParts.begin(), __vParts.end(), std::less<Track>());
//小图中的定位坐标
maxLox = cv::Point2f(__vParts[0].Pos.x / coeff, __vParts[0].Pos.y / coeff);
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle - (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
#ifdef _DEBUG
for (int j = 0; j < 4; j++)
{
cv::line(cc, predicBox[j], predicBox[(j + 1) % 4], cv::Scalar(0, 0, 238, 255), 1);
}
#endif
}
}
else {
//存在定位出错的可能性,先判断分数最高是否位于理论位置
std::sort(_vParts.begin(), _vParts.end(), std::greater<Track>());
for (auto&_vPart : _vParts) {
maxLox = cv::Point2f(_vPart.Pos.x / coeff, _vPart.Pos.y / coeff);
if (tRecF.contains(maxLox)) {
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle - (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
break;
}
}
//如果不在则选取距离理论位置最近的
if (vParts.empty()) {
//这里负责处理意外情况(极大可能是元件偏离过多或者中心定位不准确),采用距离理论位置最近的点(两种方式都失效的概率比较低)
cv::Mat _mmRescaling, _tplResultMap;
_mmRescaling = mmRescaling.clone(); _tplResultMap = tplResultMap.clone();
//累加的方式
double maxVal; cv::Point maxLoc;
cv::minMaxLoc(_mmRescaling(_rr), NULL, &maxVal, NULL, &maxLoc);
maxLoc += _rr.tl();
//模板匹配的方式
double minVal; cv::Point minLoc;
cv::minMaxLoc(_tplResultMap(_rr), &minVal, NULL, &minLoc, NULL);
minLoc += _rr.tl();
std::vector<Track> __vParts;
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)maxLoc.x, (float)maxLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)maxLoc.x, (float)maxLoc.y), std::vector<cv::Point2f>()));
__vParts.push_back(Track(0, 0, cv::norm(cv::Point2f((float)minLoc.x, (float)minLoc.y) - cv::Point2f(floorf((float)_traceMat.cols / 2.0f), floorf((float)_traceMat.rows / 2.0f))),
cv::Point2f((float)minLoc.x, (float)minLoc.y), std::vector<cv::Point2f>()));
//排序
std::sort(__vParts.begin(), __vParts.end(), std::less<Track>());
//小图中的位置
maxLox = cv::Point2f(__vParts[0].Pos.x / coeff, __vParts[0].Pos.y / coeff);
//计算旋转前的坐标(即匹配的最终坐标)
float realX = 0.0f, realY = 0.0f;
realX = (float)rLimits.tl().x + ((maxLox.x - matx[2])*matx[4] - (maxLox.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
realY = (float)rLimits.tl().y + ((maxLox.x - matx[2])*matx[3] - (maxLox.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//外包矩形顶点
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(realX, realY), (float)(trackAngle - (trackOffset + partDist)), (float)trackLength*2.0f, (float)trackWidth*2.0f, pts);
//
std::vector<cv::Point2f> vRect(pts, pts + sizeof(pts) / sizeof(cv::Point2f));
vParts.push_back(Track(0, 0, 0, cv::Point2f(realX, realY), vRect));
#ifdef _DEBUG
for (int j = 0; j < 4; j++)
{
cv::line(cc, predicBox[j], predicBox[(j + 1) % 4], cv::Scalar(0, 0, 238, 255), 1);
}
#endif
}
}
if (!vParts.empty()) {
cv::Rect tRec_ = cv::Rect(cv::Point(cvFloor((((float)maxLox.x)*2.0f - (float)trackLength*2.0f) / 2.0f),
cvFloor((((float)maxLox.y)*2.0f - (float)trackWidth*4.0f) / 2.0f)),
cv::Size(cvRound(trackLength*2.0) + 2, cvRound(trackWidth*4.0) + 2))
&cv::Rect(0, 0, traceMat.cols, traceMat.rows);
//当作一种辅助手段,无需设置太严格
double dmax;
cv::minMaxLoc(traceMat(tRec_).clone(), NULL, &dmax);
if (dmax < 0.7*taMaxGray) {
trayEnd = true;
}
}
break;
}
//接着下一个起点
if (trayEnd) {
break;
}
//更新位置
trackCenter = cv::Point2f(vParts[0].Pos.x, vParts[0].Pos.y);
//更新扫描半径
trackRadius = cv::norm(trackCenter - reelCenter);
//更新扫描角度
trackAngle = atan2((double)trackCenter.y - (double)reelCenter.y, (double)trackCenter.x - (double)reelCenter.x) * 180.0 / PI;
//更新偏移量(元件角度大小)
trackOffset = (2.0 * asin(2.0 * trackLength / (2.0 * trackRadius))) * 180.0 / PI;
//更新元件间角度
partDist = (2.0 * asin(dChordL / (2.0 * trackRadius))) * 180.0 / PI;
//追踪到了重复的元件
if ((trackCenter.x<0 || trackCenter.x>X - 1 ||
trackCenter.y<0 || trackCenter.y>Y - 1) || trackMat.ptr<uint8_t>(cvRound(trackCenter.y))[cvRound(trackCenter.x)] == 255) {
found = false;
}
else {
//计算元件位置
cv::Point2f pts[4];
calcRotateRect(trackCenter, (float)trackAngle, (float)trackLength, (float)trackWidth, pts);
//标记计数
lbMat.ptr<uint8_t>(cvRound(trackCenter.y))[cvRound(trackCenter.x)] = 255;
//标记为已追踪过
std::vector<cv::Point> vT = { cv::Point(pts[0]),cv::Point(pts[1]) ,cv::Point(pts[2]) ,cv::Point(pts[3]) };
cv::fillConvexPoly(trackMat, vT, cv::Scalar(255));
//用于显示
cv::circle(cc, trackCenter, 2, cv::Scalar(0, 255, 0, 255), 1);
#ifdef _DEBUG
for (int j = 0; j < 4; j++)
{
cv::line(cc, pts[j], pts[(j + 1) % 4], cv::Scalar(102, 205, 0, 255), 1);
}
#endif
}
//继续下一个起点
vParts.resize(0);
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularParts 追踪阶段被跳过执行...");
found = false;
}
trackEnd = (!found);
} while (!trackEnd);
}
}
//标记料盘编号
//cv::putText(cc, std::to_string(sortedTrays[i].iDir), cv::Point(cvRound(reelCenter.x), cvRound(reelCenter.y) - 50), 0, 1.0, cv::Scalar(0, 140, 255, 255), 2);
//计数
int reelNum = cv::countNonZero(lbMat);
std::string text = std::to_string(i + 1) + ": Reel Number = ";
text += std::to_string(reelNum);
text += " ; PartSize = " + std::to_string(sinPartSize);
cv::putText(cc, text, cv::Point(35, 35 + i * 35), 0, 1.0, cv::Scalar(0, 140, 255, 255), 2);
//输出
trayNum[sortedTrays[i].iDir] = reelNum;
//释放资源
delete[] ucpTrackLabel;
ucpTrackLabel = NULL;
}
}
//输出结果
const int SizeConst = 4;
//<输出计数结果标记图像
{
for (int i = 0; i < SizeConst; i++) {
ipReelNum[i] = trayNum[i];
}
tpDstImg->iWidth = cc.cols; tpDstImg->iHeight = cc.rows; tpDstImg->iDepth = cc.depth(); tpDstImg->iChannels = cc.channels();
//内存尺寸
int _Size = tpDstImg->iWidth*tpDstImg->iHeight*tpDstImg->iChannels * sizeof(uint8_t);
//分配内存
tpDstImg->vpImage = (uint8_t *)malloc(_Size);
if (NULL == tpDstImg->vpImage)
return FUNC_NOT_ENOUGH_MEM;
memset(tpDstImg->vpImage, 0, _Size);
//拷贝数据
memcpy(tpDstImg->vpImage, cc.data, _Size);
}
return FUNC_OK;
}
int eyemCountObjectIrregularPartsE(EyemImage tpImage, EyemRect tpRoi, const char *fileName, const char *ccTplName, IntPtr hModelID, int *ipReelNum, EyemImage *tpDstImg)
{
cv::Mat src = cv::Mat(tpImage.iHeight, tpImage.iWidth, MAKETYPE(tpImage.iDepth, tpImage.iChannels), tpImage.vpImage).clone();
//判断文件是否存在
if (src.empty() || NULL == hModelID) {
return FUNC_IMAGE_NOT_EXIST;
}
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularPartsE 初始阶段被跳过执行...");
return FUNC_CANNOT_CALC;
}
double begin0 = (double)cv::getTickCount();
//转单通道图像
if (src.channels() != 1)
cv::cvtColor(src, src, cv::COLOR_BGR2GRAY);
//图像裁剪
src = src(cv::Rect(tpRoi.iXs, tpRoi.iYs, tpRoi.iWidth, tpRoi.iHeight)).clone();
//图像尺寸
int X = src.cols, Y = src.rows;
//加载模板
std::vector<EyemModelID> *tpModelIDs = reinterpret_cast<std::vector<EyemModelID>*>(hModelID);
cv::Mat _tplMat; double matchDeg = 0.0;
//
for (std::vector<EyemModelID>::iterator it = tpModelIDs->begin(); it != tpModelIDs->end(); ++it) {
if (std::strcmp((*it).lpszName, ccTplName) == 0)
{
EyemModelID tpModelID = (*it);
matchDeg = tpModelID.dMatchDeg;
_tplMat = cv::Mat(tpModelID.iHeight, tpModelID.iWidth, CV_8UC1, tpModelID.vpImage);
break;
}
}
//模板文件不存在
if (_tplMat.empty())
return FUNC_CANNOT_CALC;
//模板反转
cv::Mat tplMat;
cv::bitwise_not(_tplMat, tplMat);
//模板尺寸
int tplWidth, tplHeight;
tplWidth = tplMat.cols, tplHeight = tplMat.rows;
//去除局部量斑影响(默认亮斑尺寸不会大于15个像素)
cv::Mat srcTmp;
cv::morphologyEx(src, srcTmp, cv::MORPH_ERODE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(15, 15)));
//去除黑斑影响
int m = cvRound(cv::mean(src)[0]);
srcTmp.forEach<uint16_t>([&](uint16_t& pixel, const int *pos)->void {
pixel = pixel == 0 ? m : pixel;
});
//图像增强
double min, max;
cv::minMaxLoc(srcTmp, &min, &max);
src.convertTo(src, CV_64FC1);
src -= min;
src /= (max - min);
src *= 65535;
src.convertTo(src, CV_16UC1);
//转8位灰度图
cv::Mat src8U;
src.convertTo(src8U, CV_8UC1, 1 / 255.);
//用于显示
cv::Mat cc;
cv::cvtColor(src8U, cc, cv::COLOR_GRAY2BGRA);
//设定bin数目
const int histSize = 17;
//设定取值范围
float range[] = { 0,255 };
const float* histRange = { range };
//计算直方图
cv::Mat hist;
cv::calcHist(&src8U, 1, 0, cv::Mat(), hist, 1, &histSize, &histRange);
//计算背景像素
int maxIdx[2] = { 255,255 };
cv::minMaxIdx(hist, NULL, NULL, NULL, maxIdx);
//背景阈值
int backT = 15 * (maxIdx[0] - 2);
//去掉背景
src8U.forEach<uint8_t>([&](uint8_t& pixel, const int *pos)->void {
pixel = pixel >= backT ? backT : pixel;
});
//增强到目标亮度,用于显示
cc += cv::Scalar((162 - backT), (162 - backT), (162 - backT));
//去掉干扰
cv::Mat binary, srcPrev;
cv::bitwise_not(src8U, srcPrev);
//计数图像
cv::Mat lbMat(Y, X, CV_8UC1, cv::Scalar(0));
//测试用,根据模板尺寸顶帽处理,去掉中间料盘
int minPart = cv::min(tplWidth, tplHeight);
cv::Mat srcPrevWithMask(Y, X, CV_8UC1);
srcPrev.copyTo(srcPrevWithMask);
if (minPart < 12) {
cv::Mat srcPrevEx;
cv::morphologyEx(srcPrev, srcPrevEx, cv::MORPH_TOPHAT, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(minPart, minPart)));
//
cv::Mat srcPrevExb;
cv::threshold(srcPrevEx, srcPrevExb, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
//膨胀
cv::morphologyEx(srcPrevExb, srcPrevExb, cv::MORPH_DILATE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(minPart, minPart)));
//去掉盘本身的影响
srcPrevWithMask = cv::Scalar(255 - backT);
srcPrev.copyTo(srcPrevWithMask, srcPrevExb);
}
//使用大料算法(模板匹配方式)
cv::threshold(srcPrev, binary, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
//去掉小于5个像素的干扰
cv::Mat labels0, stats0, centroids0;
int nccomps0 = cv::connectedComponentsWithStats(binary, labels0, stats0, centroids0, 4);
//过滤连通域面积及长/宽比例不符合的,允许50%误差
std::vector<uchar> colors0(nccomps0 + 1, 0);
for (int i = 1; i < nccomps0; i++) {
colors0[i] = 255;
if ((stats0.ptr<int>(i)[cv::CC_STAT_AREA] < 10))
{
colors0[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 = labels0.ptr<int>(y)[x];
CV_Assert(0 <= label && label <= nccomps0);
ptrRow[x] = colors0[label];
}
}
});
cv::Mat srcPrevEx0;
//连接
cv::morphologyEx(binary, srcPrevEx0, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(95, 95)));
//定位料盘中心
std::vector<std::vector<cv::Point>> contours;
cv::findContours(srcPrevEx0, contours, cv::RETR_TREE, cv::CHAIN_APPROX_NONE);
cv::Mat srcPrevEx1 = cv::Mat::zeros(src8U.size(), CV_8UC1);
//填充料盘
for (int i = 0; i < contours.size(); i++)
{
cv::drawContours(srcPrevEx1, contours, i, cv::Scalar(255), -1);
}
cv::Mat image = srcPrevEx1.clone();
//取中间部分,避免因料盘散开而导致中心定位错误(如果没有就选取外面)
srcPrevEx1 -= srcPrevEx0;
//
cv::morphologyEx(srcPrevEx1, srcPrevEx1, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(95, 95)));
//获取最大轮廓
cv::findContours(srcPrevEx1, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
if (contours.size() <= 0)
{
cv::findContours(image, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
}
std::vector<cv::Point> contourMax = contours[0]; double contourMaxArea = cv::contourArea(contourMax);
for (int i = 1; i < contours.size(); i++)
{
double contourArea = cv::contourArea(contours[i]);
if (contourArea > contourMaxArea)
{
contourMax = contours[i];
contourMaxArea = contourArea;
}
}
//面积小于50000判断不是中心
if (contourMaxArea < 50000) {
cv::findContours(image, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
//最大轮廓
for (int i = 1; i < contours.size(); i++)
{
double contourArea = cv::contourArea(contours[i]);
if (contourArea > contourMaxArea)
{
contourMax = contours[i];
contourMaxArea = contourArea;
}
}
}
//质心
cv::Moments mu = cv::moments(contourMax);
cv::Point2f reelCenter(float(mu.m10 / mu.m00), float(mu.m01 / mu.m00));
//画中心
reelCenter.x = reelCenter.x > 0 && reelCenter.x < X ? reelCenter.x : 0;
reelCenter.y = reelCenter.y > 0 && reelCenter.y < Y ? reelCenter.y : 0;
cv::drawMarker(cc, reelCenter, cv::Scalar(0, 0, 238, 255), 1, 35, 2);
//计算料盘范围
cv::findContours(image, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
contourMax = contours[0]; contourMaxArea = cv::contourArea(contourMax);
for (int i = 1; i < contours.size(); i++)
{
double contourArea = cv::contourArea(contours[i]);
if (contourArea > contourMaxArea)
{
contourMax = contours[i];
contourMaxArea = contourArea;
}
}
//去掉料盘中心
cv::circle(srcPrevWithMask, cv::Point(reelCenter), 150, cv::Scalar(255 - backT), -1);
cv::Rect rec = cv::boundingRect(contourMax);
//顶点坐标
cv::Point tl, br, tr, bl;
tl = cv::Point(cv::max(rec.tl().x - 35, 0), cv::max(rec.tl().y - 35, 0)); br = cv::Point(cv::min(rec.br().x + 35, Y), cv::min(rec.br().y + 35, Y));
tr = cv::Point(br.x, tl.y); bl = cv::Point(tl.x, br.y);
//用八个方向的模板进行模板匹配(模板匹配的方式对于发生形变的器件效果不好,实在不行就用八个方向,增加起点数量来弥补追踪终止导致的偏差)
const float icvDirections[4] = { 0 , 90 , 180 , -90 };
//用以计算元件中心
const int icvDirectionDeltas[4][2] = { { tplWidth / 2,tplHeight / 2 },{ tplHeight / 2,tplWidth / 2 },{ tplWidth / 2,tplHeight / 2 },\
{ tplHeight / 2,tplWidth / 2 } };
//用于计数
cv::Mat matchParts(Y, X, CV_8UC1, cv::Scalar(0));
cv::parallel_for_(cv::Range(0, 4), [&](const cv::Range& range)->void {
for (int tpl = range.start; tpl < range.end; tpl++)
{
//模板匹配(仅处理料盘区域以提高速度)
cv::Mat tplResult0;
cv::matchTemplate(srcPrevWithMask(cv::Rect(tl, br)), getTplMat(tplMat, icvDirections[tpl], (255 - backT)), tplResult0, cv::TM_CCOEFF_NORMED);
//分数大于一定分数才当作元件处理
tplResult0 = cv::Mat(tplResult0 > matchDeg);
cv::Point quard[4]{ cv::Point(tplResult0.cols,0),cv::Point(0,0),cv::Point(0,tplResult0.rows),cv::Point(tplResult0.cols,tplResult0.rows) };
std::vector<cv::Point> pt = { cv::Point(tplResult0.cols / 2,tplResult0.rows / 2),quard[tpl], quard[(tpl + 1) % 4] };
std::vector<std::vector<cv::Point>> pts;
pts.push_back(pt);
cv::Mat dirMask(tplResult0.size(), CV_8UC1, cv::Scalar(0));
cv::drawContours(dirMask, pts, 0, cv::Scalar(255), -1);
//除去非必要部分
cv::bitwise_and(tplResult0, dirMask, tplResult0);
//连通域分析
cv::Mat labels, stats, centroids;
int nccomps = cv::connectedComponentsWithStats(tplResult0, labels, stats, centroids);
for (int i = 1; i < nccomps; i++) {
cv::Point matchPt(cvRound(centroids.ptr<double>(i)[0]) + icvDirectionDeltas[tpl][0] + tl.x, \
cvRound(centroids.ptr<double>(i)[1]) + icvDirectionDeltas[tpl][1] + tl.y);
matchParts.ptr<uint8_t>(matchPt.y)[matchPt.x] = 255;
}
}
});
//旋转图像,计算另外四个方向的起点
float matx[6];
cv::Mat srcPrev45 = getTrackMat(srcPrevWithMask(cv::Rect(tl, br)), 45.0, 0, matx);
/*cv::Mat showMat2;
cv::cvtColor(srcPrev(cv::Rect(tl, br)), showMat2, cv::COLOR_GRAY2BGRA);*/
cv::parallel_for_(cv::Range(0, 4), [&](const cv::Range& range)->void {
for (int tpl = range.start; tpl < range.end; tpl++)
{
//模板匹配(仅处理料盘区域以提高速度)
cv::Mat tplResult0;
cv::matchTemplate(srcPrev45, getTplMat(tplMat, icvDirections[tpl], 0), tplResult0, cv::TM_CCOEFF_NORMED);
//分数大于一定分数才当作元件处理
tplResult0 = cv::Mat(tplResult0 > matchDeg);
cv::Point quard[4]{ cv::Point(tplResult0.cols,0),cv::Point(0,0),cv::Point(0,tplResult0.rows),cv::Point(tplResult0.cols,tplResult0.rows) };
std::vector<cv::Point> pt = { cv::Point(tplResult0.cols / 2,tplResult0.rows / 2),quard[tpl], quard[(tpl + 1) % 4] };
std::vector<std::vector<cv::Point>> pts;
pts.push_back(pt);
cv::Mat dirMask(tplResult0.size(), CV_8UC1, cv::Scalar(0));
cv::drawContours(dirMask, pts, 0, cv::Scalar(255), -1);
//除去非必要部分
cv::bitwise_and(tplResult0, dirMask, tplResult0);
//连通域分析
cv::Mat labels, stats, centroids;
int nccomps = cv::connectedComponentsWithStats(tplResult0, labels, stats, centroids);
for (int i = 1; i < nccomps; i++) {
cv::Point matchPt(cvRound(centroids.ptr<double>(i)[0]) + icvDirectionDeltas[tpl][0], \
cvRound(centroids.ptr<double>(i)[1]) + icvDirectionDeltas[tpl][1]);
//转原图坐标
cv::Point2f maxLoc;
maxLoc.x = (float)tl.x + (((float)matchPt.x - matx[2])*matx[4] - ((float)matchPt.y - matx[5])*matx[1]) / (matx[0] * matx[4] - matx[3] * matx[1]);
maxLoc.y = (float)tl.y + (((float)matchPt.x - matx[2])*matx[3] - ((float)matchPt.y - matx[5])*matx[0]) / (matx[1] * matx[3] - matx[4] * matx[0]);
//记录位置
matchParts.ptr<uint8_t>(cvRound(maxLoc.y))[cvRound(maxLoc.x)] = 255;
}
}
});
//计算初始起点
std::vector<cv::Point> matchPts;
cv::findNonZero(matchParts, matchPts);
#ifdef _DEBUG
for (std::vector<cv::Point>::iterator itv = matchPts.begin(); itv != matchPts.end(); ++itv)
{
cv::drawMarker(cc, cv::Point((*itv).x, (*itv).y), cv::Scalar(0, 255, 0, 255));
}
#endif
///<追踪元件算法流程
//标签图
cv::Mat trackMat(Y, X, CV_8UC1, cv::Scalar(0));
//追踪信息
struct Track {
int iLimit, iPartSize;
double dMatchDeg;
cv::Point Pos;
std::vector<cv::Point2f> Rect;
Track() {};
Track(int iLimit, int iPartSize, double dMatchDeg, cv::Point Pos, std::vector<cv::Point2f> Rect) :iLimit(iLimit), \
iPartSize(iPartSize), dMatchDeg(dMatchDeg), Pos(Pos), Rect(Rect) {};
bool operator >(const Track &te)const
{
return dMatchDeg > te.dMatchDeg;
}
};
//计算元件间距
double dChordL = .0;
for (std::vector<cv::Point>::iterator itv = matchPts.begin(); itv != matchPts.end(); ++itv)
{
///<初始化追踪参数
//追踪起点
cv::Point2f startCenter((float)(*itv).x, (float)(*itv).y);
//扫描步长
const double dMinorStep = 0.1;
//追踪长宽
const double trackLength = (double)tplWidth / 2., trackWidth = (double)tplHeight / 4.;
//起始扫描角度
const double startAngle = atan2((double)startCenter.y - (double)reelCenter.y, (double)startCenter.x - (double)reelCenter.x) * 180 / PI;
//起始扫描半径
const double startRadius = cv::norm(startCenter - reelCenter);
//偏移角度(元件尺寸)
const double dOffset = (2 * asin(2 * trackLength / (2 * startRadius))) * 180. / PI;
//初始搜索角度,用以确定元件间距(默认15度范围内存在元件)
const double dScanRange = 15;
//追踪元件间距(弦长,可以尽量避免因个别器件偏离导致的追踪中断)
std::vector<Track> track4ChordL; bool expect = false;
for (double t = startAngle + dOffset; t < startAngle + dOffset + dScanRange; t += dMinorStep)
{
float x = float(reelCenter.x + startRadius*cos(t*c));
float y = float(reelCenter.y + startRadius*sin(t*c));
cv::Point2f pts[4];
calcRotateRect(cv::Point2f(x, y), (float)t, (float)trackLength, (float)trackWidth, pts);
//计算极值
double maxyyu; cv::Point2f trackCentert;
findTrackModel(srcPrev, tplMat, 90.0 - (t + 180.0), trackWidth, pts, (255 - backT), false, maxyyu, trackCentert, cv::noArray());
//匹配阈值
if (maxyyu > matchDeg)
{
track4ChordL.push_back(Track(0, 0, maxyyu, (cv::Point)trackCentert, std::vector<cv::Point2f>()));
if (!expect)
expect = true;
}
if ((maxyyu < matchDeg) && expect)
break;
}
//计算元件间距
if (track4ChordL.size() != 0) {
std::sort(track4ChordL.begin(), track4ChordL.end(), std::greater<Track>());
cv::Point expectPos = track4ChordL[0].Pos;
dChordL = 2.0 * startRadius*sin(((2.0 * asin((cv::norm(startCenter - cv::Point2f((float)expectPos.x, \
(float)expectPos.y))) / (2.0 * startRadius))) * 180.0 / PI - dOffset)*PI / 180.0 / 2.0);
//标记
//cv::drawMarker(cc, cv::Point(expectPos.x, expectPos.y), cv::Scalar(0, 0, 255, 255), 0, 10);
}
else {
//用先前的方式重新计算间距,因为耗时操作不会在这里,加上可以减少耗时但可能不一定准
}
//计算元件间距
if (dChordL > 0) {
break;
}
}
//std::cout << "除追踪之外耗时:" << 1000 * (static_cast<double>(cv::getTickCount()) - begin0) / cv::getTickFrequency() << std::endl;
//大于3个起点坐标排序
if (matchPts.size() > 3) {
std::vector<Track> tMatchPts;
for (std::vector<cv::Point>::iterator itv = matchPts.begin(); itv != matchPts.end(); ++itv)
{
cv::Point2f startCenter((float)(*itv).x, (float)(*itv).y);
tMatchPts.push_back(Track(0, 0, cv::norm(startCenter - reelCenter), cv::Point(startCenter), std::vector<cv::Point2f>()));
}
//按照距离排序
std::sort(tMatchPts.begin(), tMatchPts.end(), std::greater<Track>());
std::vector<cv::Point> sortedMatchPts;
int len = cvRound((double)tMatchPts.size() / 2.0);
for (int i = 0; i < len; i++)
{
int beforeidx = (len * 3 - i) % tMatchPts.size();
int afteridx = (len * 3 + i) % tMatchPts.size();
if (beforeidx == afteridx) {
sortedMatchPts.push_back(tMatchPts[afteridx].Pos);
}
else {
sortedMatchPts.push_back(tMatchPts[afteridx].Pos);
sortedMatchPts.push_back(tMatchPts[beforeidx].Pos);
}
}
//偶数个
if (tMatchPts.size() % 2 == 0) {
sortedMatchPts.push_back(tMatchPts[0].Pos);
}
//容器内容互换
sortedMatchPts.swap(matchPts);
}
///<开始顺时针与逆时针两个方向追踪流程
for (std::vector<cv::Point>::iterator itv = matchPts.begin(); itv != matchPts.end(); ++itv)
{
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularPartsE 点料阶段被跳过执行...");
break;
}
//追踪起点
cv::Point2f startCenter((float)(*itv).x, (float)(*itv).y);
//已作标记
if (trackMat.ptr<uint8_t>((int)startCenter.y)[(int)startCenter.x] == 255)
continue;
//除去内圈干扰
if (cv::norm(startCenter - reelCenter) < 150)
continue;
//计算元件区域
cv::Point2f points[4];
{
double t = atan2((double)(*itv).y - reelCenter.y, (double)(*itv).x - reelCenter.x) * 180 / PI;
const float trackLength = (float)tplWidth / 2.0f, trackWidth = (float)tplHeight / 4.0f;
calcRotateRect(startCenter, (float)t, trackLength, trackWidth, points);
}
//增加判断,在模板匹配失效时候判断,可能匹配的不是元件
cv::RotatedRect rt(points[0], points[1], points[2]);
cv::Rect brt = rt.boundingRect()&cv::Rect(0, 0, X, Y);
//判断为背景
if (((float)cv::countNonZero(binary(brt)) / rt.size.area()) < 0.25) {
continue;
}
//标记为已追踪过
std::vector<cv::Point> vT = { cv::Point(points[0]),cv::Point(points[1]) ,cv::Point(points[2]) ,cv::Point(points[3]) };
cv::fillConvexPoly(trackMat, vT, cv::Scalar(255));
//标记计数
lbMat.ptr<uint8_t>(cvRound(startCenter.y))[cvRound(startCenter.x)] = 255;
//标记当前位置
cv::drawMarker(cc, cv::Point((*itv).x, (*itv).y), cv::Scalar(0, 255, 0, 255), cv::MARKER_DIAMOND, 5);
///<初始化追踪参数
//扫描步长
const double dMinorStep = 0.1;
//追踪长宽
const double trackLength = (double)tplWidth / 2., trackWidth = (double)tplHeight / 4.;
//起始扫描角度
const double startAngle = atan2((double)startCenter.y - (double)reelCenter.y, (double)startCenter.x - (double)reelCenter.x) * 180 / PI;
//起始扫描半径
const double startRadius = cv::norm(startCenter - reelCenter);
//偏移角度(元件尺寸)
const double dOffset = (2 * asin(2 * trackLength / (2 * startRadius))) * 180. / PI;
//优化开关
#define OPTIMIZE_ON true
#if OPTIMIZE_ON
//考虑作并行处理
tbb::parallel_invoke(
[&]
#endif
{
//< 顺时针追踪
//追踪中心
cv::Point2f trackCenter = cv::Point2f(startCenter.x, startCenter.y);
//追踪角度、半径
double trackAngle = startAngle, trackRadius = startRadius;
//元件本身角度
double trackOffset = dOffset;
//元件间间距
double partDist = (2 * asin(dChordL / (2 * trackRadius))) * 180 / PI;
//外接矩形顶点
cv::Point2f pts[4];
//开始追踪
bool trackEnd = true;
do
{
double begin0 = (double)cv::getTickCount();
bool found = true;
std::vector<Track> vParts;
for (double t = trackAngle + (trackOffset / 2.0 + partDist + trackOffset / 3.0); t < trackAngle + \
(trackOffset / 2.0 + partDist + trackOffset / 3.0) + trackOffset / 3.0; t += dMinorStep)
{
trackCenter.x = reelCenter.x + (float)trackRadius*(float)cos(t*c);
trackCenter.y = reelCenter.y + (float)trackRadius*(float)sin(t*c);
//计算旋转矩形
calcRotateRect(trackCenter, (float)t, (float)trackLength, (float)trackWidth, pts);
//模板匹配
double maxyyu; cv::Point2f maxyyuloc;
findTrackModel(srcPrev, tplMat, 90.0 - (t + 180.0), trackWidth, pts, (255 - backT), false, maxyyu, maxyyuloc, cv::noArray());
//最小匹配结果
if (maxyyu > 0.15)
{
//存放结果
vParts.push_back(Track(0, 0, maxyyu, cv::Point(cvRound(trackCenter.x), cvRound(trackCenter.y)), std::vector<cv::Point2f>()));
}
//测试标记
//cv::drawMarker(cc, cv::Point(cvRound(trackCenter.x), cvRound(trackCenter.y)), cv::Scalar(0, 165, 255, 255), 0, 5);
}
//如果为0大概率是背景
if (vParts.size() <= 0)
break;
//更新切线方向位置,由于这个方向是元件间隙不会有太大偏差
trackCenter = cv::Point2f((float)vParts[vParts.size() / 2].Pos.x, (float)vParts[vParts.size() / 2].Pos.y);
//理论元件位置
cv::Point2f trackCenterT(trackCenter.x, trackCenter.y);
//更新扫描角度
trackAngle = atan2((double)trackCenter.y - reelCenter.y, (double)trackCenter.x - reelCenter.x) * 180 / PI;
///<开始离心/向心扫描(横向由于间隔固定所以一般不会出现偏离的情况,除非料盘本身严重变形或者中心定位出问题)
calcRotateRect(trackCenter, (float)trackAngle, (float)trackLength, (float)trackWidth, pts);
//模板匹配/更新元件精确位置
double maxyyu;
//findTrackModel(srcPrev, tplMat, 90.0 - (trackAngle + 180.0), trackWidth, pts, (255 - backT), false, maxyyu, trackCenter, cv::noArray());
//进一步确认元件位置
bool trayEnd = false;
if (true) {
//考虑增加[-2,2]角度范围以应对料盘变形
trayEnd = findTrackModel(srcPrev, tplMat, 90.0 - (trackAngle + 180.0), trackWidth, pts, (255 - backT), true, maxyyu, trackCenter, binary);
}
//if (cvRound(trackCenter.x) == 336 && cvRound(trackCenter.y) == 536)
// std::cout << "" << std::endl;
//更新扫描半径
trackRadius = cv::norm(trackCenter - reelCenter);
//更新扫描角度
trackAngle = atan2((double)trackCenter.y - reelCenter.y, (double)trackCenter.x - reelCenter.x) * 180 / PI;
//更新偏移量(元件大小)
trackOffset = (2 * asin(2 * trackLength / (2 * trackRadius))) * 180 / PI;
//更新元件间角度
partDist = (2 * asin(dChordL / (2 * trackRadius))) * 180 / PI;
//计算实际元件区域
calcRotateRect(trackCenter, (float)trackAngle, (float)trackLength, (float)trackWidth, pts);
#ifdef _DEBUG
cv::Point2f ptsT[4];
calcRotateRect(trackCenter, (float)trackAngle, (float)trackLength, (float)trackWidth, ptsT);
if (!trayEnd)
{
//画出元件区域
for (int j = 0; j < 4; j++)
{
cv::line(cc, ptsT[j], ptsT[(j + 1) % 4], cv::Scalar(0, 0, 255, 255), 1);
}
}
#endif
//判断是否追踪终止(增加匹配分数小于0.18被判定不是元件)
if (trayEnd) {
//不再判断,大概率已经终止
found = false;
}
else if (trackMat.ptr<uint8_t>(cvRound(trackCenterT.y))[cvRound(trackCenterT.x)] == 255) {
//不再判断,大概率已经终止
found = false;
}
else if (trackMat.ptr<uint8_t>(cvRound(trackCenter.y))[cvRound(trackCenter.x)] == 255) {
//判断可能并未终止,遂采用理论位置作为下一个元件位置
trackCenter = trackCenterT;
//<更新追踪信息
//更新扫描半径
trackRadius = cv::norm(trackCenter - reelCenter);
//更新扫描角度
trackAngle = atan2((double)trackCenter.y - reelCenter.y, (double)trackCenter.x - reelCenter.x) * 180 / PI;
//更新偏移量(元件大小)
trackOffset = (2 * asin(2 * trackLength / (2 * trackRadius))) * 180 / PI;
//更新元件间角度
partDist = (2 * asin(dChordL / (2 * trackRadius))) * 180 / PI;
//计算理论元件区域
calcRotateRect(trackCenter, (float)trackAngle, (float)trackLength, (float)trackWidth, pts);
//标记为已追踪过
std::vector<cv::Point> ptPoly = { cv::Point(pts[0]),cv::Point(pts[1]) ,cv::Point(pts[2]) ,cv::Point(pts[3]) };
cv::fillConvexPoly(trackMat, ptPoly, cv::Scalar(255));
//标记计数
lbMat.ptr<uint8_t>(cvRound(trackCenter.y))[cvRound(trackCenter.x)] = 255;
//标记当前位置
cv::drawMarker(cc, trackCenter, cv::Scalar(0, 255, 0, 255), cv::MARKER_DIAMOND, 5);
//cv::drawMarker(cc, trackCenter, cv::Scalar(0, 0, 255, 255), 0, 5);
}
else
{
//标记为已追踪过
std::vector<cv::Point> ptPoly = { cv::Point(pts[0]),cv::Point(pts[1]) ,cv::Point(pts[2]) ,cv::Point(pts[3]) };
cv::fillConvexPoly(trackMat, ptPoly, cv::Scalar(255));
//标记计数
lbMat.ptr<uint8_t>(cvRound(trackCenter.y))[cvRound(trackCenter.x)] = 255;
//标记当前位置
cv::drawMarker(cc, trackCenter, cv::Scalar(0, 255, 0, 255), cv::MARKER_DIAMOND, 5);
//cv::drawMarker(cc, trackCenter, cv::Scalar(0, 0, 255, 255), 0, 5);
}
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularPartsE 追踪阶段被跳过执行...");
found = false;
}
//std::cout << "总体耗时:" << 1000 * (static_cast<double>(cv::getTickCount()) - begin0) / cv::getTickFrequency() << std::endl;
trackEnd = (!found);
} while (!trackEnd);
}
#if OPTIMIZE_ON
,
[&]
#endif
{
//< 逆时针追踪
//追踪起点
cv::Point2f trackCenter(startCenter.x, startCenter.y);
//起始扫描角度、半径
double trackAngle = startAngle, trackRadius = startRadius;
//元件本身角度
double trackOffset = dOffset;
//元件间间距
double partDist = (2 * asin(dChordL / (2 * trackRadius))) * 180 / PI;
//外接矩形
cv::Point2f pts[4];
//开始追踪
bool trackEnd = true;
//
do
{
bool found = true;
std::vector<Track> vParts;
for (double t = trackAngle - (trackOffset / 3.0 + partDist + trackOffset / 2.0); t > trackAngle - \
(trackOffset / 3.0 + partDist + trackOffset / 2.0) - trackOffset / 3.0; t -= dMinorStep)
{
trackCenter.x = float(reelCenter.x + trackRadius*cos(t*c));
trackCenter.y = float(reelCenter.y + trackRadius*sin(t*c));
//计算旋转矩形
calcRotateRect(trackCenter, (float)t, (float)trackLength, (float)trackWidth, pts);
//模板匹配
double maxyyu; cv::Point2f maxyyuloc;
findTrackModel(srcPrev, tplMat, 90.0 - (t + 180.0), trackWidth, pts, (255 - backT), false, maxyyu, maxyyuloc, cv::noArray());
//最小匹配结果
if (maxyyu > 0.15) {
//存放结果
vParts.push_back(Track(0, 0, maxyyu, cv::Point(cvRound(trackCenter.x), cvRound(trackCenter.y)), std::vector<cv::Point2f>()));
}
//测试标记
//cv::drawMarker(cc, cv::Point(cvRound(trackCenter.x), cvRound(trackCenter.y)), cv::Scalar(0, 165, 255, 255), 0, 5);
}
if (vParts.size() == 0)
break;
//更新切线方向位置,由于这个方向是元件间隙不会有太大偏差
trackCenter = cv::Point2f((float)vParts[vParts.size() / 2].Pos.x, (float)vParts[vParts.size() / 2].Pos.y);
//理论元件区域
cv::Point2f trackCenterT(trackCenter.x, trackCenter.y);
//更新扫描角度
trackAngle = atan2((double)trackCenter.y - reelCenter.y, (double)trackCenter.x - reelCenter.x) * 180 / PI;
///<开始离心/向心扫描(横向由于间隔固定所以一般不会出现偏离的情况,除非料盘本身严重变形或者中心定位出问题)
calcRotateRect(trackCenter, (float)trackAngle, (float)trackLength, (float)trackWidth, pts);
//模板匹配/更新元件精确位置+判断
double maxyyu;
//findTrackModel(srcPrev, tplMat, 90.0 - (trackAngle + 180.0), trackWidth, pts, (255 - backT), false, maxyyu, trackCenter, cv::noArray());
//
bool trayEnd = false;
if (true) {
//考虑增加[-2,2]角度范围以应对料盘变形
trayEnd = findTrackModel(srcPrev, tplMat, 90.0 - (trackAngle + 180.0), trackWidth, pts, (255 - backT), true, maxyyu, trackCenter, binary);
}
//if (cvRound(trackCenter.x) == 1356 && cvRound(trackCenter.y) == 1812){
// std::cout << "xx" << std::endl;
//}
//更新扫描半径
trackRadius = cv::norm(trackCenter - reelCenter);
//更新扫描角度
trackAngle = atan2((double)trackCenter.y - reelCenter.y, (double)trackCenter.x - reelCenter.x) * 180 / PI;
//更新偏移量
trackOffset = (2 * asin(2 * trackLength / (2 * trackRadius))) * 180 / PI;
//更新元件间角度
partDist = (2 * asin(dChordL / (2 * trackRadius))) * 180 / PI;
//计算实际元件位置
calcRotateRect(trackCenter, (float)trackAngle, (float)trackLength, (float)trackWidth, pts);
#ifdef _DEBUG
cv::Point2f ptsT[4];
calcRotateRect(trackCenter, (float)trackAngle, (float)trackLength, (float)trackWidth, ptsT);
if (!trayEnd)
{
//画出元件区域
for (int j = 0; j < 4; j++)
{
cv::line(cc, ptsT[j], ptsT[(j + 1) % 4], cv::Scalar(0, 0, 255, 255), 1);
}
}
#endif
//判断是否追踪终止(增加匹配分数小于0.18被判定不是元件)
if (trayEnd) {
//不再判断,大概率已经终止
found = false;
}
else if (trackMat.ptr<uint8_t>(cvRound(trackCenterT.y))[cvRound(trackCenterT.x)] == 255) {
//不再判断,大概率已经终止
found = false;
}
else if (trackMat.ptr<uint8_t>(cvRound(trackCenter.y))[cvRound(trackCenter.x)] == 255) {
//判断可能并未终止,遂采用理论位置作为下一个元件位置
trackCenter = trackCenterT;
///<更新追踪信息
//更新扫描半径
trackRadius = cv::norm(trackCenter - reelCenter);
//更新扫描角度
trackAngle = atan2((double)trackCenter.y - reelCenter.y, (double)trackCenter.x - reelCenter.x) * 180 / PI;
//更新偏移量
trackOffset = (2 * asin(2 * trackLength / (2 * trackRadius))) * 180 / PI;
//更新元件间角度
partDist = (2 * asin(dChordL / (2 * trackRadius))) * 180 / PI;
//计算理论元件位置
calcRotateRect(trackCenter, (float)trackAngle, (float)trackLength, (float)trackWidth, pts);
//标记为已追踪过
std::vector<cv::Point> ptPoly = { cv::Point(pts[0]),cv::Point(pts[1]) ,cv::Point(pts[2]) ,cv::Point(pts[3]) };
cv::fillConvexPoly(trackMat, ptPoly, cv::Scalar(255));
//标记计数
lbMat.ptr<uint8_t>(cvRound(trackCenter.y))[cvRound(trackCenter.x)] = 255;
//标记当前位置
cv::drawMarker(cc, trackCenter, cv::Scalar(0, 255, 0, 255), cv::MARKER_DIAMOND, 5);
//cv::drawMarker(cc, trackCenter, cv::Scalar(0, 0, 255, 255), 0, 5);
}
else
{
//标记为已追踪过
std::vector<cv::Point> ptPoly = { cv::Point(pts[0]),cv::Point(pts[1]) ,cv::Point(pts[2]) ,cv::Point(pts[3]) };
cv::fillConvexPoly(trackMat, ptPoly, cv::Scalar(255));
//标记计数
lbMat.ptr<uint8_t>(cvRound(trackCenter.y))[cvRound(trackCenter.x)] = 255;
//标记当前位置
cv::drawMarker(cc, trackCenter, cv::Scalar(0, 255, 0, 255), cv::MARKER_DIAMOND, 5);
//cv::drawMarker(cc, trackCenter, cv::Scalar(0, 0, 255, 255), 0, 5);
}
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularPartsE 追踪阶段被跳过执行...");
found = false;
}
trackEnd = (!found);
} while (!trackEnd);
}
#if OPTIMIZE_ON
);
#endif
}
//计数
int reelNum = cv::countNonZero(lbMat);
//画图显示
std::string text = "Reel Number = " + std::to_string(reelNum);
cv::putText(cc, text, cv::Point(35, 35), 0, 1.0, cv::Scalar(0, 140, 255, 255), 2);
//<输出结果
const int SizeConst = 4;
//<输出计数结果标记图像
{
memset(ipReelNum, 0, SizeConst);
ipReelNum[0] = reelNum;
tpDstImg->iWidth = cc.cols; tpDstImg->iHeight = cc.rows; tpDstImg->iDepth = cc.depth(); tpDstImg->iChannels = cc.channels();
//内存尺寸
int _Size = tpDstImg->iWidth*tpDstImg->iHeight*tpDstImg->iChannels * sizeof(uint8_t);
//分配初始化内存
tpDstImg->vpImage = (uint8_t *)malloc(_Size);
if (NULL == tpDstImg->vpImage)
return FUNC_NOT_ENOUGH_MEM;
memset(tpDstImg->vpImage, 0, _Size);
//拷贝数据
memcpy(tpDstImg->vpImage, cc.data, _Size);
}
return FUNC_OK;
}
int eyemAchvMatchMat(EyemImage tpImage, EyemRect tpRoi, EyemImage *tpDstImg)
{
cv::Mat src = cv::Mat(tpImage.iHeight, tpImage.iWidth, MAKETYPE(tpImage.iDepth, tpImage.iChannels), tpImage.vpImage).clone();
if (src.empty()) {
return FUNC_IMAGE_NOT_EXIST;
}
//转单通道
if (src.channels() != 1)
cv::cvtColor(src, src, cv::COLOR_BGR2GRAY);
//跳过执行
if (killProcessID == 0) {
logger.t("eyemCountObjectIrregularPartsE 初始阶段被跳过执行...");
return FUNC_CANNOT_CALC;
}
//图像裁剪
src = src(cv::Rect(tpRoi.iXs, tpRoi.iYs, tpRoi.iWidth, tpRoi.iHeight)).clone();
//image size
int X = src.cols, Y = src.rows;
//去除局部量斑影响(默认亮斑尺寸不会大于15个像素)
cv::Mat srcTmp;
cv::morphologyEx(src, srcTmp, cv::MORPH_ERODE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(15, 15)));
//去除黑斑影响
int m = cvRound(cv::mean(src)[0]);
srcTmp.forEach<uint16_t>([&](uint16_t& pixel, const int *pos)->void {
pixel = pixel == 0 ? m : pixel;
});
//图像增强
double min, max;
cv::Point maxId;
cv::minMaxLoc(srcTmp, &min, &max, NULL, &maxId);
src.convertTo(src, CV_64FC1);
src -= min;
src /= (max - min);
src *= 65535;
src.convertTo(src, CV_16UC1);
cv::Mat src8U;
src.convertTo(src8U, CV_8UC1, 1 / 255.);
//显示结果图像
cv::Mat cc;
cv::cvtColor(src8U, cc, cv::COLOR_GRAY2BGRA);
//设置bins
const int histSize = 17;
//range of values
float range[] = { 0,255 };
const float* histRange = { range };
//计算直方图
cv::Mat hist;
cv::calcHist(&src8U, 1, 0, cv::Mat(), hist, 1, &histSize, &histRange);
//计算背景
int maxIdx[2] = { 255,255 };
cv::minMaxIdx(hist, NULL, NULL, NULL, maxIdx);
//背景阈值
int backThresh = 15 * cvRound(((double)maxIdx[0] - 2));//正常-2
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 (src8U.ptr<uint8_t>(y)[x] >= backThresh) {
src8U.ptr<uint8_t>(y)[x] = backThresh;
}
}
}
});
//方便显示
cc += cv::Scalar((162 - backThresh), (162 - backThresh), (162 - backThresh));
//inv
cv::bitwise_not(src8U, src8U);
cv::Mat binary;
cv::threshold(src8U, binary, (255 - backThresh), 255, cv::THRESH_BINARY);
//连接在一起
cv::morphologyEx(binary, binary, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(45, 45)));
//find the pallet
std::vector<std::vector<cv::Point>> contoursFilter;
cv::findContours(binary, contoursFilter, cv::RETR_TREE, cv::CHAIN_APPROX_NONE);
//填充内部确定料盘
cv::Mat image = cv::Mat::zeros(src8U.size(), CV_8UC1);
for (int i = 0; i < contoursFilter.size(); i++)
{
if (cv::contourArea(contoursFilter[i]) > 100000)
{
cv::drawContours(image, contoursFilter, i, cv::Scalar(255), -1);
}
}
cv::bitwise_not(src8U, src8U);
//剩下即料盘区域(面积大于100000均认为是料盘)
cv::findContours(image, contoursFilter, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
//区分多个料盘
struct TrayPos
{
int iDir = -1;//0左上1左下2右下3右上
double dBackThresh;
bool bSorted;
cv::Point2f Center;
cv::Mat Tray;
TrayPos() {};
TrayPos(cv::Point2f center, cv::Mat tray, bool bSorted, double dBackThresh) :Center(center), Tray(tray), bSorted(bSorted), dBackThresh(dBackThresh) {}
};
std::vector <TrayPos> trays; std::vector<cv::Mat> matchMats;
for (int i = 0; i < contoursFilter.size(); i++)
{
//定位中心
cv::Moments mu = cv::moments(contoursFilter[i]);
cv::Point reelCenter(cvRound(mu.m10 / mu.m00), cvRound(mu.m01 / mu.m00));
//掩膜
cv::Mat trayMask = cv::Mat::zeros(Y, X, CV_8UC1);
cv::drawContours(trayMask, contoursFilter, i, cv::Scalar(255), -1);
//
cv::Mat tray = cv::Mat(Y, X, CV_8UC1, backThresh);
src8U.copyTo(tray, trayMask);
trays.push_back(TrayPos(reelCenter, tray, false, backThresh));
//获取局部图像
cv::Rect bbox = cv::boundingRect(contoursFilter[i]);
cv::Point pt(bbox.tl().x + bbox.width / 2, bbox.tl().y);
cv::Rect limit(cv::Point2i(pt.x - 112, pt.y), cv::Point2i(pt.x + 112, pt.y + 224));
matchMats.push_back(cc(limit).clone());
}
if (matchMats.empty()) {
return FUNC_CANNOT_CALC;
}
cv::Mat matchMat;
cv::cvtColor(matchMats[0], matchMat, cv::COLOR_BGRA2BGR);
//<输出结果图像
tpDstImg->iWidth = matchMat.cols; tpDstImg->iHeight = matchMat.rows; tpDstImg->iDepth = matchMat.depth(); tpDstImg->iChannels = matchMat.channels();
//内存尺寸
int _Size = tpDstImg->iWidth*tpDstImg->iHeight*tpDstImg->iChannels * sizeof(uint8_t);
//分配初始化内存
tpDstImg->vpImage = (uint8_t *)malloc(_Size);
if (NULL == tpDstImg->vpImage)
return FUNC_NOT_ENOUGH_MEM;
memset(tpDstImg->vpImage, 0, _Size);
//拷贝数据
memcpy(tpDstImg->vpImage, matchMat.data, _Size);
return FUNC_OK;
}
int eyemAchvTemplateImage(EyemImage tpImage, EyemRect tpRoi, EyemImage *tpDstImg)
{
cv::Mat image = cv::Mat(tpImage.iHeight, tpImage.iWidth, MAKETYPE(tpImage.iDepth, tpImage.iChannels), tpImage.vpImage).clone();
//检查文件是否存在
if (image.empty())
return FUNC_IMAGE_NOT_EXIST;
//转单通道图像
if (image.channels() != 1)
cv::cvtColor(image, image, cv::COLOR_BGR2GRAY);
//范围
image = image(cv::Rect(tpRoi.iXs, tpRoi.iYs, tpRoi.iWidth, tpRoi.iHeight));
//图像尺寸
int X = image.cols, Y = image.rows;
//去除局部量斑影响(默认亮斑尺寸不会大于15个像素)
cv::Mat srcTmp;
cv::morphologyEx(image, srcTmp, cv::MORPH_ERODE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(15, 15)));
//去除局部黑斑影响
int m = cvRound(cv::mean(image)[0]);
srcTmp.forEach<uint16_t>([&](uint16_t& pixel, const int *pos)->void {
pixel = pixel == 0 ? m : pixel;
});
//图像增强
double min, max;
cv::minMaxLoc(srcTmp, &min, &max);
image.convertTo(image, CV_64FC1);
image -= min;
image /= (max - min);
image *= 65535;
image.convertTo(image, CV_16UC1);
//转8位灰度图
cv::Mat srcPrev;
image.convertTo(srcPrev, CV_8UC1, 1 / 255.);
//设定bin数目
const int histSize = 17;
//设定取值范围
float range[] = { 0,255 };
const float* histRange = { range };
//计算直方图
cv::Mat hist;
cv::calcHist(&srcPrev, 1, 0, cv::Mat(), hist, 1, &histSize, &histRange);
//计算背景像素
int maxIdx[2] = { 255,255 };
cv::minMaxIdx(hist, NULL, NULL, NULL, maxIdx);
//背景阈值
int backT = 15 * (maxIdx[0] - 2);
//去掉背景
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 (srcPrev.ptr<uint8_t>(y)[x] >= backT)
{
srcPrev.ptr<uint8_t>(y)[x] = backT;
}
}
}
});
///<输出计数结果标记图像
{
tpDstImg->iWidth = srcPrev.cols; tpDstImg->iHeight = srcPrev.rows; tpDstImg->iDepth = srcPrev.depth(); tpDstImg->iChannels = srcPrev.channels();
//内存尺寸
int _Size = tpDstImg->iWidth*tpDstImg->iHeight*tpDstImg->iChannels * sizeof(uint8_t);
//分配初始化内存
tpDstImg->vpImage = (uint8_t *)malloc(_Size);
if (NULL == tpDstImg->vpImage)
return FUNC_NOT_ENOUGH_MEM;
memset(tpDstImg->vpImage, 0, _Size);
//拷贝数据
memcpy(tpDstImg->vpImage, srcPrev.data, _Size);
}
return FUNC_OK;
}
int eyemCreateTemplateModel(EyemImage tpImage, EyemRect tpRoi, double dMinScore, const char *ccTplName)
{
cv::Mat image = cv::Mat(tpImage.iHeight, tpImage.iWidth, MAKETYPE(tpImage.iDepth, tpImage.iChannels), tpImage.vpImage).clone();
if (image.empty())
return FUNC_IMAGE_NOT_EXIST;
cv::Mat tplMat = image(cv::Rect(tpRoi.iXs, tpRoi.iYs, tpRoi.iWidth, tpRoi.iHeight)).clone();
//反转
cv::bitwise_not(tplMat, tplMat);
//内存尺寸(将信息添加到图像后面)
int _Size = tplMat.cols*tplMat.rows*tplMat.channels() * sizeof(uint8_t);
//模板信息
std::string hint = std::to_string(tpRoi.iXs) + "," + std::to_string(tpRoi.iYs) + "," \
+ std::to_string(tpRoi.iWidth) + "," + std::to_string(tpRoi.iHeight) + "," + std::to_string(dMinScore);
std::string szSize = std::to_string(_Size);
std::string head = std::string(8 - szSize.length(), '0') + szSize;
unsigned char *_Data = new unsigned char[_Size + hint.size() + 8];
if (NULL == _Data)
return FUNC_NOT_ENOUGH_MEM;
//拷贝头数据
memcpy(_Data, head.c_str(), 8);
//拷贝图像数据
memcpy(_Data + 8, tplMat.data, _Size);
//拷贝图像信息数据
memcpy(_Data + _Size + 8, hint.c_str(), hint.size());
//写入本地
std::ofstream ostream(ccTplName, std::ios::binary);
ostream.write(reinterpret_cast<const char *>(_Data), _Size + hint.size() + 8);
//释放资源
delete[] _Data;
_Data = NULL;
//关闭流
ostream.close();
return FUNC_OK;
}
int eyemInitModel(const char *ccTplName, IntPtr *hModelID)
{
std::string logModule = "";
logModule += __func__;
logModule += "(" + std::to_string(*(uint32_t *)(&std::this_thread::get_id())) + "):";
logger.t(logModule + "初始化模板...");
//获取文件路径
std::vector<std::string> fileNames;
cv::glob(ccTplName, fileNames);
logger.t(logModule + "获取文件名...");
//载入所有模板
std::vector<EyemModelID> *tpModelID = new std::vector<EyemModelID>();
//判断文件
if (fileNames.size() <= 0) {
//输出
*hModelID = reinterpret_cast<IntPtr>(tpModelID);
return FUNC_OK;
}
for (std::vector<std::string>::iterator it = fileNames.begin(); it != fileNames.end(); ++it)
{
std::string fileName = (*it);
cv::Mat tplMat; double matchDeg;
try
{
logger.t(logModule + "开始从本地加载模板文件...");
loadTrackModel(fileName.c_str(), tplMat, cv::Point(), matchDeg, "eyemInitModel");
}
catch (...) {
logger.t(logModule + "从本地加载模板文件异常...");
return FUNC_CANNOT_CALC;
}
if (!tplMat.empty()) {
cv::Mat _tplMat;
cv::bitwise_not(tplMat, _tplMat);
//载入模板
EyemModelID modelID;
int _Size = tplMat.cols*tplMat.rows * sizeof(unsigned char);
//数据
logger.t(logModule + "分配模板图像内存...");
modelID.vpImage = (unsigned char *)malloc(_Size);
if (NULL == modelID.vpImage)
return FUNC_NOT_ENOUGH_MEM;
//拷贝数据
logger.t(logModule + "拷贝模板数据...");
memcpy(modelID.vpImage, _tplMat.data, _Size);
//位置
modelID.iXs = modelID.iYs = 0;
//宽、高
modelID.iWidth = tplMat.cols; modelID.iHeight = tplMat.rows;
//匹配分数
modelID.dMatchDeg = matchDeg;
//名称?会导致内存泄露吗
logger.t(logModule + "分配模板文件名内存...");
modelID.lpszName = (char *)CoTaskMemAlloc(128);
if (NULL != modelID.lpszName)
{
char file[128] = { 0 };
sprintf_s(file, "%s", fileName.c_str());
strcpy(modelID.lpszName, file);
}
else return FUNC_NOT_ENOUGH_MEM;
//压入容器末尾
logger.t(logModule + "将模板压入容器...");
tpModelID->push_back(modelID);
}
}
//输出
*hModelID = reinterpret_cast<IntPtr>(tpModelID);
return FUNC_OK;
}
int eyemAchvModelByName(const char *ccTplName, IntPtr hModelID, EyemModelID &tpModelID)
{
if (NULL == hModelID)
return FUNC_CANNOT_CALC;
std::vector<EyemModelID> *tpModelIDs = reinterpret_cast<std::vector<EyemModelID>*>(hModelID);
for (std::vector<EyemModelID>::iterator it = tpModelIDs->begin(); it != tpModelIDs->end(); ++it) {
if (std::strcmp((*it).lpszName, ccTplName) == 0) {
EyemModelID modelID = (*it);
tpModelID.dMatchDeg = modelID.dMatchDeg; tpModelID.iHeight = modelID.iHeight; tpModelID.iWidth = modelID.iWidth;
tpModelID.iXs = tpModelID.iYs = 0;
tpModelID.lpszName = modelID.lpszName;
tpModelID.vpImage = modelID.vpImage;
break;
}
}
return FUNC_OK;
}
int eyemInsertModel(IntPtr hModelID, const char *ccTplName)
{
std::string logModule = "";
logModule += __func__;
logModule += "(" + std::to_string(*(uint32_t *)(&std::this_thread::get_id())) + "):";
if (NULL == hModelID)
return FUNC_CANNOT_CALC;
logger.t(logModule + "从指针获取模板对象...");
std::vector<EyemModelID> *tpModelID = reinterpret_cast<std::vector<EyemModelID>*>(hModelID);
//判断是否重复
for (std::vector<EyemModelID>::iterator it = tpModelID->begin(); it != tpModelID->end(); ++it) {
if (std::strcmp((*it).lpszName, ccTplName) == 0) {
return FUNC_OK;
}
}
//加载指定模板
cv::Mat tplMat; double matchDeg;
try
{
logger.t(logModule + "开始从本地加载模板文件...");
loadTrackModel(ccTplName, tplMat, cv::Point(), matchDeg, "eyemInsertModel");
}
catch (...) {
logger.t(logModule + "从本地加载模板文件异常...");
return FUNC_CANNOT_CALC;
}
//插到容器末尾
if (!tplMat.empty()) {
cv::Mat _tplMat;
cv::bitwise_not(tplMat, _tplMat);
//载入模板
EyemModelID modelID;
int _Size = tplMat.cols*tplMat.rows * sizeof(unsigned char);
//数据
logger.t(logModule + "分配图像内存...");
modelID.vpImage = (unsigned char *)malloc(_Size);
if (NULL == modelID.vpImage)
return FUNC_NOT_ENOUGH_MEM;
//拷贝数据
logger.t(logModule + "拷贝图像数据...");
memcpy(modelID.vpImage, _tplMat.data, _Size);
//位置
modelID.iXs = modelID.iYs = 0;
//宽、高
modelID.iWidth = tplMat.cols; modelID.iHeight = tplMat.rows;
//匹配分数
modelID.dMatchDeg = matchDeg;
//名称
logger.t(logModule + "分配模板文件名内存...");
modelID.lpszName = (char *)CoTaskMemAlloc(128);
if (NULL != modelID.lpszName)
{
char file[128] = { 0 };
sprintf_s(file, "%s", ccTplName);
strcpy(modelID.lpszName, file);
}
else {
return FUNC_NOT_ENOUGH_MEM;
}
//压入容器末尾
logger.t(logModule + "将模板压入容器...");
tpModelID->push_back(modelID);
}
else {
return FUNC_CANNOT_CALC;
}
return FUNC_OK;
}
int eyemRemoveModelByName(IntPtr hModelID, const char *ccTplName)
{
if (NULL == hModelID)
return FUNC_CANNOT_CALC;
std::vector<EyemModelID> *tpModelID = reinterpret_cast<std::vector<EyemModelID>*>(hModelID);
//遍历移除
for (std::vector<EyemModelID>::iterator it = tpModelID->begin(); it != tpModelID->end(); ++it) {
EyemModelID *modelID = &(*it);
if (std::strcmp((const char *)modelID->lpszName, ccTplName) == 0) {
//释放资源
modelID->dMatchDeg = modelID->iHeight = modelID->iWidth = modelID->iXs = modelID->iYs = 0;
//释放内容
CoTaskMemFree((LPVOID)modelID->lpszName);
free(modelID->vpImage);
//
modelID->vpImage = NULL; modelID->lpszName = NULL;
//删除
tpModelID->erase(it);
break;
}
}
return FUNC_OK;
}
int eyemRemoveModelByID(IntPtr hModelID, const int iTplID)
{
return FUNC_OK;
}
int eyemMatchTemplateModel(EyemImage tpImage, IntPtr hModelID, char **lpszTplName)
{
cv::Mat image = cv::Mat(tpImage.iHeight, tpImage.iWidth, MAKETYPE(tpImage.iDepth, tpImage.iChannels), tpImage.vpImage).clone();
//判断图像是否存在
if (image.empty() || NULL == hModelID)
return FUNC_IMAGE_NOT_EXIST;
//反转
cv::bitwise_not(image, image);
struct Track {
double dMatchDeg;
std::string tplName;
cv::Mat tplMat;
Track() {};
Track(double dMatchDeg, std::string tplName, cv::Mat tplMat) :dMatchDeg(dMatchDeg), tplName(tplName), tplMat(tplMat) {};
bool operator >(const Track &te)const
{
return dMatchDeg > te.dMatchDeg;
}
};
//模板文件
std::vector<EyemModelID> *tpModelIDs = reinterpret_cast<std::vector<EyemModelID>*>(hModelID);
//载入所有模板
std::vector<Track> tplMats;
for (std::vector<EyemModelID>::iterator it = tpModelIDs->begin(); it != tpModelIDs->end(); ++it)
{
EyemModelID tpModelID = (*it);
cv::Mat tplMat;
tplMat = cv::Mat(tpModelID.iHeight, tpModelID.iWidth, CV_8UC1, tpModelID.vpImage);
//模板取反
cv::Mat _tplMat;
cv::bitwise_not(tplMat, _tplMat);
if (!tplMat.empty())
tplMats.push_back(Track(tpModelID.dMatchDeg, tpModelID.lpszName, _tplMat));
}
//模板文件不存在
if (tplMats.size() <= 0)
return FUNC_CANNOT_CALC;
const float icvDirections[4] = { 0 , 90 , 180 , -90 };
//遍历所有模板选择最佳匹配模板
cv::parallel_for_(cv::Range(0, (int)tplMats.size()), [&](const cv::Range& range)->void {
for (int tpl = range.start; tpl < range.end; tpl++)
{
double sumMatchDeg = 0.0; int sumMatchNum = 0;
//模板匹配(仅处理料盘区域以提高速度)
cv::Mat tplMat = tplMats[tpl].tplMat;
cv::Mat tplResult;
cv::matchTemplate(image, getTplMat(tplMats[tpl].tplMat, icvDirections[0], 0), tplResult, cv::TM_CCOEFF_NORMED);
//分数大于一定分数才当作元件处理
cv::Mat tplResult0 = cv::Mat(tplResult > tplMats[tpl].dMatchDeg);
//连通域分析
cv::Mat labels, stats, centroids;
int nccomps = cv::connectedComponentsWithStats(tplResult0, labels, stats, centroids);
if (nccomps > 1) {
//累加分数
double maxVal = 0.;
for (int i = 1; i < nccomps; i++) {
sumMatchNum++;
cv::minMaxLoc(tplResult(cv::Rect(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])), NULL, &maxVal, NULL, NULL);
sumMatchDeg += maxVal;
}
}
if (sumMatchNum != 0) {
tplMats[tpl].dMatchDeg = sumMatchDeg / (double)sumMatchNum;
}
else {
tplMats[tpl].dMatchDeg = 0.0;
}
}
});
//计算最佳匹配模板
std::sort(tplMats.begin(), tplMats.end(), std::greater<Track>());
//最匹配模板
std::string bestMatch = "";
int select = 0;
do
{
bestMatch += tplMats[select].tplName + ",";
select++;
} while (select < 5 && select < tplMats.size());
//输出结果
*lpszTplName = (char *)CoTaskMemAlloc(bestMatch.length() + 1);
if (NULL != lpszTplName)
{
strcpy(*lpszTplName, bestMatch.c_str());
}
else {
return FUNC_NOT_ENOUGH_MEM;
}
return FUNC_OK;
}
int eyemReleaseModel(IntPtr &hModelID)
{
if (NULL == hModelID)
return FUNC_OK;
std::vector<EyemModelID> *tpModelID = reinterpret_cast<std::vector<EyemModelID>*>(hModelID);
for (std::vector<EyemModelID>::iterator it = tpModelID->begin(); it != tpModelID->end(); ++it) {
EyemModelID *modelID = &(*it);
modelID->dMatchDeg = modelID->iHeight = modelID->iWidth = modelID->iXs = modelID->iYs = 0;
//释放内容
CoTaskMemFree((LPVOID)modelID->lpszName);
free(modelID->vpImage);
}
//清空容器
tpModelID->clear();
//释放容器
delete tpModelID;
tpModelID = NULL; hModelID = NULL;
return FUNC_OK;
}
int eyemTrackFeature(EyemImage tpRefImg, EyemImage tpNextImg, EyemRect3 *tpRois, int iRoiNum, int *ipResults, EyemImage *tpDstImg)
{
cv::Mat refImg = cv::Mat(tpRefImg.iHeight, tpRefImg.iWidth, MAKETYPE(tpRefImg.iDepth, tpRefImg.iChannels), tpRefImg.vpImage).clone();
cv::Mat nextImg = cv::Mat(tpNextImg.iHeight, tpNextImg.iWidth, MAKETYPE(tpNextImg.iDepth, tpNextImg.iChannels), tpNextImg.vpImage).clone();
if (refImg.empty() | nextImg.empty())
return FUNC_IMAGE_NOT_EXIST;
//显示图像
cv::Mat showMat;
showMat = nextImg.clone();
//转灰度图像
if (refImg.channels() != 1) {
cv::cvtColor(refImg, refImg, cv::COLOR_BGR2GRAY);
}
if (nextImg.channels() != 1) {
cv::cvtColor(nextImg, nextImg, cv::COLOR_BGR2GRAY);
}
cv::Mat dst;
cv::absdiff(nextImg, refImg, dst);
cv::Mat binary;
cv::threshold(dst, binary, 25, 255, cv::THRESH_BINARY);
for (int i = 0; i < iRoiNum; i++)
{
cv::Mat labels, stats, centroids;
int nccomps = cv::connectedComponentsWithStats(binary(cv::Rect(tpRois[i].iXs, tpRois[i].iYs, tpRois[i].iWidth, tpRois[i].iHeight)), \
labels, stats, centroids);
//判断结果
if (((double)cv::countNonZero(labels) / (double(tpRois[i].iWidth*(double)tpRois[i].iHeight))) > tpRois[i].dVar)
{
ipResults[i] = 1;
}
else
ipResults[i] = 0;
//寻找轮廓
std::vector<std::vector<cv::Point>> contours;
cv::findContours(binary(cv::Rect(tpRois[i].iXs, tpRois[i].iYs, tpRois[i].iWidth, tpRois[i].iHeight)), contours, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE);
//画图
for (int j = 0; j < contours.size(); j++)
{
cv::drawContours(showMat, contours, j, cv::Scalar(0, 0, 255), 3, 8, cv::noArray(), 2147483647, cv::Point(tpRois[i].iXs, tpRois[i].iYs));
}
}
//<输出结果图像
{
tpDstImg->iWidth = showMat.cols; tpDstImg->iHeight = showMat.rows; tpDstImg->iDepth = showMat.depth(); tpDstImg->iChannels = showMat.channels();
//内存尺寸
int _Size = tpDstImg->iWidth*tpDstImg->iHeight*tpDstImg->iChannels * sizeof(uint8_t);
//分配初始化内存
tpDstImg->vpImage = (uint8_t *)malloc(_Size);
if (NULL == tpDstImg->vpImage)
return FUNC_NOT_ENOUGH_MEM;
memset(tpDstImg->vpImage, 0, _Size);
//拷贝数据
memcpy(tpDstImg->vpImage, showMat.data, _Size);
}
return FUNC_OK;
}
int eyemAOIForTSAV(EyemImage tpRefImg, EyemImage tpNextImg, EyemRect3 *tpRois, int iRoiNum)
{
return FUNC_OK;
}
int eyemMarkerTracing(EyemImage tpImage, EyemHSVModel tpHSVModel, EyemOcsFXYR *tpCircle, EyemImage *tpDstImg, bool bHighAccuracy)
{
cv::Mat image = cv::Mat(tpImage.iHeight, tpImage.iWidth, MAKETYPE(tpImage.iDepth, tpImage.iChannels), tpImage.vpImage).clone();
if (image.empty())
return FUNC_IMAGE_NOT_EXIST;
const int X = image.cols; const int Y = image.rows;
int incn = image.channels();
if (incn > 3) {
cv::cvtColor(image, image, cv::COLOR_BGRA2BGR);
}
else if (incn == 1) {
cv::cvtColor(image, image, cv::COLOR_GRAY2BGR);
}
//滤波
cv::blur(image, image, cv::Size(5, 5));
//用于显示
cv::Mat cc = image.clone();
//转hsv空间
cv::Mat imgGray;
cv::cvtColor(image, imgGray, cv::COLOR_BGR2HSV);
//红色比较特殊,分两个区间
cv::Mat mask1, mask2(cv::Size(X, Y), CV_8UC1, cv::Scalar(0));
cv::inRange(imgGray, cv::Scalar(tpHSVModel.dpRangeL[0], tpHSVModel.dpRangeL[1], tpHSVModel.dpRangeL[2]),
cv::Scalar(tpHSVModel.dpRangeU[0], tpHSVModel.dpRangeU[1], tpHSVModel.dpRangeU[2]), mask1);
//多个分割阈值
if ((tpHSVModel.dpRangeLExt[0] + tpHSVModel.dpRangeLExt[1] + tpHSVModel.dpRangeLExt[2]) != 0 ||
(tpHSVModel.dpRangeUExt[0] + tpHSVModel.dpRangeUExt[1] + tpHSVModel.dpRangeUExt[2]) != 0) {
cv::inRange(imgGray, cv::Scalar(tpHSVModel.dpRangeLExt[0], tpHSVModel.dpRangeLExt[1], tpHSVModel.dpRangeLExt[2]),
cv::Scalar(tpHSVModel.dpRangeUExt[0], tpHSVModel.dpRangeUExt[1], tpHSVModel.dpRangeUExt[2]), mask2);
}
//合并
cv::Mat maskj;
cv::bitwise_or(mask1, mask2, maskj);
//去掉干扰
cv::morphologyEx(maskj, maskj, cv::MORPH_OPEN, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)));
//测试用,局部用RBG分割
cv::Mat labels, stats, centroids;
int nccomps = cv::connectedComponentsWithStats(maskj, labels, stats, centroids);
//过滤连通域面积及长/宽比例不符合的,允许50%误差
std::vector<uchar> colors(nccomps + 1, 0);
for (int i = 1; i < nccomps; i++) {
colors[i] = 255;
double minSize = cv::min(stats.ptr<int>(i)[cv::CC_STAT_WIDTH], stats.ptr<int>(i)[cv::CC_STAT_HEIGHT]); double dRate = (double)stats.ptr<int>(i)[cv::CC_STAT_WIDTH] / (double)stats.ptr<int>(i)[cv::CC_STAT_HEIGHT];
if (minSize < 24 || !(dRate > 0.75&&dRate < 1.25))
{
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 = maskj.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>> contours, contourFilter;
cv::findContours(maskj, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
for (auto&contour : contours) {
cv::Rect bbox = cv::boundingRect(contour);
int minSize = cv::min(bbox.height, bbox.width);
cv::Rect limRec = cv::Rect(cv::Point2i(bbox.tl().x - minSize, bbox.tl().y - minSize),
cv::Point2i(bbox.br().x + minSize, bbox.br().y + minSize))&cv::Rect(0, 0, X, Y);
cv::Mat limit = image(limRec).clone();
//过滤
std::vector<cv::Point> approx;
float arcL = (float)cv::arcLength(cv::Mat(contour), true);
cv::approxPolyDP(cv::Mat(contour), approx, arcL*0.01, true);
if (approx.size() > 5) {
cv::Rect bbox = cv::boundingRect(contour);
if (MIN(bbox.width, bbox.height) > 24 && ((float)bbox.width / (float)bbox.height) > 0.75 && \
((float)bbox.width / (float)bbox.height) < 1.25) {
//圆度
double afa = 4.0f*CV_PI*cv::contourArea(contour, false) / std::pow(arcL, 2);
if (afa > 0.45) {
contourFilter.push_back(contour);
}
}
}
}
struct AFA {
double dMatchDeg;
EyemOcsDXYR tpCircle;
AFA() {};
AFA(double dMatchDeg, EyemOcsDXYR tpCircle) :dMatchDeg(dMatchDeg), tpCircle(tpCircle) {};
bool operator >(const AFA &te)const
{
return dMatchDeg > te.dMatchDeg;
}
bool operator <(const AFA &te)const
{
return dMatchDeg < te.dMatchDeg;
}
};
if (contourFilter.empty()) {
return FUNC_FAILED_DETECT;
}
bool typeCircle = true;
if (typeCircle) {
std::vector<AFA> AFAs;
//画图
for (auto&contour : contourFilter) {
std::vector<EyemOcsDXY> taPoints;
for (int n = 0; n < contour.size(); n++) {
EyemOcsDXY taPoint;
taPoint.dX = (double)contour[n].x;
taPoint.dY = (double)contour[n].y;
taPoints.push_back(taPoint);
}
double min_err;
EyemOcsDXYR _tpCircle;
eyemFitCircle((int)taPoints.size(), &taPoints[0], 10, min_err, _tpCircle);
AFAs.push_back(AFA(min_err, _tpCircle));
}
if (AFAs.empty()) {
return FUNC_FAILED_DETECT;
}
//排序
std::sort(AFAs.begin(), AFAs.end(), std::less<AFA>());
//高精度定位
if (false) {
EyemOcsDXY tpPoint; IntPtr hObject;
tpPoint.dX = AFAs[0].tpCircle.dX; tpPoint.dY = AFAs[0].tpCircle.dY;
//提取图像
std::vector<cv::Mat> mvx;
cv::split(cc, mvx);
EyemImage imageRed; imageRed.iWidth = cc.cols; imageRed.iHeight = cc.rows; imageRed.iDepth = cc.depth(); imageRed.iChannels = 1; imageRed.vpImage = mvx[2].data;
int iRadius = 27, iCapLength = 9, iCapWidth = 6, nCalipers = 19, nFilterSize = 2, iSearchDirec = 1;
eyemEdge1dFindCircle(imageRed, tpPoint, iRadius, iCapLength, iCapWidth, nCalipers, nFilterSize, iSearchDirec, 35, "positive", &hObject);
//拟合
std::vector<EyemOcsDXY> *tpResults = reinterpret_cast<std::vector<EyemOcsDXY>*>(hObject);
double rms; EyemOcsDXYR _tpCircle;
eyemFitCircle((int)tpResults->size(), tpResults->data(), 5, rms, _tpCircle);
//输出
tpCircle->fX = (float)_tpCircle.dX;
tpCircle->fY = (float)_tpCircle.dY;
tpCircle->fR = (float)_tpCircle.dR;
//释放
eyemEdge1dGenMeasureFree(hObject);
}
else {
//输出
tpCircle->fX = (float)AFAs[0].tpCircle.dX;
tpCircle->fY = (float)AFAs[0].tpCircle.dY;
tpCircle->fR = (float)AFAs[0].tpCircle.dR;
}
//画图
cv::rectangle(cc, cv::Rect(cv::Point2f(tpCircle->fX - 2.0f*tpCircle->fR, tpCircle->fY - 2.0f*tpCircle->fR),
cv::Point2f(tpCircle->fX + 2.0f*tpCircle->fR, tpCircle->fY + 2.0f*tpCircle->fR)), cv::Scalar(0, 255, 255), 4);
cv::drawMarker(cc, cv::Point2f(tpCircle->fX, tpCircle->fY), cv::Scalar(0, 255, 0), cv::MARKER_CROSS, 20, 1);
}
else {
std::vector<AFA> rboxes;
//过滤
std::vector<cv::Point> approx;
for (auto&contour : contours) {
float arcL = (float)cv::arcLength(cv::Mat(contour), true);
cv::approxPolyDP(cv::Mat(contour), approx, arcL*0.01, true);
if (approx.size() < 6) {
cv::RotatedRect rbox = cv::minAreaRect(contour);
if (std::max(rbox.size.width, rbox.size.height) > 20) {
double min_err = (double)rbox.size.area() / cv::contourArea(contour);
if (min_err > 0.85 && min_err < 1.15) {
EyemOcsDXYR _tpCenter;
_tpCenter.dR = std::min(rbox.size.width, rbox.size.height) / 2.0;
_tpCenter.dX = rbox.center.x; _tpCenter.dY = rbox.center.y;
rboxes.push_back(AFA(min_err, _tpCenter));
}
}
}
}
if (rboxes.empty()) {
return FUNC_FAILED_DETECT;
}
//排序
std::sort(rboxes.begin(), rboxes.end(), std::less<AFA>());
//输出
tpCircle->fX = (float)rboxes[0].tpCircle.dX;
tpCircle->fY = (float)rboxes[0].tpCircle.dY;
tpCircle->fR = (float)rboxes[0].tpCircle.dR;
}
//<输出结果图像
tpDstImg->iWidth = cc.cols; tpDstImg->iHeight = cc.rows; tpDstImg->iDepth = cc.depth(); tpDstImg->iChannels = cc.channels();
//内存尺寸
int _Size = tpDstImg->iWidth*tpDstImg->iHeight*tpDstImg->iChannels * sizeof(uint8_t);
//分配初始化内存
tpDstImg->vpImage = (uint8_t *)malloc(_Size);
if (NULL == tpDstImg->vpImage)
return FUNC_NOT_ENOUGH_MEM;
memset(tpDstImg->vpImage, 0, _Size);
//拷贝数据
memcpy(tpDstImg->vpImage, cc.data, _Size);
return FUNC_OK;
}
int eyemMulFuncTool(EyemImage tpImage, EyemRect tpRoi, const char *funcName, double dThreshold, int iNumToIgnore, EyemOcsFXYR *tpCircle, EyemImage *tpDstImg)
{
cv::Mat image = cv::Mat(tpImage.iHeight, tpImage.iWidth, MAKETYPE(tpImage.iDepth, tpImage.iChannels), tpImage.vpImage).clone()(
cv::Rect(tpRoi.iXs, tpRoi.iYs, tpRoi.iWidth, tpRoi.iHeight));
if (image.empty())
return FUNC_IMAGE_NOT_EXIST;
const int X = image.cols; const int Y = image.rows;
if (strcmp(funcName, "__func1") == 0) {
int incn = image.channels();
if (incn > 3) {
cv::cvtColor(image, image, cv::COLOR_BGRA2GRAY);
}
else if (incn == 3) {
cv::cvtColor(image, image, cv::COLOR_BGR2GRAY);
}
else if (incn == 1) {
}
//高斯滤波
cv::Mat imagePrev;
cv::blur(image, imagePrev, cv::Size(15, 15));
//二值化
cv::Mat binary;
if (dThreshold == 0.0) {
cv::threshold(imagePrev, binary, dThreshold, 255, cv::THRESH_BINARY_INV | cv::THRESH_OTSU);
}
else {
cv::threshold(imagePrev, binary, dThreshold, 255, cv::THRESH_BINARY_INV);
}
//去掉干扰
cv::Mat mask;
cv::morphologyEx(binary, mask, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(45, 45)));
//填充孔洞
std::vector<std::vector<cv::Point>> contours;
cv::findContours(mask, contours, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE);
for (auto contourIdx = 0; contourIdx < contours.size(); contourIdx++) {
cv::drawContours(mask, contours, contourIdx, cv::Scalar(255), -1);
}
//计算最大连通域
cv::Mat labels, stats, centroids;
int nccomps = cv::connectedComponentsWithStats(mask, labels, stats, centroids);
double maxVal;
cv::minMaxIdx(stats(cv::Range(1, stats.rows), cv::Range(4, 5)), NULL, &maxVal);
//过滤连通域面积<=maxVal的
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] < maxVal))
{
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 = mask.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::findContours(mask, contours, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE);
std::vector<EyemOcsDXY> taPoints;
for (auto&contour : contours) {
for (int n = 0; n < contour.size(); n++) {
EyemOcsDXY taPoint;
taPoint.dX = (double)contour[n].x;
taPoint.dY = (double)contour[n].y;
taPoints.push_back(taPoint);
}
}
double min_err;
EyemOcsDXYR _tpCircle;
eyemFitCircle((int)taPoints.size(), &taPoints[0], iNumToIgnore, min_err, _tpCircle);
//画图
cv::Mat showMat;
cv::cvtColor(image, showMat, cv::COLOR_GRAY2RGB);
cv::circle(showMat, cv::Point(cvRound(_tpCircle.dX), cvRound(_tpCircle.dY)), cvRound(_tpCircle.dR), cv::Scalar(0, 255, 0), 2);
//输出
tpCircle->fX = (float)_tpCircle.dX + (float)tpRoi.iXs;
tpCircle->fY = (float)_tpCircle.dY + (float)tpRoi.iYs;
tpCircle->fR = (float)_tpCircle.dR;
//输出结果图像
{
if (NULL != tpDstImg->vpImage) {
tpDstImg->iWidth = tpDstImg->iHeight = tpDstImg->iDepth = tpDstImg->iChannels = 0;
//释放
free(tpDstImg->vpImage);
tpDstImg->vpImage = NULL;
}
tpDstImg->iWidth = mask.cols; tpDstImg->iHeight = mask.rows; tpDstImg->iDepth = mask.depth(); tpDstImg->iChannels = mask.channels();
//内存尺寸
int _Size = tpDstImg->iWidth*tpDstImg->iHeight*tpDstImg->iChannels * sizeof(uint8_t);
//分配初始化内存
tpDstImg->vpImage = (uint8_t *)malloc(_Size);
if (NULL == tpDstImg->vpImage)
return FUNC_NOT_ENOUGH_MEM;
memset(tpDstImg->vpImage, 0, _Size);
//拷贝数据
memcpy(tpDstImg->vpImage, mask.data, _Size);
}
}
else if (strcmp(funcName, "__func2") == 0) {
}
else {
//there is no function named for this
return FUNC_CANNOT_USE;
}
return FUNC_OK;
}
#include "eyemMatchShapes.h"
int eyemLibImpl(EyemImage tpImage, EyemHSVModel tpHSVModel, EyemImage *tpDstImg)
{
CV_Assert(NULL != tpImage.vpImage);
cv::Mat image = cv::Mat(tpImage.iHeight, tpImage.iWidth, MAKETYPE(tpImage.iDepth, tpImage.iChannels), tpImage.vpImage).clone();
if (image.empty())
return FUNC_IMAGE_NOT_EXIST;
//多个分割阈值
if ((tpHSVModel.dpRangeLExt[0] + tpHSVModel.dpRangeLExt[1] + tpHSVModel.dpRangeLExt[2]) != 0 ||
(tpHSVModel.dpRangeUExt[0] + tpHSVModel.dpRangeUExt[1] + tpHSVModel.dpRangeUExt[2]) != 0) {
std::cout << "红色" << std::endl;
}
return FUNC_OK;
//shape_based_matching GM; // object to implent geometric matching
//int lowThreshold = 10; //deafult value
//int highThreashold = 100; //deafult value
//double minScore = 0.25; //deafult value
//double greediness = 0.8; //deafult value
//double total_time = 0;
//double score = 0;
//cv::Point result;
//cv::Mat templateImage = cv::imread("D://批量测试图像//template2.png", cv::IMREAD_GRAYSCALE);
//if (templateImage.data == NULL)
//{
// return 0;
//}
////Load Search Image
//cv::Mat searchImage = cv::imread("D://批量测试图像//rings_01.png", cv::IMREAD_GRAYSCALE);
//if (searchImage.data == NULL)
//{
// return 0;
//}
//lowThreshold = atoi("10");
//highThreashold = atoi("100");//get high threshold
//minScore = atof("0.25");
//greediness = atof("0.9");
//cv::Mat grayTemplateImg; //(templateImage.size(), CV_8U, 1);
//templateImage.copyTo(grayTemplateImg);
//if (GM.create_shape_model(grayTemplateImg, lowThreshold, highThreashold) != FUNC_OK)
//{
// std::cout << "ERROR: could not create model...";
// return 0;
//}
//else {
// cv::Mat cc;
// cv::cvtColor(templateImage, cc, cv::COLOR_GRAY2BGR);
//}
////测试用833
////测试用
//cv::Mat cc;
//cv::cvtColor(templateImage, cc, cv::COLOR_GRAY2BGR);
//for (int i = 0; i < 833; i++)
//{
// //cc.ptr<cv::Vec3b>(resultPoints)[resultPoints[i].y] = cv::Vec3b(0, 0, 255);
//}
////CvSize searchSize = cvSize(searchImage->width, searchImage->height);
//cv::Mat graySearchImg; //= cvCreateImage(searchSize, IPL_DEPTH_8U, 1);
// // Convert color image to gray image.
//searchImage.copyTo(graySearchImg);
//clock_t start_time1 = clock();
//score = GM.find_shape_model(graySearchImg, minScore, greediness, &result);
//clock_t finish_time1 = clock();
//total_time = ((double)finish_time1 - (double)start_time1) / CLOCKS_PER_SEC;
//cv::Mat rgb;
//if (score > minScore) // if score is atleast 0.4
//{
// std::cout << " Found at [" << result.x << ", " << result.y << "]\n Score = " << score << "\n Searching Time = " << total_time * 1000 << "ms";
// cvtColor(searchImage, rgb, cv::COLOR_GRAY2BGR);
// GM.draw_match_shapes(rgb, result, cv::Scalar(0, 255, 0), 1);
//}
//else
// std::cout << " Object Not found";
////////////////////////////////////
//std::cout << "\n ------------------------------------\n\n";
//std::cout << "\n Press any key to exit!";
////Display result
//cv::Mat dispTemplate;
//cvtColor(templateImage, dispTemplate, cv::COLOR_GRAY2BGR);
//GM.draw_match_shapes(dispTemplate, CV_RGB(255, 0, 0), 1);
//cv::namedWindow("Template", cv::WINDOW_AUTOSIZE);
//cv::imshow("Template", dispTemplate);
//cv::namedWindow("Search Image", cv::WINDOW_AUTOSIZE);
//imshow("Search Image", rgb);
//cv::waitKey(0);
//cv::destroyWindow("Search Image");
//cv::destroyWindow("Template");
//return 0;
#pragma region resize img
//const int minInputSize = 832;
//float resizeRatio = (float)sqrt(image.cols * image.rows * 1.0 / (minInputSize * minInputSize));
//int target_width = cvRound((float)image.cols / resizeRatio);
//int target_height = cvRound((float)image.rows / resizeRatio);
//cv::Mat input;
//resize(image, input, cv::Size(image.cols / 2, image.rows / 2), 0, 0, cv::INTER_CUBIC);
//image = input;
#pragma endregion
#pragma region wechat_qrcode
//cv::Ptr<wechat_qrcode::WeChatQRCode> detector;
//try {
// detector = cv::makePtr<wechat_qrcode::WeChatQRCode>(".\\opencv_3rdparty-wechat_qrcode\\detect.prototxt", ".\\opencv_3rdparty-wechat_qrcode\\detect.caffemodel",
// ".\\opencv_3rdparty-wechat_qrcode\\sr.prototxt", ".\\opencv_3rdparty-wechat_qrcode\\sr.caffemodel");
//}
//catch (const std::exception& e) {
// std::cout << e.what() << std::endl;
// return 0;
//}
//std::string prevstr = "";
//std::vector<cv::Mat> points;
//auto res = detector->detectAndDecode(image, points);
//for (const auto& t : res) std::cout << t << std::endl;
#pragma endregion
#pragma region darknet
////加载类名
//std::vector<std::string> classes;
//std::string classFile = ".\\darknet\\detect.names";
//std::ifstream ifs(classFile.c_str());
//std::string line;
//while (std::getline(ifs, line)) classes.push_back(line);
////加载网络
//cv::dnn::Net net = cv::dnn::readNet(".\\darknet\\yolov3-detect-tiny.cfg", ".\\darknet\\yolov3-detect-tiny_last.weights");
//net.setPreferableBackend(cv::dnn::DNN_BACKEND_OPENCV);
//net.setPreferableBackend(cv::dnn::DNN_TARGET_CPU);
////获取输出层名称
//auto layerNames = net.getLayerNames();
//std::vector<int> outLayers = net.getUnconnectedOutLayers();
//std::vector<std::string> outBlobNames(outLayers.size());
//for (int i = 0; i < outLayers.size(); i++) {
// outBlobNames[i] = layerNames[outLayers[i] - 1];
//}
////预处理图像
//cv::Mat blob;
//cv::dnn::blobFromImage(image, blob, 1 / 255., cv::Size(608, 608));
////为网络输入新值
//net.setInput(blob);
////获取预测结果
//std::vector<cv::Mat> outputBlobs;
//net.forward(outputBlobs, outBlobNames);
//std::vector<int> classIds;//储存识别类的索引
//std::vector<float> confidences;//储存置信度
//std::vector<cv::Rect> bboxes;//储存边框
//for (int n = 0; n < outputBlobs.size(); n++) {
// for (int row = 0; row < outputBlobs[n].rows; row++) {
// //置信度
// cv::Mat prob = outputBlobs[n](cv::Range(row, row + 1), cv::Range(5, outputBlobs[n].cols));
// double confidence;
// cv::Point classIdPoint;
// //取得最大分数值与索引
// cv::minMaxLoc(prob, 0, &confidence, 0, &classIdPoint);
// //如果置信度大于阈值
// if (confidence > 0.01) {
// cv::Mat dt = outputBlobs[n];
// cv::Mat x = outputBlobs[n](cv::Range(row, row + 1), cv::Range(0, 5));
// int cx = cvRound(x.ptr<float>(0)[0] * (float)image.cols);
// int cy = cvRound(x.ptr<float>(0)[1] * (float)image.rows);
// int w = cvRound(x.ptr<float>(0)[2] * (float)image.cols);
// int h = cvRound(x.ptr<float>(0)[3] * (float)image.rows);
// int left = cx - w / 2;
// int top = cy - h / 2;
// classIds.push_back(classIdPoint.x);
// confidences.push_back((float)confidence);
// bboxes.push_back(cv::Rect(left, top, w, h));
// }
// }
//}
////cv::Mat showMat;
////cv::cvtColor(image)
//std::vector<int> indices;
////非极大值抑制
//cv::dnn::NMSBoxes(bboxes, confidences, 0.01f, 0.05f, indices);
//for (int i = 0; i < indices.size(); i++) {
// int idx = indices[i];
// cv::Rect bbox = bboxes[idx] & cv::Rect(0, 0, image.cols, image.rows);
// //标签
// std::string label = cv::format("%.2f", confidences[idx]);
// if (!classes.empty()) {
// label = classes[classIds[idx]] + ":" + label;
// }
// int baseLine;
// cv::Size labelSize = cv::getTextSize(label, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
// cv::Scalar pal(0, 255, 0);
// cv::rectangle(image, bbox, pal);
// cv::rectangle(image, cv::Point(bbox.x, bbox.y - labelSize.height - baseLine), cv::Point(bbox.x + labelSize.width, bbox.y), pal, cv::FILLED);
// cv::putText(image, label, cv::Point(bbox.tl().x, bbox.tl().y - baseLine), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0), 1);
//}
/////<输出计数结果标记图像
//{
// tpDstImg->iWidth = image.cols; tpDstImg->iHeight = image.rows; tpDstImg->iDepth = image.depth(); tpDstImg->iChannels = image.channels();
// //内存尺寸
// int _Size = tpDstImg->iWidth*tpDstImg->iHeight*tpDstImg->iChannels * sizeof(uint8_t);
// //分配初始化内存
// tpDstImg->vpImage = (uint8_t *)malloc(_Size);
// if (NULL == tpDstImg->vpImage)
// return FUNC_NOT_ENOUGH_MEM;
// memset(tpDstImg->vpImage, 0, _Size);
// //拷贝数据
// memcpy(tpDstImg->vpImage, image.data, _Size);
//}
#pragma endregion
return FUNC_OK;
}