Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

model.py 124 KB

You have to be logged in to leave a comment. Sign In
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
  1. """
  2. Mask R-CNN
  3. The main Mask R-CNN model implementation.
  4. Copyright (c) 2017 Matterport, Inc.
  5. Licensed under the MIT License (see LICENSE for details)
  6. Written by Waleed Abdulla
  7. """
  8. import os
  9. import datetime
  10. import re
  11. import math
  12. from collections import OrderedDict
  13. import multiprocessing
  14. import numpy as np
  15. import tensorflow as tf
  16. import tensorflow.keras as keras
  17. import tensorflow.keras.backend as K
  18. import tensorflow.keras.layers as KL
  19. import tensorflow.keras.utils as KU
  20. from tensorflow.python.eager import context
  21. import tensorflow.keras.models as KM
  22. from mrcnn import utils
  23. # Requires TensorFlow 2.0+
  24. from distutils.version import LooseVersion
  25. assert LooseVersion(tf.__version__) >= LooseVersion("2.0")
  26. tf.compat.v1.disable_eager_execution()
  27. ############################################################
  28. # Utility Functions
  29. ############################################################
  30. class ModdedLayer(KL.Layer):
  31. def get_config(self):
  32. cfg = super().get_config()
  33. return cfg
  34. def log(text, array=None):
  35. """Prints a text message. And, optionally, if a Numpy array is provided it
  36. prints it's shape, min, and max values.
  37. """
  38. if array is not None:
  39. text = text.ljust(25)
  40. text += ("shape: {:20} ".format(str(array.shape)))
  41. if array.size:
  42. text += ("min: {:10.5f} max: {:10.5f}".format(array.min(),array.max()))
  43. else:
  44. text += ("min: {:10} max: {:10}".format("",""))
  45. text += " {}".format(array.dtype)
  46. print(text)
  47. class BatchNorm(KL.BatchNormalization):
  48. """Extends the Keras BatchNormalization class to allow a central place
  49. to make changes if needed.
  50. Batch normalization has a negative effect on training if batches are small
  51. so this layer is often frozen (via setting in Config class) and functions
  52. as linear layer.
  53. """
  54. def call(self, inputs, training=None):
  55. """
  56. Note about training values:
  57. None: Train BN layers. This is the normal mode
  58. False: Freeze BN layers. Good when batch size is small
  59. True: (don't use). Set layer in training mode even when making inferences
  60. """
  61. return super(self.__class__, self).call(inputs, training=training)
  62. def compute_backbone_shapes(config, image_shape):
  63. """Computes the width and height of each stage of the backbone network.
  64. Returns:
  65. [N, (height, width)]. Where N is the number of stages
  66. """
  67. if callable(config.BACKBONE):
  68. return config.COMPUTE_BACKBONE_SHAPE(image_shape)
  69. # Currently supports ResNet only
  70. assert config.BACKBONE in ["resnet50", "resnet101"]
  71. return np.array(
  72. [[int(math.ceil(image_shape[0] / stride)),
  73. int(math.ceil(image_shape[1] / stride))]
  74. for stride in config.BACKBONE_STRIDES])
  75. ############################################################
  76. # Resnet Graph
  77. ############################################################
  78. # Code adopted from:
  79. # https://github.com/fchollet/deep-learning-models/blob/master/resnet50.py
  80. def identity_block(input_tensor, kernel_size, filters, stage, block,
  81. use_bias=True, train_bn=True):
  82. """The identity_block is the block that has no conv layer at shortcut
  83. # Arguments
  84. input_tensor: input tensor
  85. kernel_size: default 3, the kernel size of middle conv layer at main path
  86. filters: list of integers, the nb_filters of 3 conv layer at main path
  87. stage: integer, current stage label, used for generating layer names
  88. block: 'a','b'..., current block label, used for generating layer names
  89. use_bias: Boolean. To use or not use a bias in conv layers.
  90. train_bn: Boolean. Train or freeze Batch Norm layers
  91. """
  92. nb_filter1, nb_filter2, nb_filter3 = filters
  93. conv_name_base = 'res' + str(stage) + block + '_branch'
  94. bn_name_base = 'bn' + str(stage) + block + '_branch'
  95. x = KL.Conv2D(nb_filter1, (1, 1), name=conv_name_base + '2a',
  96. use_bias=use_bias)(input_tensor)
  97. x = BatchNorm(name=bn_name_base + '2a')(x, training=train_bn)
  98. x = KL.Activation('relu')(x)
  99. x = KL.Conv2D(nb_filter2, (kernel_size, kernel_size), padding='same',
  100. name=conv_name_base + '2b', use_bias=use_bias)(x)
  101. x = BatchNorm(name=bn_name_base + '2b')(x, training=train_bn)
  102. x = KL.Activation('relu')(x)
  103. x = KL.Conv2D(nb_filter3, (1, 1), name=conv_name_base + '2c',
  104. use_bias=use_bias)(x)
  105. x = BatchNorm(name=bn_name_base + '2c')(x, training=train_bn)
  106. x = KL.Add()([x, input_tensor])
  107. x = KL.Activation('relu', name='res' + str(stage) + block + '_out')(x)
  108. return x
  109. def conv_block(input_tensor, kernel_size, filters, stage, block,
  110. strides=(2, 2), use_bias=True, train_bn=True):
  111. """conv_block is the block that has a conv layer at shortcut
  112. # Arguments
  113. input_tensor: input tensor
  114. kernel_size: default 3, the kernel size of middle conv layer at main path
  115. filters: list of integers, the nb_filters of 3 conv layer at main path
  116. stage: integer, current stage label, used for generating layer names
  117. block: 'a','b'..., current block label, used for generating layer names
  118. use_bias: Boolean. To use or not use a bias in conv layers.
  119. train_bn: Boolean. Train or freeze Batch Norm layers
  120. Note that from stage 3, the first conv layer at main path is with subsample=(2,2)
  121. And the shortcut should have subsample=(2,2) as well
  122. """
  123. nb_filter1, nb_filter2, nb_filter3 = filters
  124. conv_name_base = 'res' + str(stage) + block + '_branch'
  125. bn_name_base = 'bn' + str(stage) + block + '_branch'
  126. x = KL.Conv2D(nb_filter1, (1, 1), strides=strides,
  127. name=conv_name_base + '2a', use_bias=use_bias)(input_tensor)
  128. x = BatchNorm(name=bn_name_base + '2a')(x, training=train_bn)
  129. x = KL.Activation('relu')(x)
  130. x = KL.Conv2D(nb_filter2, (kernel_size, kernel_size), padding='same',
  131. name=conv_name_base + '2b', use_bias=use_bias)(x)
  132. x = BatchNorm(name=bn_name_base + '2b')(x, training=train_bn)
  133. x = KL.Activation('relu')(x)
  134. x = KL.Conv2D(nb_filter3, (1, 1), name=conv_name_base +
  135. '2c', use_bias=use_bias)(x)
  136. x = BatchNorm(name=bn_name_base + '2c')(x, training=train_bn)
  137. shortcut = KL.Conv2D(nb_filter3, (1, 1), strides=strides,
  138. name=conv_name_base + '1', use_bias=use_bias)(input_tensor)
  139. shortcut = BatchNorm(name=bn_name_base + '1')(shortcut, training=train_bn)
  140. x = KL.Add()([x, shortcut])
  141. x = KL.Activation('relu', name='res' + str(stage) + block + '_out')(x)
  142. return x
  143. def resnet_graph(input_image, architecture, stage5=False, train_bn=True):
  144. """Build a ResNet graph.
  145. architecture: Can be resnet50 or resnet101
  146. stage5: Boolean. If False, stage5 of the network is not created
  147. train_bn: Boolean. Train or freeze Batch Norm layers
  148. """
  149. assert architecture in ["resnet50", "resnet101"]
  150. # Stage 1
  151. x = KL.ZeroPadding2D((3, 3))(input_image)
  152. x = KL.Conv2D(64, (7, 7), strides=(2, 2), name='conv1', use_bias=True)(x)
  153. x = BatchNorm(name='bn_conv1')(x, training=train_bn)
  154. x = KL.Activation('relu')(x)
  155. C1 = x = KL.MaxPooling2D((3, 3), strides=(2, 2), padding="same")(x)
  156. # Stage 2
  157. x = conv_block(x, 3, [64, 64, 256], stage=2, block='a', strides=(1, 1), train_bn=train_bn)
  158. x = identity_block(x, 3, [64, 64, 256], stage=2, block='b', train_bn=train_bn)
  159. C2 = x = identity_block(x, 3, [64, 64, 256], stage=2, block='c', train_bn=train_bn)
  160. # Stage 3
  161. x = conv_block(x, 3, [128, 128, 512], stage=3, block='a', train_bn=train_bn)
  162. x = identity_block(x, 3, [128, 128, 512], stage=3, block='b', train_bn=train_bn)
  163. x = identity_block(x, 3, [128, 128, 512], stage=3, block='c', train_bn=train_bn)
  164. C3 = x = identity_block(x, 3, [128, 128, 512], stage=3, block='d', train_bn=train_bn)
  165. # Stage 4
  166. x = conv_block(x, 3, [256, 256, 1024], stage=4, block='a', train_bn=train_bn)
  167. block_count = {"resnet50": 5, "resnet101": 22}[architecture]
  168. for i in range(block_count):
  169. x = identity_block(x, 3, [256, 256, 1024], stage=4, block=chr(98 + i), train_bn=train_bn)
  170. C4 = x
  171. # Stage 5
  172. if stage5:
  173. x = conv_block(x, 3, [512, 512, 2048], stage=5, block='a', train_bn=train_bn)
  174. x = identity_block(x, 3, [512, 512, 2048], stage=5, block='b', train_bn=train_bn)
  175. C5 = x = identity_block(x, 3, [512, 512, 2048], stage=5, block='c', train_bn=train_bn)
  176. else:
  177. C5 = None
  178. return [C1, C2, C3, C4, C5]
  179. ############################################################
  180. # Proposal Layer
  181. ############################################################
  182. def apply_box_deltas_graph(boxes, deltas):
  183. """Applies the given deltas to the given boxes.
  184. boxes: [N, (y1, x1, y2, x2)] boxes to update
  185. deltas: [N, (dy, dx, log(dh), log(dw))] refinements to apply
  186. """
  187. # Convert to y, x, h, w
  188. height = boxes[:, 2] - boxes[:, 0]
  189. width = boxes[:, 3] - boxes[:, 1]
  190. center_y = boxes[:, 0] + 0.5 * height
  191. center_x = boxes[:, 1] + 0.5 * width
  192. # Apply deltas
  193. center_y += deltas[:, 0] * height
  194. center_x += deltas[:, 1] * width
  195. height *= tf.exp(deltas[:, 2])
  196. width *= tf.exp(deltas[:, 3])
  197. # Convert back to y1, x1, y2, x2
  198. y1 = center_y - 0.5 * height
  199. x1 = center_x - 0.5 * width
  200. y2 = y1 + height
  201. x2 = x1 + width
  202. result = tf.stack([y1, x1, y2, x2], axis=1, name="apply_box_deltas_out")
  203. return result
  204. def clip_boxes_graph(boxes, window):
  205. """
  206. boxes: [N, (y1, x1, y2, x2)]
  207. window: [4] in the form y1, x1, y2, x2
  208. """
  209. # Split
  210. wy1, wx1, wy2, wx2 = tf.split(window, 4)
  211. y1, x1, y2, x2 = tf.split(boxes, 4, axis=1)
  212. # Clip
  213. y1 = tf.maximum(tf.minimum(y1, wy2), wy1)
  214. x1 = tf.maximum(tf.minimum(x1, wx2), wx1)
  215. y2 = tf.maximum(tf.minimum(y2, wy2), wy1)
  216. x2 = tf.maximum(tf.minimum(x2, wx2), wx1)
  217. clipped = tf.concat([y1, x1, y2, x2], axis=1, name="clipped_boxes")
  218. clipped.set_shape((clipped.shape[0], 4))
  219. return clipped
  220. class ProposalLayer(ModdedLayer):
  221. """Receives anchor scores and selects a subset to pass as proposals
  222. to the second stage. Filtering is done based on anchor scores and
  223. non-max suppression to remove overlaps. It also applies bounding
  224. box refinement deltas to anchors.
  225. Inputs:
  226. rpn_probs: [batch, num_anchors, (bg prob, fg prob)]
  227. rpn_bbox: [batch, num_anchors, (dy, dx, log(dh), log(dw))]
  228. anchors: [batch, num_anchors, (y1, x1, y2, x2)] anchors in normalized coordinates
  229. Returns:
  230. Proposals in normalized coordinates [batch, rois, (y1, x1, y2, x2)]
  231. """
  232. def __init__(self, proposal_count, nms_threshold, config=None, **kwargs):
  233. super(ProposalLayer, self).__init__(**kwargs)
  234. self.config = config
  235. self.proposal_count = proposal_count
  236. self.nms_threshold = nms_threshold
  237. def get_config(self):
  238. config = super(ProposalLayer, self).get_config()
  239. config["config"] = self.config.to_dict()
  240. config["proposal_count"] = self.proposal_count
  241. config["nms_threshold"] = self.nms_threshold
  242. return config
  243. def call(self, inputs):
  244. # Box Scores. Use the foreground class confidence. [Batch, num_rois, 1]
  245. scores = inputs[0][:, :, 1]
  246. # Box deltas [batch, num_rois, 4]
  247. deltas = inputs[1]
  248. deltas = deltas * np.reshape(self.config.RPN_BBOX_STD_DEV, [1, 1, 4])
  249. # Anchors
  250. anchors = inputs[2]
  251. # Improve performance by trimming to top anchors by score
  252. # and doing the rest on the smaller subset.
  253. pre_nms_limit = tf.minimum(self.config.PRE_NMS_LIMIT, tf.shape(input=anchors)[1])
  254. ix = tf.nn.top_k(scores, pre_nms_limit, sorted=True,
  255. name="top_anchors").indices
  256. scores = utils.batch_slice([scores, ix], lambda x, y: tf.gather(x, y),
  257. self.config.IMAGES_PER_GPU)
  258. deltas = utils.batch_slice([deltas, ix], lambda x, y: tf.gather(x, y),
  259. self.config.IMAGES_PER_GPU)
  260. pre_nms_anchors = utils.batch_slice([anchors, ix], lambda a, x: tf.gather(a, x),
  261. self.config.IMAGES_PER_GPU,
  262. names=["pre_nms_anchors"])
  263. # Apply deltas to anchors to get refined anchors.
  264. # [batch, N, (y1, x1, y2, x2)]
  265. boxes = utils.batch_slice([pre_nms_anchors, deltas],
  266. lambda x, y: apply_box_deltas_graph(x, y),
  267. self.config.IMAGES_PER_GPU,
  268. names=["refined_anchors"])
  269. # Clip to image boundaries. Since we're in normalized coordinates,
  270. # clip to 0..1 range. [batch, N, (y1, x1, y2, x2)]
  271. window = np.array([0, 0, 1, 1], dtype=np.float32)
  272. boxes = utils.batch_slice(boxes,
  273. lambda x: clip_boxes_graph(x, window),
  274. self.config.IMAGES_PER_GPU,
  275. names=["refined_anchors_clipped"])
  276. # Filter out small boxes
  277. # According to Xinlei Chen's paper, this reduces detection accuracy
  278. # for small objects, so we're skipping it.
  279. # Non-max suppression
  280. def nms(boxes, scores):
  281. indices = tf.image.non_max_suppression(
  282. boxes, scores, self.proposal_count,
  283. self.nms_threshold, name="rpn_non_max_suppression")
  284. proposals = tf.gather(boxes, indices)
  285. # Pad if needed
  286. padding = tf.maximum(self.proposal_count - tf.shape(input=proposals)[0], 0)
  287. proposals = tf.pad(tensor=proposals, paddings=[(0, padding), (0, 0)])
  288. return proposals
  289. proposals = utils.batch_slice([boxes, scores], nms,
  290. self.config.IMAGES_PER_GPU)
  291. if not context.executing_eagerly():
  292. # Infer the static output shape:
  293. out_shape = self.compute_output_shape(None)
  294. proposals.set_shape(out_shape)
  295. return proposals
  296. def compute_output_shape(self, input_shape):
  297. return None, self.proposal_count, 4
  298. ############################################################
  299. # ROIAlign Layer
  300. ############################################################
  301. def log2_graph(x):
  302. """Implementation of Log2. TF doesn't have a native implementation."""
  303. return tf.math.log(x) / tf.math.log(2.0)
  304. class PyramidROIAlign(ModdedLayer):
  305. """Implements ROI Pooling on multiple levels of the feature pyramid.
  306. Params:
  307. - pool_shape: [pool_height, pool_width] of the output pooled regions. Usually [7, 7]
  308. Inputs:
  309. - boxes: [batch, num_boxes, (y1, x1, y2, x2)] in normalized
  310. coordinates. Possibly padded with zeros if not enough
  311. boxes to fill the array.
  312. - image_meta: [batch, (meta data)] Image details. See compose_image_meta()
  313. - feature_maps: List of feature maps from different levels of the pyramid.
  314. Each is [batch, height, width, channels]
  315. Output:
  316. Pooled regions in the shape: [batch, num_boxes, pool_height, pool_width, channels].
  317. The width and height are those specific in the pool_shape in the layer
  318. constructor.
  319. """
  320. def __init__(self, pool_shape, **kwargs):
  321. super(PyramidROIAlign, self).__init__(**kwargs)
  322. self.pool_shape = tuple(pool_shape)
  323. def get_config(self):
  324. config = super(PyramidROIAlign, self).get_config()
  325. config['pool_shape'] = self.pool_shape
  326. return config
  327. def call(self, inputs):
  328. # Crop boxes [batch, num_boxes, (y1, x1, y2, x2)] in normalized coords
  329. boxes = inputs[0]
  330. # Image meta
  331. # Holds details about the image. See compose_image_meta()
  332. image_meta = inputs[1]
  333. # Feature Maps. List of feature maps from different level of the
  334. # feature pyramid. Each is [batch, height, width, channels]
  335. feature_maps = inputs[2:]
  336. # Assign each ROI to a level in the pyramid based on the ROI area.
  337. y1, x1, y2, x2 = tf.split(boxes, 4, axis=2)
  338. h = y2 - y1
  339. w = x2 - x1
  340. # Use shape of first image. Images in a batch must have the same size.
  341. image_shape = parse_image_meta_graph(image_meta)['image_shape'][0]
  342. # Equation 1 in the Feature Pyramid Networks paper. Account for
  343. # the fact that our coordinates are normalized here.
  344. # e.g. a 224x224 ROI (in pixels) maps to P4
  345. image_area = tf.cast(image_shape[0] * image_shape[1], tf.float32)
  346. roi_level = log2_graph(tf.sqrt(h * w) / (224.0 / tf.sqrt(image_area)))
  347. roi_level = tf.minimum(5, tf.maximum(
  348. 2, 4 + tf.cast(tf.round(roi_level), tf.int32)))
  349. roi_level = tf.squeeze(roi_level, 2)
  350. # Loop through levels and apply ROI pooling to each. P2 to P5.
  351. pooled = []
  352. box_to_level = []
  353. for i, level in enumerate(range(2, 6)):
  354. ix = tf.compat.v1.where(tf.equal(roi_level, level))
  355. level_boxes = tf.gather_nd(boxes, ix)
  356. # Box indices for crop_and_resize.
  357. box_indices = tf.cast(ix[:, 0], tf.int32)
  358. # Keep track of which box is mapped to which level
  359. box_to_level.append(ix)
  360. # Stop gradient propogation to ROI proposals
  361. level_boxes = tf.stop_gradient(level_boxes)
  362. box_indices = tf.stop_gradient(box_indices)
  363. # Crop and Resize
  364. # From Mask R-CNN paper: "We sample four regular locations, so
  365. # that we can evaluate either max or average pooling. In fact,
  366. # interpolating only a single value at each bin center (without
  367. # pooling) is nearly as effective."
  368. #
  369. # Here we use the simplified approach of a single value per bin,
  370. # which is how it's done in tf.crop_and_resize()
  371. # Result: [batch * num_boxes, pool_height, pool_width, channels]
  372. pooled.append(tf.image.crop_and_resize(
  373. feature_maps[i], level_boxes, box_indices, self.pool_shape,
  374. method="bilinear"))
  375. # Pack pooled features into one tensor
  376. pooled = tf.concat(pooled, axis=0)
  377. # Pack box_to_level mapping into one array and add another
  378. # column representing the order of pooled boxes
  379. box_to_level = tf.concat(box_to_level, axis=0)
  380. box_range = tf.expand_dims(tf.range(tf.shape(input=box_to_level)[0]), 1)
  381. box_to_level = tf.concat([tf.cast(box_to_level, tf.int32), box_range],
  382. axis=1)
  383. # Rearrange pooled features to match the order of the original boxes
  384. # Sort box_to_level by batch then box index
  385. # TF doesn't have a way to sort by two columns, so merge them and sort.
  386. sorting_tensor = box_to_level[:, 0] * 100000 + box_to_level[:, 1]
  387. ix = tf.nn.top_k(sorting_tensor, k=tf.shape(
  388. input=box_to_level)[0]).indices[::-1]
  389. ix = tf.gather(box_to_level[:, 2], ix)
  390. pooled = tf.gather(pooled, ix)
  391. # Re-add the batch dimension
  392. shape = tf.concat([tf.shape(input=boxes)[:2], tf.shape(input=pooled)[1:]], axis=0)
  393. pooled = tf.reshape(pooled, shape)
  394. return pooled
  395. def compute_output_shape(self, input_shape):
  396. return input_shape[0][:2] + self.pool_shape + (input_shape[2][-1], )
  397. ############################################################
  398. # Detection Target Layer
  399. ############################################################
  400. def overlaps_graph(boxes1, boxes2):
  401. """Computes IoU overlaps between two sets of boxes.
  402. boxes1, boxes2: [N, (y1, x1, y2, x2)].
  403. """
  404. # 1. Tile boxes2 and repeat boxes1. This allows us to compare
  405. # every boxes1 against every boxes2 without loops.
  406. # TF doesn't have an equivalent to np.repeat() so simulate it
  407. # using tf.tile() and tf.reshape.
  408. b1 = tf.reshape(tf.tile(tf.expand_dims(boxes1, 1),
  409. [1, 1, tf.shape(input=boxes2)[0]]), [-1, 4])
  410. b2 = tf.tile(boxes2, [tf.shape(input=boxes1)[0], 1])
  411. # 2. Compute intersections
  412. b1_y1, b1_x1, b1_y2, b1_x2 = tf.split(b1, 4, axis=1)
  413. b2_y1, b2_x1, b2_y2, b2_x2 = tf.split(b2, 4, axis=1)
  414. y1 = tf.maximum(b1_y1, b2_y1)
  415. x1 = tf.maximum(b1_x1, b2_x1)
  416. y2 = tf.minimum(b1_y2, b2_y2)
  417. x2 = tf.minimum(b1_x2, b2_x2)
  418. intersection = tf.maximum(x2 - x1, 0) * tf.maximum(y2 - y1, 0)
  419. # 3. Compute unions
  420. b1_area = (b1_y2 - b1_y1) * (b1_x2 - b1_x1)
  421. b2_area = (b2_y2 - b2_y1) * (b2_x2 - b2_x1)
  422. union = b1_area + b2_area - intersection
  423. # 4. Compute IoU and reshape to [boxes1, boxes2]
  424. iou = intersection / union
  425. overlaps = tf.reshape(iou, [tf.shape(input=boxes1)[0], tf.shape(input=boxes2)[0]])
  426. return overlaps
  427. def detection_targets_graph(proposals, gt_class_ids, gt_boxes, gt_masks, config):
  428. """Generates detection targets for one image. Subsamples proposals and
  429. generates target class IDs, bounding box deltas, and masks for each.
  430. Inputs:
  431. proposals: [POST_NMS_ROIS_TRAINING, (y1, x1, y2, x2)] in normalized coordinates. Might
  432. be zero padded if there are not enough proposals.
  433. gt_class_ids: [MAX_GT_INSTANCES] int class IDs
  434. gt_boxes: [MAX_GT_INSTANCES, (y1, x1, y2, x2)] in normalized coordinates.
  435. gt_masks: [height, width, MAX_GT_INSTANCES] of boolean type.
  436. Returns: Target ROIs and corresponding class IDs, bounding box shifts,
  437. and masks.
  438. rois: [TRAIN_ROIS_PER_IMAGE, (y1, x1, y2, x2)] in normalized coordinates
  439. class_ids: [TRAIN_ROIS_PER_IMAGE]. Integer class IDs. Zero padded.
  440. deltas: [TRAIN_ROIS_PER_IMAGE, (dy, dx, log(dh), log(dw))]
  441. masks: [TRAIN_ROIS_PER_IMAGE, height, width]. Masks cropped to bbox
  442. boundaries and resized to neural network output size.
  443. Note: Returned arrays might be zero padded if not enough target ROIs.
  444. """
  445. # Assertions
  446. asserts = [
  447. tf.Assert(tf.greater(tf.shape(input=proposals)[0], 0), [proposals],
  448. name="roi_assertion"),
  449. ]
  450. with tf.control_dependencies(asserts):
  451. proposals = tf.identity(proposals)
  452. # Remove zero padding
  453. proposals, _ = trim_zeros_graph(proposals, name="trim_proposals")
  454. gt_boxes, non_zeros = trim_zeros_graph(gt_boxes, name="trim_gt_boxes")
  455. gt_class_ids = tf.boolean_mask(tensor=gt_class_ids, mask=non_zeros,
  456. name="trim_gt_class_ids")
  457. gt_masks = tf.gather(gt_masks, tf.compat.v1.where(non_zeros)[:, 0], axis=2,
  458. name="trim_gt_masks")
  459. # Handle COCO crowds
  460. # A crowd box in COCO is a bounding box around several instances. Exclude
  461. # them from training. A crowd box is given a negative class ID.
  462. crowd_ix = tf.compat.v1.where(gt_class_ids < 0)[:, 0]
  463. non_crowd_ix = tf.compat.v1.where(gt_class_ids > 0)[:, 0]
  464. crowd_boxes = tf.gather(gt_boxes, crowd_ix)
  465. gt_class_ids = tf.gather(gt_class_ids, non_crowd_ix)
  466. gt_boxes = tf.gather(gt_boxes, non_crowd_ix)
  467. gt_masks = tf.gather(gt_masks, non_crowd_ix, axis=2)
  468. # Compute overlaps matrix [proposals, gt_boxes]
  469. overlaps = overlaps_graph(proposals, gt_boxes)
  470. # Compute overlaps with crowd boxes [proposals, crowd_boxes]
  471. crowd_overlaps = overlaps_graph(proposals, crowd_boxes)
  472. crowd_iou_max = tf.reduce_max(input_tensor=crowd_overlaps, axis=1)
  473. no_crowd_bool = (crowd_iou_max < 0.001)
  474. # Determine positive and negative ROIs
  475. roi_iou_max = tf.reduce_max(input_tensor=overlaps, axis=1)
  476. # 1. Positive ROIs are those with >= 0.5 IoU with a GT box
  477. positive_roi_bool = (roi_iou_max >= 0.5)
  478. positive_indices = tf.compat.v1.where(positive_roi_bool)[:, 0]
  479. # 2. Negative ROIs are those with < 0.5 with every GT box. Skip crowds.
  480. negative_indices = tf.compat.v1.where(tf.logical_and(roi_iou_max < 0.5, no_crowd_bool))[:, 0]
  481. # Subsample ROIs. Aim for 33% positive
  482. # Positive ROIs
  483. positive_count = int(config.TRAIN_ROIS_PER_IMAGE *
  484. config.ROI_POSITIVE_RATIO)
  485. positive_indices = tf.random.shuffle(positive_indices)[:positive_count]
  486. positive_count = tf.shape(input=positive_indices)[0]
  487. # Negative ROIs. Add enough to maintain positive:negative ratio.
  488. r = 1.0 / config.ROI_POSITIVE_RATIO
  489. negative_count = tf.cast(r * tf.cast(positive_count, tf.float32), tf.int32) - positive_count
  490. negative_indices = tf.random.shuffle(negative_indices)[:negative_count]
  491. # Gather selected ROIs
  492. positive_rois = tf.gather(proposals, positive_indices)
  493. negative_rois = tf.gather(proposals, negative_indices)
  494. # Assign positive ROIs to GT boxes.
  495. positive_overlaps = tf.gather(overlaps, positive_indices)
  496. roi_gt_box_assignment = tf.cond(
  497. pred=tf.greater(tf.shape(input=positive_overlaps)[1], 0),
  498. true_fn=lambda: tf.argmax(input=positive_overlaps, axis=1),
  499. false_fn=lambda: tf.cast(K.constant([]), tf.int64)
  500. )
  501. roi_gt_boxes = tf.gather(gt_boxes, roi_gt_box_assignment)
  502. roi_gt_class_ids = tf.gather(gt_class_ids, roi_gt_box_assignment)
  503. # Compute bbox refinement for positive ROIs
  504. deltas = utils.box_refinement_graph(positive_rois, roi_gt_boxes)
  505. deltas /= config.BBOX_STD_DEV
  506. # Assign positive ROIs to GT masks
  507. # Permute masks to [N, height, width, 1]
  508. transposed_masks = tf.expand_dims(tf.transpose(a=gt_masks, perm=[2, 0, 1]), -1)
  509. # Pick the right mask for each ROI
  510. roi_masks = tf.gather(transposed_masks, roi_gt_box_assignment)
  511. # Compute mask targets
  512. boxes = positive_rois
  513. if config.USE_MINI_MASK:
  514. # Transform ROI coordinates from normalized image space
  515. # to normalized mini-mask space.
  516. y1, x1, y2, x2 = tf.split(positive_rois, 4, axis=1)
  517. gt_y1, gt_x1, gt_y2, gt_x2 = tf.split(roi_gt_boxes, 4, axis=1)
  518. gt_h = gt_y2 - gt_y1
  519. gt_w = gt_x2 - gt_x1
  520. y1 = (y1 - gt_y1) / gt_h
  521. x1 = (x1 - gt_x1) / gt_w
  522. y2 = (y2 - gt_y1) / gt_h
  523. x2 = (x2 - gt_x1) / gt_w
  524. boxes = tf.concat([y1, x1, y2, x2], 1)
  525. box_ids = tf.range(0, tf.shape(input=roi_masks)[0])
  526. masks = tf.image.crop_and_resize(tf.cast(roi_masks, tf.float32), boxes,
  527. box_ids,
  528. config.MASK_SHAPE)
  529. # Remove the extra dimension from masks.
  530. masks = tf.squeeze(masks, axis=3)
  531. # Threshold mask pixels at 0.5 to have GT masks be 0 or 1 to use with
  532. # binary cross entropy loss.
  533. masks = tf.round(masks)
  534. # Append negative ROIs and pad bbox deltas and masks that
  535. # are not used for negative ROIs with zeros.
  536. rois = tf.concat([positive_rois, negative_rois], axis=0)
  537. N = tf.shape(input=negative_rois)[0]
  538. P = tf.maximum(config.TRAIN_ROIS_PER_IMAGE - tf.shape(input=rois)[0], 0)
  539. rois = tf.pad(tensor=rois, paddings=[(0, P), (0, 0)])
  540. roi_gt_boxes = tf.pad(tensor=roi_gt_boxes, paddings=[(0, N + P), (0, 0)])
  541. roi_gt_class_ids = tf.pad(tensor=roi_gt_class_ids, paddings=[(0, N + P)])
  542. deltas = tf.pad(tensor=deltas, paddings=[(0, N + P), (0, 0)])
  543. masks = tf.pad(tensor=masks, paddings=[[0, N + P], (0, 0), (0, 0)])
  544. return rois, roi_gt_class_ids, deltas, masks
  545. class DetectionTargetLayer(ModdedLayer):
  546. """Subsamples proposals and generates target box refinement, class_ids,
  547. and masks for each.
  548. Inputs:
  549. proposals: [batch, N, (y1, x1, y2, x2)] in normalized coordinates. Might
  550. be zero padded if there are not enough proposals.
  551. gt_class_ids: [batch, MAX_GT_INSTANCES] Integer class IDs.
  552. gt_boxes: [batch, MAX_GT_INSTANCES, (y1, x1, y2, x2)] in normalized
  553. coordinates.
  554. gt_masks: [batch, height, width, MAX_GT_INSTANCES] of boolean type
  555. Returns: Target ROIs and corresponding class IDs, bounding box shifts,
  556. and masks.
  557. rois: [batch, TRAIN_ROIS_PER_IMAGE, (y1, x1, y2, x2)] in normalized
  558. coordinates
  559. target_class_ids: [batch, TRAIN_ROIS_PER_IMAGE]. Integer class IDs.
  560. target_deltas: [batch, TRAIN_ROIS_PER_IMAGE, (dy, dx, log(dh), log(dw)]
  561. target_mask: [batch, TRAIN_ROIS_PER_IMAGE, height, width]
  562. Masks cropped to bbox boundaries and resized to neural
  563. network output size.
  564. Note: Returned arrays might be zero padded if not enough target ROIs.
  565. """
  566. def __init__(self, config, **kwargs):
  567. super(DetectionTargetLayer, self).__init__(**kwargs)
  568. self.config = config
  569. def get_config(self):
  570. config = super(DetectionTargetLayer, self).get_config()
  571. config["config"] = self.config.to_dict()
  572. return config
  573. def call(self, inputs):
  574. proposals = inputs[0]
  575. gt_class_ids = inputs[1]
  576. gt_boxes = inputs[2]
  577. gt_masks = inputs[3]
  578. # Slice the batch and run a graph for each slice
  579. # TODO: Rename target_bbox to target_deltas for clarity
  580. names = ["rois", "target_class_ids", "target_bbox", "target_mask"]
  581. outputs = utils.batch_slice(
  582. [proposals, gt_class_ids, gt_boxes, gt_masks],
  583. lambda w, x, y, z: detection_targets_graph(
  584. w, x, y, z, self.config),
  585. self.config.IMAGES_PER_GPU, names=names)
  586. return outputs
  587. def compute_output_shape(self, input_shape):
  588. return [
  589. (None, self.config.TRAIN_ROIS_PER_IMAGE, 4), # rois
  590. (None, self.config.TRAIN_ROIS_PER_IMAGE), # class_ids
  591. (None, self.config.TRAIN_ROIS_PER_IMAGE, 4), # deltas
  592. (None, self.config.TRAIN_ROIS_PER_IMAGE, self.config.MASK_SHAPE[0],
  593. self.config.MASK_SHAPE[1]) # masks
  594. ]
  595. def compute_mask(self, inputs, mask=None):
  596. return [None, None, None, None]
  597. ############################################################
  598. # Detection Layer
  599. ############################################################
  600. def refine_detections_graph(rois, probs, deltas, window, config):
  601. """Refine classified proposals and filter overlaps and return final
  602. detections.
  603. Inputs:
  604. rois: [N, (y1, x1, y2, x2)] in normalized coordinates
  605. probs: [N, num_classes]. Class probabilities.
  606. deltas: [N, num_classes, (dy, dx, log(dh), log(dw))]. Class-specific
  607. bounding box deltas.
  608. window: (y1, x1, y2, x2) in normalized coordinates. The part of the image
  609. that contains the image excluding the padding.
  610. Returns detections shaped: [num_detections, (y1, x1, y2, x2, class_id, score)] where
  611. coordinates are normalized.
  612. """
  613. # Class IDs per ROI
  614. class_ids = tf.argmax(input=probs, axis=1, output_type=tf.int32)
  615. # Class probability of the top class of each ROI
  616. indices = tf.stack([tf.range(probs.shape[0]), class_ids], axis=1)
  617. class_scores = tf.gather_nd(probs, indices)
  618. # Class-specific bounding box deltas
  619. deltas_specific = tf.gather_nd(deltas, indices)
  620. # Apply bounding box deltas
  621. # Shape: [boxes, (y1, x1, y2, x2)] in normalized coordinates
  622. refined_rois = apply_box_deltas_graph(
  623. rois, deltas_specific * config.BBOX_STD_DEV)
  624. # Clip boxes to image window
  625. refined_rois = clip_boxes_graph(refined_rois, window)
  626. # TODO: Filter out boxes with zero area
  627. # Filter out background boxes
  628. keep = tf.compat.v1.where(class_ids > 0)[:, 0]
  629. # Filter out low confidence boxes
  630. if config.DETECTION_MIN_CONFIDENCE:
  631. conf_keep = tf.compat.v1.where(class_scores >= config.DETECTION_MIN_CONFIDENCE)[:, 0]
  632. keep = tf.sets.intersection(tf.expand_dims(keep, 0),
  633. tf.expand_dims(conf_keep, 0))
  634. keep = tf.sparse.to_dense(keep)[0]
  635. # Apply per-class NMS
  636. # 1. Prepare variables
  637. pre_nms_class_ids = tf.gather(class_ids, keep)
  638. pre_nms_scores = tf.gather(class_scores, keep)
  639. pre_nms_rois = tf.gather(refined_rois, keep)
  640. unique_pre_nms_class_ids = tf.unique(pre_nms_class_ids)[0]
  641. def nms_keep_map(class_id):
  642. """Apply Non-Maximum Suppression on ROIs of the given class."""
  643. # Indices of ROIs of the given class
  644. ixs = tf.compat.v1.where(tf.equal(pre_nms_class_ids, class_id))[:, 0]
  645. # Apply NMS
  646. class_keep = tf.image.non_max_suppression(
  647. tf.gather(pre_nms_rois, ixs),
  648. tf.gather(pre_nms_scores, ixs),
  649. max_output_size=config.DETECTION_MAX_INSTANCES,
  650. iou_threshold=config.DETECTION_NMS_THRESHOLD)
  651. # Map indices
  652. class_keep = tf.gather(keep, tf.gather(ixs, class_keep))
  653. # Pad with -1 so returned tensors have the same shape
  654. gap = config.DETECTION_MAX_INSTANCES - tf.shape(input=class_keep)[0]
  655. class_keep = tf.pad(tensor=class_keep, paddings=[(0, gap)],
  656. mode='CONSTANT', constant_values=-1)
  657. # Set shape so map_fn() can infer result shape
  658. class_keep.set_shape([config.DETECTION_MAX_INSTANCES])
  659. return class_keep
  660. # 2. Map over class IDs
  661. nms_keep = tf.map_fn(nms_keep_map, unique_pre_nms_class_ids,
  662. dtype=tf.int64)
  663. # 3. Merge results into one list, and remove -1 padding
  664. nms_keep = tf.reshape(nms_keep, [-1])
  665. nms_keep = tf.gather(nms_keep, tf.compat.v1.where(nms_keep > -1)[:, 0])
  666. # 4. Compute intersection between keep and nms_keep
  667. keep = tf.sets.intersection(tf.expand_dims(keep, 0),
  668. tf.expand_dims(nms_keep, 0))
  669. keep = tf.sparse.to_dense(keep)[0]
  670. # Keep top detections
  671. roi_count = config.DETECTION_MAX_INSTANCES
  672. class_scores_keep = tf.gather(class_scores, keep)
  673. num_keep = tf.minimum(tf.shape(input=class_scores_keep)[0], roi_count)
  674. top_ids = tf.nn.top_k(class_scores_keep, k=num_keep, sorted=True)[1]
  675. keep = tf.gather(keep, top_ids)
  676. # Arrange output as [N, (y1, x1, y2, x2, class_id, score)]
  677. # Coordinates are normalized.
  678. detections = tf.concat([
  679. tf.gather(refined_rois, keep),
  680. tf.dtypes.cast(tf.gather(class_ids, keep), tf.float32)[..., tf.newaxis],
  681. tf.gather(class_scores, keep)[..., tf.newaxis]
  682. ], axis=1)
  683. # Pad with zeros if detections < DETECTION_MAX_INSTANCES
  684. gap = config.DETECTION_MAX_INSTANCES - tf.shape(input=detections)[0]
  685. detections = tf.pad(tensor=detections, paddings=[(0, gap), (0, 0)], mode="CONSTANT")
  686. return detections
  687. class DetectionLayer(ModdedLayer):
  688. """Takes classified proposal boxes and their bounding box deltas and
  689. returns the final detection boxes.
  690. Returns:
  691. [batch, num_detections, (y1, x1, y2, x2, class_id, class_score)] where
  692. coordinates are normalized.
  693. """
  694. def __init__(self, config=None, **kwargs):
  695. super(DetectionLayer, self).__init__(**kwargs)
  696. self.config = config
  697. def get_config(self):
  698. config = super(DetectionLayer, self).get_config()
  699. config["config"] = self.config.to_dict()
  700. return config
  701. def call(self, inputs):
  702. rois = inputs[0]
  703. mrcnn_class = inputs[1]
  704. mrcnn_bbox = inputs[2]
  705. image_meta = inputs[3]
  706. # Get windows of images in normalized coordinates. Windows are the area
  707. # in the image that excludes the padding.
  708. # Use the shape of the first image in the batch to normalize the window
  709. # because we know that all images get resized to the same size.
  710. m = parse_image_meta_graph(image_meta)
  711. image_shape = m['image_shape'][0]
  712. window = norm_boxes_graph(m['window'], image_shape[:2])
  713. # Run detection refinement graph on each item in the batch
  714. detections_batch = utils.batch_slice(
  715. [rois, mrcnn_class, mrcnn_bbox, window],
  716. lambda x, y, w, z: refine_detections_graph(x, y, w, z, self.config),
  717. self.config.IMAGES_PER_GPU)
  718. # Reshape output
  719. # [batch, num_detections, (y1, x1, y2, x2, class_id, class_score)] in
  720. # normalized coordinates
  721. return tf.reshape(
  722. detections_batch,
  723. [self.config.BATCH_SIZE, self.config.DETECTION_MAX_INSTANCES, 6])
  724. def compute_output_shape(self, input_shape):
  725. return (None, self.config.DETECTION_MAX_INSTANCES, 6)
  726. ############################################################
  727. # Region Proposal Network (RPN)
  728. ############################################################
  729. def rpn_graph(feature_map, anchors_per_location, anchor_stride):
  730. """Builds the computation graph of Region Proposal Network.
  731. feature_map: backbone features [batch, height, width, depth]
  732. anchors_per_location: number of anchors per pixel in the feature map
  733. anchor_stride: Controls the density of anchors. Typically 1 (anchors for
  734. every pixel in the feature map), or 2 (every other pixel).
  735. Returns:
  736. rpn_class_logits: [batch, H * W * anchors_per_location, 2] Anchor classifier logits (before softmax)
  737. rpn_probs: [batch, H * W * anchors_per_location, 2] Anchor classifier probabilities.
  738. rpn_bbox: [batch, H * W * anchors_per_location, (dy, dx, log(dh), log(dw))] Deltas to be
  739. applied to anchors.
  740. """
  741. # TODO: check if stride of 2 causes alignment issues if the feature map
  742. # is not even.
  743. # Shared convolutional base of the RPN
  744. shared = KL.Conv2D(512, (3, 3), padding='same', activation='relu',
  745. strides=anchor_stride,
  746. name='rpn_conv_shared')(feature_map)
  747. # Anchor Score. [batch, height, width, anchors per location * 2].
  748. x = KL.Conv2D(2 * anchors_per_location, (1, 1), padding='valid',
  749. activation='linear', name='rpn_class_raw')(shared)
  750. # Reshape to [batch, anchors, 2]
  751. rpn_class_logits = KL.Lambda(
  752. lambda t: tf.reshape(t, [tf.shape(input=t)[0], -1, 2]))(x)
  753. # Softmax on last dimension of BG/FG.
  754. rpn_probs = KL.Activation(
  755. "softmax", name="rpn_class_xxx")(rpn_class_logits)
  756. # Bounding box refinement. [batch, H, W, anchors per location * depth]
  757. # where depth is [x, y, log(w), log(h)]
  758. x = KL.Conv2D(anchors_per_location * 4, (1, 1), padding="valid",
  759. activation='linear', name='rpn_bbox_pred')(shared)
  760. # Reshape to [batch, anchors, 4]
  761. rpn_bbox = KL.Lambda(lambda t: tf.reshape(t, [tf.shape(input=t)[0], -1, 4]))(x)
  762. return [rpn_class_logits, rpn_probs, rpn_bbox]
  763. def build_rpn_model(anchor_stride, anchors_per_location, depth):
  764. """Builds a Keras model of the Region Proposal Network.
  765. It wraps the RPN graph so it can be used multiple times with shared
  766. weights.
  767. anchors_per_location: number of anchors per pixel in the feature map
  768. anchor_stride: Controls the density of anchors. Typically 1 (anchors for
  769. every pixel in the feature map), or 2 (every other pixel).
  770. depth: Depth of the backbone feature map.
  771. Returns a Keras Model object. The model outputs, when called, are:
  772. rpn_class_logits: [batch, H * W * anchors_per_location, 2] Anchor classifier logits (before softmax)
  773. rpn_probs: [batch, H * W * anchors_per_location, 2] Anchor classifier probabilities.
  774. rpn_bbox: [batch, H * W * anchors_per_location, (dy, dx, log(dh), log(dw))] Deltas to be
  775. applied to anchors.
  776. """
  777. input_feature_map = KL.Input(shape=[None, None, depth],
  778. name="input_rpn_feature_map")
  779. outputs = rpn_graph(input_feature_map, anchors_per_location, anchor_stride)
  780. return KM.Model([input_feature_map], outputs, name="rpn_model")
  781. ############################################################
  782. # Feature Pyramid Network Heads
  783. ############################################################
  784. def fpn_classifier_graph(rois, feature_maps, image_meta,
  785. pool_size, num_classes, train_bn=True,
  786. fc_layers_size=1024):
  787. """Builds the computation graph of the feature pyramid network classifier
  788. and regressor heads.
  789. rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized
  790. coordinates.
  791. feature_maps: List of feature maps from different layers of the pyramid,
  792. [P2, P3, P4, P5]. Each has a different resolution.
  793. image_meta: [batch, (meta data)] Image details. See compose_image_meta()
  794. pool_size: The width of the square feature map generated from ROI Pooling.
  795. num_classes: number of classes, which determines the depth of the results
  796. train_bn: Boolean. Train or freeze Batch Norm layers
  797. fc_layers_size: Size of the 2 FC layers
  798. Returns:
  799. logits: [batch, num_rois, NUM_CLASSES] classifier logits (before softmax)
  800. probs: [batch, num_rois, NUM_CLASSES] classifier probabilities
  801. bbox_deltas: [batch, num_rois, NUM_CLASSES, (dy, dx, log(dh), log(dw))] Deltas to apply to
  802. proposal boxes
  803. """
  804. # ROI Pooling
  805. # Shape: [batch, num_rois, POOL_SIZE, POOL_SIZE, channels]
  806. x = PyramidROIAlign([pool_size, pool_size],
  807. name="roi_align_classifier")([rois, image_meta] + feature_maps)
  808. # Two 1024 FC layers (implemented with Conv2D for consistency)
  809. x = KL.TimeDistributed(KL.Conv2D(fc_layers_size, (pool_size, pool_size), padding="valid"),
  810. name="mrcnn_class_conv1")(x)
  811. x = KL.TimeDistributed(BatchNorm(), name='mrcnn_class_bn1')(x, training=train_bn)
  812. x = KL.Activation('relu')(x)
  813. x = KL.TimeDistributed(KL.Conv2D(fc_layers_size, (1, 1)),
  814. name="mrcnn_class_conv2")(x)
  815. x = KL.TimeDistributed(BatchNorm(), name='mrcnn_class_bn2')(x, training=train_bn)
  816. x = KL.Activation('relu')(x)
  817. shared = KL.Lambda(lambda x: K.squeeze(K.squeeze(x, 3), 2),
  818. name="pool_squeeze")(x)
  819. # Classifier head
  820. mrcnn_class_logits = KL.TimeDistributed(KL.Dense(num_classes),
  821. name='mrcnn_class_logits')(shared)
  822. mrcnn_probs = KL.TimeDistributed(KL.Activation("softmax"),
  823. name="mrcnn_class")(mrcnn_class_logits)
  824. # BBox head
  825. # [batch, num_rois, NUM_CLASSES * (dy, dx, log(dh), log(dw))]
  826. x = KL.TimeDistributed(KL.Dense(num_classes * 4, activation='linear'),
  827. name='mrcnn_bbox_fc')(shared)
  828. # Reshape to [batch, num_rois, NUM_CLASSES, (dy, dx, log(dh), log(dw))]
  829. s = K.int_shape(x)
  830. if s[1] is None:
  831. mrcnn_bbox = KL.Reshape((-1, num_classes, 4), name="mrcnn_bbox")(x)
  832. else:
  833. mrcnn_bbox = KL.Reshape((s[1], num_classes, 4), name="mrcnn_bbox")(x)
  834. return mrcnn_class_logits, mrcnn_probs, mrcnn_bbox
  835. def build_fpn_mask_graph(rois, feature_maps, image_meta,
  836. pool_size, num_classes, train_bn=True):
  837. """Builds the computation graph of the mask head of Feature Pyramid Network.
  838. rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized
  839. coordinates.
  840. feature_maps: List of feature maps from different layers of the pyramid,
  841. [P2, P3, P4, P5]. Each has a different resolution.
  842. image_meta: [batch, (meta data)] Image details. See compose_image_meta()
  843. pool_size: The width of the square feature map generated from ROI Pooling.
  844. num_classes: number of classes, which determines the depth of the results
  845. train_bn: Boolean. Train or freeze Batch Norm layers
  846. Returns: Masks [batch, num_rois, MASK_POOL_SIZE, MASK_POOL_SIZE, NUM_CLASSES]
  847. """
  848. # ROI Pooling
  849. # Shape: [batch, num_rois, MASK_POOL_SIZE, MASK_POOL_SIZE, channels]
  850. x = PyramidROIAlign([pool_size, pool_size],
  851. name="roi_align_mask")([rois, image_meta] + feature_maps)
  852. # Conv layers
  853. x = KL.TimeDistributed(KL.Conv2D(256, (3, 3), padding="same"),
  854. name="mrcnn_mask_conv1")(x)
  855. x = KL.TimeDistributed(BatchNorm(),
  856. name='mrcnn_mask_bn1')(x, training=train_bn)
  857. x = KL.Activation('relu')(x)
  858. x = KL.TimeDistributed(KL.Conv2D(256, (3, 3), padding="same"),
  859. name="mrcnn_mask_conv2")(x)
  860. x = KL.TimeDistributed(BatchNorm(),
  861. name='mrcnn_mask_bn2')(x, training=train_bn)
  862. x = KL.Activation('relu')(x)
  863. x = KL.TimeDistributed(KL.Conv2D(256, (3, 3), padding="same"),
  864. name="mrcnn_mask_conv3")(x)
  865. x = KL.TimeDistributed(BatchNorm(),
  866. name='mrcnn_mask_bn3')(x, training=train_bn)
  867. x = KL.Activation('relu')(x)
  868. x = KL.TimeDistributed(KL.Conv2D(256, (3, 3), padding="same"),
  869. name="mrcnn_mask_conv4")(x)
  870. x = KL.TimeDistributed(BatchNorm(),
  871. name='mrcnn_mask_bn4')(x, training=train_bn)
  872. x = KL.Activation('relu')(x)
  873. x = KL.TimeDistributed(KL.Conv2DTranspose(256, (2, 2), strides=2, activation="relu"),
  874. name="mrcnn_mask_deconv")(x)
  875. x = KL.TimeDistributed(KL.Conv2D(num_classes, (1, 1), strides=1, activation="sigmoid"),
  876. name="mrcnn_mask")(x)
  877. return x
  878. ############################################################
  879. # Loss Functions
  880. ############################################################
  881. def smooth_l1_loss(y_true, y_pred):
  882. """Implements Smooth-L1 loss.
  883. y_true and y_pred are typically: [N, 4], but could be any shape.
  884. """
  885. diff = K.abs(y_true - y_pred)
  886. less_than_one = K.cast(K.less(diff, 1.0), "float32")
  887. loss = (less_than_one * 0.5 * diff**2) + (1 - less_than_one) * (diff - 0.5)
  888. return loss
  889. def rpn_class_loss_graph(rpn_match, rpn_class_logits):
  890. """RPN anchor classifier loss.
  891. rpn_match: [batch, anchors, 1]. Anchor match type. 1=positive,
  892. -1=negative, 0=neutral anchor.
  893. rpn_class_logits: [batch, anchors, 2]. RPN classifier logits for BG/FG.
  894. """
  895. # Squeeze last dim to simplify
  896. rpn_match = tf.squeeze(rpn_match, -1)
  897. # Get anchor classes. Convert the -1/+1 match to 0/1 values.
  898. anchor_class = K.cast(K.equal(rpn_match, 1), tf.int32)
  899. # Positive and Negative anchors contribute to the loss,
  900. # but neutral anchors (match value = 0) don't.
  901. indices = tf.compat.v1.where(K.not_equal(rpn_match, 0))
  902. # Pick rows that contribute to the loss and filter out the rest.
  903. rpn_class_logits = tf.gather_nd(rpn_class_logits, indices)
  904. anchor_class = tf.gather_nd(anchor_class, indices)
  905. # Cross entropy loss
  906. loss = K.sparse_categorical_crossentropy(target=anchor_class,
  907. output=rpn_class_logits,
  908. from_logits=True)
  909. loss = K.switch(tf.size(input=loss) > 0, K.mean(loss), K.constant(0.0))
  910. return loss
  911. def rpn_bbox_loss_graph(config, target_bbox, rpn_match, rpn_bbox):
  912. """Return the RPN bounding box loss graph.
  913. config: the model config object.
  914. target_bbox: [batch, max positive anchors, (dy, dx, log(dh), log(dw))].
  915. Uses 0 padding to fill in unsed bbox deltas.
  916. rpn_match: [batch, anchors, 1]. Anchor match type. 1=positive,
  917. -1=negative, 0=neutral anchor.
  918. rpn_bbox: [batch, anchors, (dy, dx, log(dh), log(dw))]
  919. """
  920. # Positive anchors contribute to the loss, but negative and
  921. # neutral anchors (match value of 0 or -1) don't.
  922. rpn_match = K.squeeze(rpn_match, -1)
  923. indices = tf.compat.v1.where(K.equal(rpn_match, 1))
  924. # Pick bbox deltas that contribute to the loss
  925. rpn_bbox = tf.gather_nd(rpn_bbox, indices)
  926. # Trim target bounding box deltas to the same length as rpn_bbox.
  927. batch_counts = K.sum(K.cast(K.equal(rpn_match, 1), tf.int32), axis=1)
  928. target_bbox = batch_pack_graph(target_bbox, batch_counts,
  929. config.IMAGES_PER_GPU)
  930. loss = smooth_l1_loss(target_bbox, rpn_bbox)
  931. loss = K.switch(tf.size(input=loss) > 0, K.mean(loss), K.constant(0.0))
  932. return loss
  933. def mrcnn_class_loss_graph(target_class_ids, pred_class_logits,
  934. active_class_ids):
  935. """Loss for the classifier head of Mask RCNN.
  936. target_class_ids: [batch, num_rois]. Integer class IDs. Uses zero
  937. padding to fill in the array.
  938. pred_class_logits: [batch, num_rois, num_classes]
  939. active_class_ids: [batch, num_classes]. Has a value of 1 for
  940. classes that are in the dataset of the image, and 0
  941. for classes that are not in the dataset.
  942. """
  943. # During model building, Keras calls this function with
  944. # target_class_ids of type float32. Unclear why. Cast it
  945. # to int to get around it.
  946. target_class_ids = tf.cast(target_class_ids, 'int64')
  947. # Find predictions of classes that are not in the dataset.
  948. pred_class_ids = tf.argmax(input=pred_class_logits, axis=2)
  949. # TODO: Update this line to work with batch > 1. Right now it assumes all
  950. # images in a batch have the same active_class_ids
  951. pred_active = tf.gather(active_class_ids[0], pred_class_ids)
  952. # Loss
  953. loss = tf.nn.sparse_softmax_cross_entropy_with_logits(
  954. labels=target_class_ids, logits=pred_class_logits)
  955. # Erase losses of predictions of classes that are not in the active
  956. # classes of the image.
  957. loss = loss * pred_active
  958. # Computer loss mean. Use only predictions that contribute
  959. # to the loss to get a correct mean.
  960. loss = tf.reduce_sum(input_tensor=loss) / tf.reduce_sum(input_tensor=pred_active)
  961. return loss
  962. def mrcnn_bbox_loss_graph(target_bbox, target_class_ids, pred_bbox):
  963. """Loss for Mask R-CNN bounding box refinement.
  964. target_bbox: [batch, num_rois, (dy, dx, log(dh), log(dw))]
  965. target_class_ids: [batch, num_rois]. Integer class IDs.
  966. pred_bbox: [batch, num_rois, num_classes, (dy, dx, log(dh), log(dw))]
  967. """
  968. # Reshape to merge batch and roi dimensions for simplicity.
  969. target_class_ids = K.reshape(target_class_ids, (-1,))
  970. target_bbox = K.reshape(target_bbox, (-1, 4))
  971. pred_bbox = K.reshape(pred_bbox, (-1, K.int_shape(pred_bbox)[2], 4))
  972. # Only positive ROIs contribute to the loss. And only
  973. # the right class_id of each ROI. Get their indices.
  974. positive_roi_ix = tf.compat.v1.where(target_class_ids > 0)[:, 0]
  975. positive_roi_class_ids = tf.cast(
  976. tf.gather(target_class_ids, positive_roi_ix), tf.int64)
  977. indices = tf.stack([positive_roi_ix, positive_roi_class_ids], axis=1)
  978. # Gather the deltas (predicted and true) that contribute to loss
  979. target_bbox = tf.gather(target_bbox, positive_roi_ix)
  980. pred_bbox = tf.gather_nd(pred_bbox, indices)
  981. # Smooth-L1 Loss
  982. loss = K.switch(tf.size(input=target_bbox) > 0,
  983. smooth_l1_loss(y_true=target_bbox, y_pred=pred_bbox),
  984. K.constant(0.0))
  985. loss = K.mean(loss)
  986. return loss
  987. def mrcnn_mask_loss_graph(target_masks, target_class_ids, pred_masks):
  988. """Mask binary cross-entropy loss for the masks head.
  989. target_masks: [batch, num_rois, height, width].
  990. A float32 tensor of values 0 or 1. Uses zero padding to fill array.
  991. target_class_ids: [batch, num_rois]. Integer class IDs. Zero padded.
  992. pred_masks: [batch, proposals, height, width, num_classes] float32 tensor
  993. with values from 0 to 1.
  994. """
  995. # Reshape for simplicity. Merge first two dimensions into one.
  996. target_class_ids = K.reshape(target_class_ids, (-1,))
  997. mask_shape = tf.shape(input=target_masks)
  998. target_masks = K.reshape(target_masks, (-1, mask_shape[2], mask_shape[3]))
  999. pred_shape = tf.shape(input=pred_masks)
  1000. pred_masks = K.reshape(pred_masks,
  1001. (-1, pred_shape[2], pred_shape[3], pred_shape[4]))
  1002. # Permute predicted masks to [N, num_classes, height, width]
  1003. pred_masks = tf.transpose(a=pred_masks, perm=[0, 3, 1, 2])
  1004. # Only positive ROIs contribute to the loss. And only
  1005. # the class specific mask of each ROI.
  1006. positive_ix = tf.compat.v1.where(target_class_ids > 0)[:, 0]
  1007. positive_class_ids = tf.cast(
  1008. tf.gather(target_class_ids, positive_ix), tf.int64)
  1009. indices = tf.stack([positive_ix, positive_class_ids], axis=1)
  1010. # Gather the masks (predicted and true) that contribute to loss
  1011. y_true = tf.gather(target_masks, positive_ix)
  1012. y_pred = tf.gather_nd(pred_masks, indices)
  1013. # Compute binary cross entropy. If no positive ROIs, then return 0.
  1014. # shape: [batch, roi, num_classes]
  1015. loss = K.switch(tf.size(input=y_true) > 0,
  1016. K.binary_crossentropy(target=y_true, output=y_pred),
  1017. K.constant(0.0))
  1018. loss = K.mean(loss)
  1019. return loss
  1020. ############################################################
  1021. # Data Generator
  1022. ############################################################
  1023. def load_image_gt(dataset, config, image_id, augmentation=None):
  1024. """Load and return ground truth data for an image (image, mask, bounding boxes).
  1025. augmentation: Optional. An imgaug (https://github.com/aleju/imgaug) augmentation.
  1026. For example, passing imgaug.augmenters.Fliplr(0.5) flips images
  1027. right/left 50% of the time.
  1028. Returns:
  1029. image: [height, width, 3]
  1030. shape: the original shape of the image before resizing and cropping.
  1031. class_ids: [instance_count] Integer class IDs
  1032. bbox: [instance_count, (y1, x1, y2, x2)]
  1033. mask: [height, width, instance_count]. The height and width are those
  1034. of the image unless use_mini_mask is True, in which case they are
  1035. defined in MINI_MASK_SHAPE.
  1036. """
  1037. # Load image and mask
  1038. image = dataset.load_image(image_id)
  1039. mask, class_ids = dataset.load_mask(image_id)
  1040. original_shape = image.shape
  1041. image, window, scale, padding, crop = utils.resize_image(
  1042. image,
  1043. min_dim=config.IMAGE_MIN_DIM,
  1044. min_scale=config.IMAGE_MIN_SCALE,
  1045. max_dim=config.IMAGE_MAX_DIM,
  1046. mode=config.IMAGE_RESIZE_MODE)
  1047. mask = utils.resize_mask(mask, scale, padding, crop)
  1048. # Augmentation
  1049. # This requires the imgaug lib (https://github.com/aleju/imgaug)
  1050. if augmentation:
  1051. import imgaug
  1052. # Augmenters that are safe to apply to masks
  1053. # Some, such as Affine, have settings that make them unsafe, so always
  1054. # test your augmentation on masks
  1055. MASK_AUGMENTERS = ["Sequential", "SomeOf", "OneOf", "Sometimes",
  1056. "Fliplr", "Flipud", "CropAndPad",
  1057. "Affine", "PiecewiseAffine"]
  1058. def hook(images, augmenter, parents, default):
  1059. """Determines which augmenters to apply to masks."""
  1060. return augmenter.__class__.__name__ in MASK_AUGMENTERS
  1061. # Store shapes before augmentation to compare
  1062. image_shape = image.shape
  1063. mask_shape = mask.shape
  1064. # Make augmenters deterministic to apply similarly to images and masks
  1065. det = augmentation.to_deterministic()
  1066. image = det.augment_image(image)
  1067. # Change mask to np.uint8 because imgaug doesn't support np.bool
  1068. mask = det.augment_image(mask.astype(np.uint8),
  1069. hooks=imgaug.HooksImages(activator=hook))
  1070. # Verify that shapes didn't change
  1071. assert image.shape == image_shape, "Augmentation shouldn't change image size"
  1072. assert mask.shape == mask_shape, "Augmentation shouldn't change mask size"
  1073. # Change mask back to bool
  1074. mask = mask.astype(np.bool)
  1075. # Note that some boxes might be all zeros if the corresponding mask got cropped out.
  1076. # and here is to filter them out
  1077. _idx = np.sum(mask, axis=(0, 1)) > 0
  1078. mask = mask[:, :, _idx]
  1079. class_ids = class_ids[_idx]
  1080. # Bounding boxes. Note that some boxes might be all zeros
  1081. # if the corresponding mask got cropped out.
  1082. # bbox: [num_instances, (y1, x1, y2, x2)]
  1083. bbox = utils.extract_bboxes(mask)
  1084. # Active classes
  1085. # Different datasets have different classes, so track the
  1086. # classes supported in the dataset of this image.
  1087. active_class_ids = np.zeros([dataset.num_classes], dtype=np.int32)
  1088. source_class_ids = dataset.source_class_ids[dataset.image_info[image_id]["source"]]
  1089. active_class_ids[source_class_ids] = 1
  1090. # Resize masks to smaller size to reduce memory usage
  1091. if config.USE_MINI_MASK:
  1092. mask = utils.minimize_mask(bbox, mask, config.MINI_MASK_SHAPE)
  1093. # Image meta data
  1094. image_meta = compose_image_meta(image_id, original_shape, image.shape,
  1095. window, scale, active_class_ids)
  1096. return image, image_meta, class_ids, bbox, mask
  1097. def build_detection_targets(rpn_rois, gt_class_ids, gt_boxes, gt_masks, config):
  1098. """Generate targets for training Stage 2 classifier and mask heads.
  1099. This is not used in normal training. It's useful for debugging or to train
  1100. the Mask RCNN heads without using the RPN head.
  1101. Inputs:
  1102. rpn_rois: [N, (y1, x1, y2, x2)] proposal boxes.
  1103. gt_class_ids: [instance count] Integer class IDs
  1104. gt_boxes: [instance count, (y1, x1, y2, x2)]
  1105. gt_masks: [height, width, instance count] Ground truth masks. Can be full
  1106. size or mini-masks.
  1107. Returns:
  1108. rois: [TRAIN_ROIS_PER_IMAGE, (y1, x1, y2, x2)]
  1109. class_ids: [TRAIN_ROIS_PER_IMAGE]. Integer class IDs.
  1110. bboxes: [TRAIN_ROIS_PER_IMAGE, NUM_CLASSES, (y, x, log(h), log(w))]. Class-specific
  1111. bbox refinements.
  1112. masks: [TRAIN_ROIS_PER_IMAGE, height, width, NUM_CLASSES). Class specific masks cropped
  1113. to bbox boundaries and resized to neural network output size.
  1114. """
  1115. assert rpn_rois.shape[0] > 0
  1116. assert gt_class_ids.dtype == np.int32, "Expected int but got {}".format(
  1117. gt_class_ids.dtype)
  1118. assert gt_boxes.dtype == np.int32, "Expected int but got {}".format(
  1119. gt_boxes.dtype)
  1120. assert gt_masks.dtype == np.bool_, "Expected bool but got {}".format(
  1121. gt_masks.dtype)
  1122. # It's common to add GT Boxes to ROIs but we don't do that here because
  1123. # according to XinLei Chen's paper, it doesn't help.
  1124. # Trim empty padding in gt_boxes and gt_masks parts
  1125. instance_ids = np.where(gt_class_ids > 0)[0]
  1126. assert instance_ids.shape[0] > 0, "Image must contain instances."
  1127. gt_class_ids = gt_class_ids[instance_ids]
  1128. gt_boxes = gt_boxes[instance_ids]
  1129. gt_masks = gt_masks[:, :, instance_ids]
  1130. # Compute areas of ROIs and ground truth boxes.
  1131. rpn_roi_area = (rpn_rois[:, 2] - rpn_rois[:, 0]) * \
  1132. (rpn_rois[:, 3] - rpn_rois[:, 1])
  1133. gt_box_area = (gt_boxes[:, 2] - gt_boxes[:, 0]) * \
  1134. (gt_boxes[:, 3] - gt_boxes[:, 1])
  1135. # Compute overlaps [rpn_rois, gt_boxes]
  1136. overlaps = np.zeros((rpn_rois.shape[0], gt_boxes.shape[0]))
  1137. for i in range(overlaps.shape[1]):
  1138. gt = gt_boxes[i]
  1139. overlaps[:, i] = utils.compute_iou(
  1140. gt, rpn_rois, gt_box_area[i], rpn_roi_area)
  1141. # Assign ROIs to GT boxes
  1142. rpn_roi_iou_argmax = np.argmax(overlaps, axis=1)
  1143. rpn_roi_iou_max = overlaps[np.arange(
  1144. overlaps.shape[0]), rpn_roi_iou_argmax]
  1145. # GT box assigned to each ROI
  1146. rpn_roi_gt_boxes = gt_boxes[rpn_roi_iou_argmax]
  1147. rpn_roi_gt_class_ids = gt_class_ids[rpn_roi_iou_argmax]
  1148. # Positive ROIs are those with >= 0.5 IoU with a GT box.
  1149. fg_ids = np.where(rpn_roi_iou_max > 0.5)[0]
  1150. # Negative ROIs are those with max IoU 0.1-0.5 (hard example mining)
  1151. # TODO: To hard example mine or not to hard example mine, that's the question
  1152. # bg_ids = np.where((rpn_roi_iou_max >= 0.1) & (rpn_roi_iou_max < 0.5))[0]
  1153. bg_ids = np.where(rpn_roi_iou_max < 0.5)[0]
  1154. # Subsample ROIs. Aim for 33% foreground.
  1155. # FG
  1156. fg_roi_count = int(config.TRAIN_ROIS_PER_IMAGE * config.ROI_POSITIVE_RATIO)
  1157. if fg_ids.shape[0] > fg_roi_count:
  1158. keep_fg_ids = np.random.choice(fg_ids, fg_roi_count, replace=False)
  1159. else:
  1160. keep_fg_ids = fg_ids
  1161. # BG
  1162. remaining = config.TRAIN_ROIS_PER_IMAGE - keep_fg_ids.shape[0]
  1163. if bg_ids.shape[0] > remaining:
  1164. keep_bg_ids = np.random.choice(bg_ids, remaining, replace=False)
  1165. else:
  1166. keep_bg_ids = bg_ids
  1167. # Combine indices of ROIs to keep
  1168. keep = np.concatenate([keep_fg_ids, keep_bg_ids])
  1169. # Need more?
  1170. remaining = config.TRAIN_ROIS_PER_IMAGE - keep.shape[0]
  1171. if remaining > 0:
  1172. # Looks like we don't have enough samples to maintain the desired
  1173. # balance. Reduce requirements and fill in the rest. This is
  1174. # likely different from the Mask RCNN paper.
  1175. # There is a small chance we have neither fg nor bg samples.
  1176. if keep.shape[0] == 0:
  1177. # Pick bg regions with easier IoU threshold
  1178. bg_ids = np.where(rpn_roi_iou_max < 0.5)[0]
  1179. assert bg_ids.shape[0] >= remaining
  1180. keep_bg_ids = np.random.choice(bg_ids, remaining, replace=False)
  1181. assert keep_bg_ids.shape[0] == remaining
  1182. keep = np.concatenate([keep, keep_bg_ids])
  1183. else:
  1184. # Fill the rest with repeated bg rois.
  1185. keep_extra_ids = np.random.choice(
  1186. keep_bg_ids, remaining, replace=True)
  1187. keep = np.concatenate([keep, keep_extra_ids])
  1188. assert keep.shape[0] == config.TRAIN_ROIS_PER_IMAGE, \
  1189. "keep doesn't match ROI batch size {}, {}".format(
  1190. keep.shape[0], config.TRAIN_ROIS_PER_IMAGE)
  1191. # Reset the gt boxes assigned to BG ROIs.
  1192. rpn_roi_gt_boxes[keep_bg_ids, :] = 0
  1193. rpn_roi_gt_class_ids[keep_bg_ids] = 0
  1194. # For each kept ROI, assign a class_id, and for FG ROIs also add bbox refinement.
  1195. rois = rpn_rois[keep]
  1196. roi_gt_boxes = rpn_roi_gt_boxes[keep]
  1197. roi_gt_class_ids = rpn_roi_gt_class_ids[keep]
  1198. roi_gt_assignment = rpn_roi_iou_argmax[keep]
  1199. # Class-aware bbox deltas. [y, x, log(h), log(w)]
  1200. bboxes = np.zeros((config.TRAIN_ROIS_PER_IMAGE,
  1201. config.NUM_CLASSES, 4), dtype=np.float32)
  1202. pos_ids = np.where(roi_gt_class_ids > 0)[0]
  1203. bboxes[pos_ids, roi_gt_class_ids[pos_ids]] = utils.box_refinement(
  1204. rois[pos_ids], roi_gt_boxes[pos_ids, :4])
  1205. # Normalize bbox refinements
  1206. bboxes /= config.BBOX_STD_DEV
  1207. # Generate class-specific target masks
  1208. masks = np.zeros((config.TRAIN_ROIS_PER_IMAGE, config.MASK_SHAPE[0], config.MASK_SHAPE[1], config.NUM_CLASSES),
  1209. dtype=np.float32)
  1210. for i in pos_ids:
  1211. class_id = roi_gt_class_ids[i]
  1212. assert class_id > 0, "class id must be greater than 0"
  1213. gt_id = roi_gt_assignment[i]
  1214. class_mask = gt_masks[:, :, gt_id]
  1215. if config.USE_MINI_MASK:
  1216. # Create a mask placeholder, the size of the image
  1217. placeholder = np.zeros(config.IMAGE_SHAPE[:2], dtype=bool)
  1218. # GT box
  1219. gt_y1, gt_x1, gt_y2, gt_x2 = gt_boxes[gt_id]
  1220. gt_w = gt_x2 - gt_x1
  1221. gt_h = gt_y2 - gt_y1
  1222. # Resize mini mask to size of GT box
  1223. placeholder[gt_y1:gt_y2, gt_x1:gt_x2] = \
  1224. np.round(utils.resize(class_mask, (gt_h, gt_w))).astype(bool)
  1225. # Place the mini batch in the placeholder
  1226. class_mask = placeholder
  1227. # Pick part of the mask and resize it
  1228. y1, x1, y2, x2 = rois[i].astype(np.int32)
  1229. m = class_mask[y1:y2, x1:x2]
  1230. mask = utils.resize(m, config.MASK_SHAPE)
  1231. masks[i, :, :, class_id] = mask
  1232. return rois, roi_gt_class_ids, bboxes, masks
  1233. def build_rpn_targets(image_shape, anchors, gt_class_ids, gt_boxes, config):
  1234. """Given the anchors and GT boxes, compute overlaps and identify positive
  1235. anchors and deltas to refine them to match their corresponding GT boxes.
  1236. anchors: [num_anchors, (y1, x1, y2, x2)]
  1237. gt_class_ids: [num_gt_boxes] Integer class IDs.
  1238. gt_boxes: [num_gt_boxes, (y1, x1, y2, x2)]
  1239. Returns:
  1240. rpn_match: [N] (int32) matches between anchors and GT boxes.
  1241. 1 = positive anchor, -1 = negative anchor, 0 = neutral
  1242. rpn_bbox: [N, (dy, dx, log(dh), log(dw))] Anchor bbox deltas.
  1243. """
  1244. # RPN Match: 1 = positive anchor, -1 = negative anchor, 0 = neutral
  1245. rpn_match = np.zeros([anchors.shape[0]], dtype=np.int32)
  1246. # RPN bounding boxes: [max anchors per image, (dy, dx, log(dh), log(dw))]
  1247. rpn_bbox = np.zeros((config.RPN_TRAIN_ANCHORS_PER_IMAGE, 4))
  1248. # Handle COCO crowds
  1249. # A crowd box in COCO is a bounding box around several instances. Exclude
  1250. # them from training. A crowd box is given a negative class ID.
  1251. crowd_ix = np.where(gt_class_ids < 0)[0]
  1252. if crowd_ix.shape[0] > 0:
  1253. # Filter out crowds from ground truth class IDs and boxes
  1254. non_crowd_ix = np.where(gt_class_ids > 0)[0]
  1255. crowd_boxes = gt_boxes[crowd_ix]
  1256. gt_class_ids = gt_class_ids[non_crowd_ix]
  1257. gt_boxes = gt_boxes[non_crowd_ix]
  1258. # Compute overlaps with crowd boxes [anchors, crowds]
  1259. crowd_overlaps = utils.compute_overlaps(anchors, crowd_boxes)
  1260. crowd_iou_max = np.amax(crowd_overlaps, axis=1)
  1261. no_crowd_bool = (crowd_iou_max < 0.001)
  1262. else:
  1263. # All anchors don't intersect a crowd
  1264. no_crowd_bool = np.ones([anchors.shape[0]], dtype=bool)
  1265. # Compute overlaps [num_anchors, num_gt_boxes]
  1266. overlaps = utils.compute_overlaps(anchors, gt_boxes)
  1267. # Match anchors to GT Boxes
  1268. # If an anchor overlaps a GT box with IoU >= 0.7 then it's positive.
  1269. # If an anchor overlaps a GT box with IoU < 0.3 then it's negative.
  1270. # Neutral anchors are those that don't match the conditions above,
  1271. # and they don't influence the loss function.
  1272. # However, don't keep any GT box unmatched (rare, but happens). Instead,
  1273. # match it to the closest anchor (even if its max IoU is < 0.3).
  1274. #
  1275. # 1. Set negative anchors first. They get overwritten below if a GT box is
  1276. # matched to them. Skip boxes in crowd areas.
  1277. anchor_iou_argmax = np.argmax(overlaps, axis=1)
  1278. anchor_iou_max = overlaps[np.arange(overlaps.shape[0]), anchor_iou_argmax]
  1279. rpn_match[(anchor_iou_max < 0.3) & (no_crowd_bool)] = -1
  1280. # 2. Set an anchor for each GT box (regardless of IoU value).
  1281. # If multiple anchors have the same IoU match all of them
  1282. gt_iou_argmax = np.argwhere(overlaps == np.max(overlaps, axis=0))[:,0]
  1283. rpn_match[gt_iou_argmax] = 1
  1284. # 3. Set anchors with high overlap as positive.
  1285. rpn_match[anchor_iou_max >= 0.7] = 1
  1286. # Subsample to balance positive and negative anchors
  1287. # Don't let positives be more than half the anchors
  1288. ids = np.where(rpn_match == 1)[0]
  1289. extra = len(ids) - (config.RPN_TRAIN_ANCHORS_PER_IMAGE // 2)
  1290. if extra > 0:
  1291. # Reset the extra ones to neutral
  1292. ids = np.random.choice(ids, extra, replace=False)
  1293. rpn_match[ids] = 0
  1294. # Same for negative proposals
  1295. ids = np.where(rpn_match == -1)[0]
  1296. extra = len(ids) - (config.RPN_TRAIN_ANCHORS_PER_IMAGE -
  1297. np.sum(rpn_match == 1))
  1298. if extra > 0:
  1299. # Rest the extra ones to neutral
  1300. ids = np.random.choice(ids, extra, replace=False)
  1301. rpn_match[ids] = 0
  1302. # For positive anchors, compute shift and scale needed to transform them
  1303. # to match the corresponding GT boxes.
  1304. ids = np.where(rpn_match == 1)[0]
  1305. ix = 0 # index into rpn_bbox
  1306. # TODO: use box_refinement() rather than duplicating the code here
  1307. for i, a in zip(ids, anchors[ids]):
  1308. # Closest gt box (it might have IoU < 0.7)
  1309. gt = gt_boxes[anchor_iou_argmax[i]]
  1310. # Convert coordinates to center plus width/height.
  1311. # GT Box
  1312. gt_h = gt[2] - gt[0]
  1313. gt_w = gt[3] - gt[1]
  1314. gt_center_y = gt[0] + 0.5 * gt_h
  1315. gt_center_x = gt[1] + 0.5 * gt_w
  1316. # Anchor
  1317. a_h = a[2] - a[0]
  1318. a_w = a[3] - a[1]
  1319. a_center_y = a[0] + 0.5 * a_h
  1320. a_center_x = a[1] + 0.5 * a_w
  1321. # Compute the bbox refinement that the RPN should predict.
  1322. rpn_bbox[ix] = [
  1323. (gt_center_y - a_center_y) / a_h,
  1324. (gt_center_x - a_center_x) / a_w,
  1325. np.log(gt_h / a_h),
  1326. np.log(gt_w / a_w),
  1327. ]
  1328. # Normalize
  1329. rpn_bbox[ix] /= config.RPN_BBOX_STD_DEV
  1330. ix += 1
  1331. return rpn_match, rpn_bbox
  1332. def generate_random_rois(image_shape, count, gt_class_ids, gt_boxes):
  1333. """Generates ROI proposals similar to what a region proposal network
  1334. would generate.
  1335. image_shape: [Height, Width, Depth]
  1336. count: Number of ROIs to generate
  1337. gt_class_ids: [N] Integer ground truth class IDs
  1338. gt_boxes: [N, (y1, x1, y2, x2)] Ground truth boxes in pixels.
  1339. Returns: [count, (y1, x1, y2, x2)] ROI boxes in pixels.
  1340. """
  1341. # placeholder
  1342. rois = np.zeros((count, 4), dtype=np.int32)
  1343. # Generate random ROIs around GT boxes (90% of count)
  1344. rois_per_box = int(0.9 * count / gt_boxes.shape[0])
  1345. for i in range(gt_boxes.shape[0]):
  1346. gt_y1, gt_x1, gt_y2, gt_x2 = gt_boxes[i]
  1347. h = gt_y2 - gt_y1
  1348. w = gt_x2 - gt_x1
  1349. # random boundaries
  1350. r_y1 = max(gt_y1 - h, 0)
  1351. r_y2 = min(gt_y2 + h, image_shape[0])
  1352. r_x1 = max(gt_x1 - w, 0)
  1353. r_x2 = min(gt_x2 + w, image_shape[1])
  1354. # To avoid generating boxes with zero area, we generate double what
  1355. # we need and filter out the extra. If we get fewer valid boxes
  1356. # than we need, we loop and try again.
  1357. while True:
  1358. y1y2 = np.random.randint(r_y1, r_y2, (rois_per_box * 2, 2))
  1359. x1x2 = np.random.randint(r_x1, r_x2, (rois_per_box * 2, 2))
  1360. # Filter out zero area boxes
  1361. threshold = 1
  1362. y1y2 = y1y2[np.abs(y1y2[:, 0] - y1y2[:, 1]) >=
  1363. threshold][:rois_per_box]
  1364. x1x2 = x1x2[np.abs(x1x2[:, 0] - x1x2[:, 1]) >=
  1365. threshold][:rois_per_box]
  1366. if y1y2.shape[0] == rois_per_box and x1x2.shape[0] == rois_per_box:
  1367. break
  1368. # Sort on axis 1 to ensure x1 <= x2 and y1 <= y2 and then reshape
  1369. # into x1, y1, x2, y2 order
  1370. x1, x2 = np.split(np.sort(x1x2, axis=1), 2, axis=1)
  1371. y1, y2 = np.split(np.sort(y1y2, axis=1), 2, axis=1)
  1372. box_rois = np.hstack([y1, x1, y2, x2])
  1373. rois[rois_per_box * i:rois_per_box * (i + 1)] = box_rois
  1374. # Generate random ROIs anywhere in the image (10% of count)
  1375. remaining_count = count - (rois_per_box * gt_boxes.shape[0])
  1376. # To avoid generating boxes with zero area, we generate double what
  1377. # we need and filter out the extra. If we get fewer valid boxes
  1378. # than we need, we loop and try again.
  1379. while True:
  1380. y1y2 = np.random.randint(0, image_shape[0], (remaining_count * 2, 2))
  1381. x1x2 = np.random.randint(0, image_shape[1], (remaining_count * 2, 2))
  1382. # Filter out zero area boxes
  1383. threshold = 1
  1384. y1y2 = y1y2[np.abs(y1y2[:, 0] - y1y2[:, 1]) >=
  1385. threshold][:remaining_count]
  1386. x1x2 = x1x2[np.abs(x1x2[:, 0] - x1x2[:, 1]) >=
  1387. threshold][:remaining_count]
  1388. if y1y2.shape[0] == remaining_count and x1x2.shape[0] == remaining_count:
  1389. break
  1390. # Sort on axis 1 to ensure x1 <= x2 and y1 <= y2 and then reshape
  1391. # into x1, y1, x2, y2 order
  1392. x1, x2 = np.split(np.sort(x1x2, axis=1), 2, axis=1)
  1393. y1, y2 = np.split(np.sort(y1y2, axis=1), 2, axis=1)
  1394. global_rois = np.hstack([y1, x1, y2, x2])
  1395. rois[-remaining_count:] = global_rois
  1396. return rois
  1397. class DataGenerator(KU.Sequence):
  1398. """An iterable that returns images and corresponding target class ids,
  1399. bounding box deltas, and masks. It inherits from keras.utils.Sequence to avoid data redundancy
  1400. when multiprocessing=True.
  1401. dataset: The Dataset object to pick data from
  1402. config: The model config object
  1403. shuffle: If True, shuffles the samples before every epoch
  1404. augmentation: Optional. An imgaug (https://github.com/aleju/imgaug) augmentation.
  1405. For example, passing imgaug.augmenters.Fliplr(0.5) flips images
  1406. right/left 50% of the time.
  1407. random_rois: If > 0 then generate proposals to be used to train the
  1408. network classifier and mask heads. Useful if training
  1409. the Mask RCNN part without the RPN.
  1410. detection_targets: If True, generate detection targets (class IDs, bbox
  1411. deltas, and masks). Typically for debugging or visualizations because
  1412. in trainig detection targets are generated by DetectionTargetLayer.
  1413. Returns a Python iterable. Upon calling __getitem__() on it, the
  1414. iterable returns two lists, inputs and outputs. The contents
  1415. of the lists differ depending on the received arguments:
  1416. inputs list:
  1417. - images: [batch, H, W, C]
  1418. - image_meta: [batch, (meta data)] Image details. See compose_image_meta()
  1419. - rpn_match: [batch, N] Integer (1=positive anchor, -1=negative, 0=neutral)
  1420. - rpn_bbox: [batch, N, (dy, dx, log(dh), log(dw))] Anchor bbox deltas.
  1421. - gt_class_ids: [batch, MAX_GT_INSTANCES] Integer class IDs
  1422. - gt_boxes: [batch, MAX_GT_INSTANCES, (y1, x1, y2, x2)]
  1423. - gt_masks: [batch, height, width, MAX_GT_INSTANCES]. The height and width
  1424. are those of the image unless use_mini_mask is True, in which
  1425. case they are defined in MINI_MASK_SHAPE.
  1426. outputs list: Usually empty in regular training. But if detection_targets
  1427. is True then the outputs list contains target class_ids, bbox deltas,
  1428. and masks.
  1429. """
  1430. def __init__(self, dataset, config, shuffle=True, augmentation=None,
  1431. random_rois=0, detection_targets=False):
  1432. self.image_ids = np.copy(dataset.image_ids)
  1433. self.dataset = dataset
  1434. self.config = config
  1435. # Anchors
  1436. # [anchor_count, (y1, x1, y2, x2)]
  1437. self.backbone_shapes = compute_backbone_shapes(config, config.IMAGE_SHAPE)
  1438. self.anchors = utils.generate_pyramid_anchors(config.RPN_ANCHOR_SCALES,
  1439. config.RPN_ANCHOR_RATIOS,
  1440. self.backbone_shapes,
  1441. config.BACKBONE_STRIDES,
  1442. config.RPN_ANCHOR_STRIDE)
  1443. self.shuffle = shuffle
  1444. self.augmentation = augmentation
  1445. self.random_rois = random_rois
  1446. self.batch_size = self.config.BATCH_SIZE
  1447. self.detection_targets = detection_targets
  1448. def __len__(self):
  1449. return int(np.ceil(len(self.image_ids) / float(self.batch_size)))
  1450. def __getitem__(self, idx):
  1451. b = 0
  1452. image_index = -1
  1453. while b < self.batch_size:
  1454. # Increment index to pick next image. Shuffle if at the start of an epoch.
  1455. image_index = (image_index + 1) % len(self.image_ids)
  1456. if self.shuffle and image_index == 0:
  1457. np.random.shuffle(self.image_ids)
  1458. # Get GT bounding boxes and masks for image.
  1459. image_id = self.image_ids[image_index]
  1460. image, image_meta, gt_class_ids, gt_boxes, gt_masks = \
  1461. load_image_gt(self.dataset, self.config, image_id,
  1462. augmentation=self.augmentation)
  1463. # Skip images that have no instances. This can happen in cases
  1464. # where we train on a subset of classes and the image doesn't
  1465. # have any of the classes we care about.
  1466. if not np.any(gt_class_ids > 0):
  1467. continue
  1468. # RPN Targets
  1469. rpn_match, rpn_bbox = build_rpn_targets(image.shape, self.anchors,
  1470. gt_class_ids, gt_boxes, self.config)
  1471. # Mask R-CNN Targets
  1472. if self.random_rois:
  1473. rpn_rois = generate_random_rois(
  1474. image.shape, self.random_rois, gt_class_ids, gt_boxes)
  1475. if self.detection_targets:
  1476. rois, mrcnn_class_ids, mrcnn_bbox, mrcnn_mask = \
  1477. build_detection_targets(
  1478. rpn_rois, gt_class_ids, gt_boxes, gt_masks, self.config)
  1479. # Init batch arrays
  1480. if b == 0:
  1481. batch_image_meta = np.zeros(
  1482. (self.batch_size,) + image_meta.shape, dtype=image_meta.dtype)
  1483. batch_rpn_match = np.zeros(
  1484. [self.batch_size, self.anchors.shape[0], 1], dtype=rpn_match.dtype)
  1485. batch_rpn_bbox = np.zeros(
  1486. [self.batch_size, self.config.RPN_TRAIN_ANCHORS_PER_IMAGE, 4], dtype=rpn_bbox.dtype)
  1487. batch_images = np.zeros(
  1488. (self.batch_size,) + image.shape, dtype=np.float32)
  1489. batch_gt_class_ids = np.zeros(
  1490. (self.batch_size, self.config.MAX_GT_INSTANCES), dtype=np.int32)
  1491. batch_gt_boxes = np.zeros(
  1492. (self.batch_size, self.config.MAX_GT_INSTANCES, 4), dtype=np.int32)
  1493. batch_gt_masks = np.zeros(
  1494. (self.batch_size, gt_masks.shape[0], gt_masks.shape[1],
  1495. self.config.MAX_GT_INSTANCES), dtype=gt_masks.dtype)
  1496. if self.random_rois:
  1497. batch_rpn_rois = np.zeros(
  1498. (self.batch_size, rpn_rois.shape[0], 4), dtype=rpn_rois.dtype)
  1499. if self.detection_targets:
  1500. batch_rois = np.zeros(
  1501. (self.batch_size,) + rois.shape, dtype=rois.dtype)
  1502. batch_mrcnn_class_ids = np.zeros(
  1503. (self.batch_size,) + mrcnn_class_ids.shape, dtype=mrcnn_class_ids.dtype)
  1504. batch_mrcnn_bbox = np.zeros(
  1505. (self.batch_size,) + mrcnn_bbox.shape, dtype=mrcnn_bbox.dtype)
  1506. batch_mrcnn_mask = np.zeros(
  1507. (self.batch_size,) + mrcnn_mask.shape, dtype=mrcnn_mask.dtype)
  1508. # If more instances than fits in the array, sub-sample from them.
  1509. if gt_boxes.shape[0] > self.config.MAX_GT_INSTANCES:
  1510. ids = np.random.choice(
  1511. np.arange(gt_boxes.shape[0]), self.config.MAX_GT_INSTANCES, replace=False)
  1512. gt_class_ids = gt_class_ids[ids]
  1513. gt_boxes = gt_boxes[ids]
  1514. gt_masks = gt_masks[:, :, ids]
  1515. # Add to batch
  1516. batch_image_meta[b] = image_meta
  1517. batch_rpn_match[b] = rpn_match[:, np.newaxis]
  1518. batch_rpn_bbox[b] = rpn_bbox
  1519. batch_images[b] = mold_image(image.astype(np.float32), self.config)
  1520. batch_gt_class_ids[b, :gt_class_ids.shape[0]] = gt_class_ids
  1521. batch_gt_boxes[b, :gt_boxes.shape[0]] = gt_boxes
  1522. batch_gt_masks[b, :, :, :gt_masks.shape[-1]] = gt_masks
  1523. if self.random_rois:
  1524. batch_rpn_rois[b] = rpn_rois
  1525. if self.detection_targets:
  1526. batch_rois[b] = rois
  1527. batch_mrcnn_class_ids[b] = mrcnn_class_ids
  1528. batch_mrcnn_bbox[b] = mrcnn_bbox
  1529. batch_mrcnn_mask[b] = mrcnn_mask
  1530. b += 1
  1531. inputs = [batch_images, batch_image_meta, batch_rpn_match, batch_rpn_bbox,
  1532. batch_gt_class_ids, batch_gt_boxes, batch_gt_masks]
  1533. outputs = []
  1534. if self.random_rois:
  1535. inputs.extend([batch_rpn_rois])
  1536. if self.detection_targets:
  1537. inputs.extend([batch_rois])
  1538. # Keras requires that output and targets have the same number of dimensions
  1539. batch_mrcnn_class_ids = np.expand_dims(
  1540. batch_mrcnn_class_ids, -1)
  1541. outputs.extend(
  1542. [batch_mrcnn_class_ids, batch_mrcnn_bbox, batch_mrcnn_mask])
  1543. return inputs, outputs
  1544. ############################################################
  1545. # MaskRCNN Class
  1546. ############################################################
  1547. class MaskRCNN(object):
  1548. """Encapsulates the Mask RCNN model functionality.
  1549. The actual Keras model is in the keras_model property.
  1550. """
  1551. def __init__(self, mode, config, model_dir):
  1552. """
  1553. mode: Either "training" or "inference"
  1554. config: A Sub-class of the Config class
  1555. model_dir: Directory to save training logs and trained weights
  1556. """
  1557. assert mode in ['training', 'inference']
  1558. self.mode = mode
  1559. self.config = config
  1560. self.model_dir = model_dir
  1561. self.set_log_dir()
  1562. self.keras_model = self.build(mode=mode, config=config)
  1563. def build(self, mode, config):
  1564. """Build Mask R-CNN architecture.
  1565. input_shape: The shape of the input image.
  1566. mode: Either "training" or "inference". The inputs and
  1567. outputs of the model differ accordingly.
  1568. """
  1569. assert mode in ['training', 'inference']
  1570. # Image size must be dividable by 2 multiple times
  1571. h, w = config.IMAGE_SHAPE[:2]
  1572. if h / 2**6 != int(h / 2**6) or w / 2**6 != int(w / 2**6):
  1573. raise Exception("Image size must be dividable by 2 at least 6 times "
  1574. "to avoid fractions when downscaling and upscaling."
  1575. "For example, use 256, 320, 384, 448, 512, ... etc. ")
  1576. # Inputs
  1577. input_image = KL.Input(
  1578. shape=[None, None, config.IMAGE_SHAPE[2]], name="fuck-this-shit")
  1579. input_image_meta = KL.Input(shape=[config.IMAGE_META_SIZE],
  1580. name="input_image_meta")
  1581. if mode == "training":
  1582. # RPN GT
  1583. input_rpn_match = KL.Input(
  1584. shape=[None, 1], name="input_rpn_match", dtype=tf.int32)
  1585. input_rpn_bbox = KL.Input(
  1586. shape=[None, 4], name="input_rpn_bbox", dtype=tf.float32)
  1587. # Detection GT (class IDs, bounding boxes, and masks)
  1588. # 1. GT Class IDs (zero padded)
  1589. input_gt_class_ids = KL.Input(
  1590. shape=[None], name="input_gt_class_ids", dtype=tf.int32)
  1591. # 2. GT Boxes in pixels (zero padded)
  1592. # [batch, MAX_GT_INSTANCES, (y1, x1, y2, x2)] in image coordinates
  1593. input_gt_boxes = KL.Input(
  1594. shape=[None, 4], name="input_gt_boxes", dtype=tf.float32)
  1595. # Normalize coordinates
  1596. # gt_boxes = KL.Lambda(lambda x: norm_boxes_graph(
  1597. # x, K.shape(input_image)[1:3]))(input_gt_boxes)
  1598. gt_boxes = KL.Lambda(
  1599. lambda x: norm_boxes_graph(x[0], K.shape(x[1])[1:3]),
  1600. name='fucking-lambda',
  1601. )((input_gt_boxes, input_image))
  1602. # 3. GT Masks (zero padded)
  1603. # [batch, height, width, MAX_GT_INSTANCES]
  1604. if config.USE_MINI_MASK:
  1605. input_gt_masks = KL.Input(
  1606. shape=[config.MINI_MASK_SHAPE[0],
  1607. config.MINI_MASK_SHAPE[1], None],
  1608. name="input_gt_masks", dtype=bool)
  1609. else:
  1610. input_gt_masks = KL.Input(
  1611. shape=[config.IMAGE_SHAPE[0], config.IMAGE_SHAPE[1], None],
  1612. name="input_gt_masks", dtype=bool)
  1613. elif mode == "inference":
  1614. # Anchors in normalized coordinates
  1615. input_anchors = KL.Input(shape=[None, 4], name="input_anchors")
  1616. # Build the shared convolutional layers.
  1617. # Bottom-up Layers
  1618. # Returns a list of the last layers of each stage, 5 in total.
  1619. # Don't create the thead (stage 5), so we pick the 4th item in the list.
  1620. if callable(config.BACKBONE):
  1621. _, C2, C3, C4, C5 = config.BACKBONE(input_image, stage5=True,
  1622. train_bn=config.TRAIN_BN)
  1623. else:
  1624. _, C2, C3, C4, C5 = resnet_graph(input_image, config.BACKBONE,
  1625. stage5=True, train_bn=config.TRAIN_BN)
  1626. # Top-down Layers
  1627. # TODO: add assert to varify feature map sizes match what's in config
  1628. P5 = KL.Conv2D(config.TOP_DOWN_PYRAMID_SIZE, (1, 1), name='fpn_c5p5')(C5)
  1629. P4 = KL.Add(name="fpn_p4add")([
  1630. KL.UpSampling2D(size=(2, 2), name="fpn_p5upsampled")(P5),
  1631. KL.Conv2D(config.TOP_DOWN_PYRAMID_SIZE, (1, 1), name='fpn_c4p4')(C4)])
  1632. P3 = KL.Add(name="fpn_p3add")([
  1633. KL.UpSampling2D(size=(2, 2), name="fpn_p4upsampled")(P4),
  1634. KL.Conv2D(config.TOP_DOWN_PYRAMID_SIZE, (1, 1), name='fpn_c3p3')(C3)])
  1635. P2 = KL.Add(name="fpn_p2add")([
  1636. KL.UpSampling2D(size=(2, 2), name="fpn_p3upsampled")(P3),
  1637. KL.Conv2D(config.TOP_DOWN_PYRAMID_SIZE, (1, 1), name='fpn_c2p2')(C2)])
  1638. # Attach 3x3 conv to all P layers to get the final feature maps.
  1639. P2 = KL.Conv2D(config.TOP_DOWN_PYRAMID_SIZE, (3, 3), padding="SAME", name="fpn_p2")(P2)
  1640. P3 = KL.Conv2D(config.TOP_DOWN_PYRAMID_SIZE, (3, 3), padding="SAME", name="fpn_p3")(P3)
  1641. P4 = KL.Conv2D(config.TOP_DOWN_PYRAMID_SIZE, (3, 3), padding="SAME", name="fpn_p4")(P4)
  1642. P5 = KL.Conv2D(config.TOP_DOWN_PYRAMID_SIZE, (3, 3), padding="SAME", name="fpn_p5")(P5)
  1643. # P6 is used for the 5th anchor scale in RPN. Generated by
  1644. # subsampling from P5 with stride of 2.
  1645. P6 = KL.MaxPooling2D(pool_size=(1, 1), strides=2, name="fpn_p6")(P5)
  1646. # Note that P6 is used in RPN, but not in the classifier heads.
  1647. rpn_feature_maps = [P2, P3, P4, P5, P6]
  1648. mrcnn_feature_maps = [P2, P3, P4, P5]
  1649. # Anchors
  1650. if mode == "training":
  1651. anchors = self.get_anchors(config.IMAGE_SHAPE)
  1652. # Duplicate across the batch dimension because Keras requires it
  1653. # TODO: can this be optimized to avoid duplicating the anchors?
  1654. anchors = np.broadcast_to(anchors, (config.BATCH_SIZE,) + anchors.shape)
  1655. # A hack to get around Keras's bad support for constants
  1656. # This class returns a constant layer
  1657. class ConstLayer(ModdedLayer):
  1658. def __init__(self, x, name=None):
  1659. super(ConstLayer, self).__init__(name=name)
  1660. self.x = K.variable(x)
  1661. def call(self, input):
  1662. return self.x
  1663. anchors = ConstLayer(anchors, name="anchors")(input_image)
  1664. else:
  1665. anchors = input_anchors
  1666. # RPN Model
  1667. rpn = build_rpn_model(config.RPN_ANCHOR_STRIDE,
  1668. len(config.RPN_ANCHOR_RATIOS), config.TOP_DOWN_PYRAMID_SIZE)
  1669. # Loop through pyramid layers
  1670. layer_outputs = [] # list of lists
  1671. for p in rpn_feature_maps:
  1672. layer_outputs.append(rpn([p]))
  1673. # Concatenate layer outputs
  1674. # Convert from list of lists of level outputs to list of lists
  1675. # of outputs across levels.
  1676. # e.g. [[a1, b1, c1], [a2, b2, c2]] => [[a1, a2], [b1, b2], [c1, c2]]
  1677. output_names = ["rpn_class_logits", "rpn_class", "rpn_bbox"]
  1678. outputs = list(zip(*layer_outputs))
  1679. outputs = [KL.Concatenate(axis=1, name=n)(list(o))
  1680. for o, n in zip(outputs, output_names)]
  1681. rpn_class_logits, rpn_class, rpn_bbox = outputs
  1682. # Generate proposals
  1683. # Proposals are [batch, N, (y1, x1, y2, x2)] in normalized coordinates
  1684. # and zero padded.
  1685. proposal_count = config.POST_NMS_ROIS_TRAINING if mode == "training"\
  1686. else config.POST_NMS_ROIS_INFERENCE
  1687. rpn_rois = ProposalLayer(
  1688. proposal_count=proposal_count,
  1689. nms_threshold=config.RPN_NMS_THRESHOLD,
  1690. name="ROI",
  1691. config=config)([rpn_class, rpn_bbox, anchors])
  1692. if mode == "training":
  1693. # Class ID mask to mark class IDs supported by the dataset the image
  1694. # came from.
  1695. active_class_ids = KL.Lambda(
  1696. lambda x: parse_image_meta_graph(x)["active_class_ids"]
  1697. )(input_image_meta)
  1698. if not config.USE_RPN_ROIS:
  1699. # Ignore predicted ROIs and use ROIs provided as an input.
  1700. input_rois = KL.Input(shape=[config.POST_NMS_ROIS_TRAINING, 4],
  1701. name="input_roi", dtype=np.int32)
  1702. # Normalize coordinates
  1703. target_rois = KL.Lambda(lambda x: norm_boxes_graph(
  1704. x, K.shape(input_image)[1:3]))(input_rois)
  1705. else:
  1706. target_rois = rpn_rois
  1707. # Generate detection targets
  1708. # Subsamples proposals and generates target outputs for training
  1709. # Note that proposal class IDs, gt_boxes, and gt_masks are zero
  1710. # padded. Equally, returned rois and targets are zero padded.
  1711. rois, target_class_ids, target_bbox, target_mask =\
  1712. DetectionTargetLayer(config, name="proposal_targets")([
  1713. target_rois, input_gt_class_ids, gt_boxes, input_gt_masks])
  1714. # Network Heads
  1715. # TODO: verify that this handles zero padded ROIs
  1716. mrcnn_class_logits, mrcnn_class, mrcnn_bbox =\
  1717. fpn_classifier_graph(rois, mrcnn_feature_maps, input_image_meta,
  1718. config.POOL_SIZE, config.NUM_CLASSES,
  1719. train_bn=config.TRAIN_BN,
  1720. fc_layers_size=config.FPN_CLASSIF_FC_LAYERS_SIZE)
  1721. mrcnn_mask = build_fpn_mask_graph(rois, mrcnn_feature_maps,
  1722. input_image_meta,
  1723. config.MASK_POOL_SIZE,
  1724. config.NUM_CLASSES,
  1725. train_bn=config.TRAIN_BN)
  1726. # TODO: clean up (use tf.identify if necessary)
  1727. output_rois = KL.Lambda(lambda x: x * 1, name="output_rois")(rois)
  1728. # Losses
  1729. rpn_class_loss = KL.Lambda(lambda x: rpn_class_loss_graph(*x), name="rpn_class_loss")(
  1730. [input_rpn_match, rpn_class_logits])
  1731. rpn_bbox_loss = KL.Lambda(lambda x: rpn_bbox_loss_graph(config, *x), name="rpn_bbox_loss")(
  1732. [input_rpn_bbox, input_rpn_match, rpn_bbox])
  1733. class_loss = KL.Lambda(lambda x: mrcnn_class_loss_graph(*x), name="mrcnn_class_loss")(
  1734. [target_class_ids, mrcnn_class_logits, active_class_ids])
  1735. bbox_loss = KL.Lambda(lambda x: mrcnn_bbox_loss_graph(*x), name="mrcnn_bbox_loss")(
  1736. [target_bbox, target_class_ids, mrcnn_bbox])
  1737. mask_loss = KL.Lambda(lambda x: mrcnn_mask_loss_graph(*x), name="mrcnn_mask_loss")(
  1738. [target_mask, target_class_ids, mrcnn_mask])
  1739. # Model
  1740. inputs = [input_image, input_image_meta,
  1741. input_rpn_match, input_rpn_bbox, input_gt_class_ids, input_gt_boxes, input_gt_masks]
  1742. if not config.USE_RPN_ROIS:
  1743. inputs.append(input_rois)
  1744. outputs = [rpn_class_logits, rpn_class, rpn_bbox,
  1745. mrcnn_class_logits, mrcnn_class, mrcnn_bbox, mrcnn_mask,
  1746. rpn_rois, output_rois,
  1747. rpn_class_loss, rpn_bbox_loss, class_loss, bbox_loss, mask_loss]
  1748. model = KM.Model(inputs, outputs, name='mask_rcnn')
  1749. else:
  1750. # Network Heads
  1751. # Proposal classifier and BBox regressor heads
  1752. mrcnn_class_logits, mrcnn_class, mrcnn_bbox =\
  1753. fpn_classifier_graph(rpn_rois, mrcnn_feature_maps, input_image_meta,
  1754. config.POOL_SIZE, config.NUM_CLASSES,
  1755. train_bn=config.TRAIN_BN,
  1756. fc_layers_size=config.FPN_CLASSIF_FC_LAYERS_SIZE)
  1757. # Detections
  1758. # output is [batch, num_detections, (y1, x1, y2, x2, class_id, score)] in
  1759. # normalized coordinates
  1760. detections = DetectionLayer(config, name="mrcnn_detection")(
  1761. [rpn_rois, mrcnn_class, mrcnn_bbox, input_image_meta])
  1762. # Create masks for detections
  1763. detection_boxes = KL.Lambda(lambda x: x[..., :4])(detections)
  1764. mrcnn_mask = build_fpn_mask_graph(detection_boxes, mrcnn_feature_maps,
  1765. input_image_meta,
  1766. config.MASK_POOL_SIZE,
  1767. config.NUM_CLASSES,
  1768. train_bn=config.TRAIN_BN)
  1769. model = KM.Model([input_image, input_image_meta, input_anchors],
  1770. [detections, mrcnn_class, mrcnn_bbox,
  1771. mrcnn_mask, rpn_rois, rpn_class, rpn_bbox],
  1772. name='mask_rcnn')
  1773. # Add multi-GPU support.
  1774. if config.GPU_COUNT > 1:
  1775. from mrcnn.parallel_model import ParallelModel
  1776. model = ParallelModel(model, config.GPU_COUNT)
  1777. return model
  1778. def find_last(self):
  1779. """Finds the last checkpoint file of the last trained model in the
  1780. model directory.
  1781. Returns:
  1782. The path of the last checkpoint file
  1783. """
  1784. # Get directory names. Each directory corresponds to a model
  1785. dir_names = next(os.walk(self.model_dir))[1]
  1786. key = self.config.NAME.lower()
  1787. dir_names = filter(lambda f: f.startswith(key), dir_names)
  1788. dir_names = sorted(dir_names)
  1789. if not dir_names:
  1790. import errno
  1791. raise FileNotFoundError(
  1792. errno.ENOENT,
  1793. "Could not find model directory under {}".format(self.model_dir))
  1794. # Pick last directory
  1795. dir_name = os.path.join(self.model_dir, dir_names[-1])
  1796. # Find the last checkpoint
  1797. checkpoints = next(os.walk(dir_name))[2]
  1798. checkpoints = filter(lambda f: f.startswith("mask_rcnn"), checkpoints)
  1799. checkpoints = sorted(checkpoints)
  1800. if not checkpoints:
  1801. import errno
  1802. raise FileNotFoundError(
  1803. errno.ENOENT, "Could not find weight files in {}".format(dir_name))
  1804. checkpoint = os.path.join(dir_name, checkpoints[-1])
  1805. return checkpoint
  1806. def load_weights(self, filepath, by_name=False, exclude=None):
  1807. """Modified version of the corresponding Keras function with
  1808. the addition of multi-GPU support and the ability to exclude
  1809. some layers from loading.
  1810. exclude: list of layer names to exclude
  1811. """
  1812. import h5py
  1813. from tensorflow.python.keras.saving import hdf5_format
  1814. if exclude:
  1815. by_name = True
  1816. if h5py is None:
  1817. raise ImportError('`load_weights` requires h5py.')
  1818. with h5py.File(filepath, mode='r') as f:
  1819. if 'layer_names' not in f.attrs and 'model_weights' in f:
  1820. f = f['model_weights']
  1821. # In multi-GPU training, we wrap the model. Get layers
  1822. # of the inner model because they have the weights.
  1823. keras_model = self.keras_model
  1824. layers = keras_model.inner_model.layers if hasattr(keras_model, "inner_model")\
  1825. else keras_model.layers
  1826. # Exclude some layers
  1827. if exclude:
  1828. layers = filter(lambda l: l.name not in exclude, layers)
  1829. if by_name:
  1830. hdf5_format.load_weights_from_hdf5_group_by_name(f, layers)
  1831. else:
  1832. hdf5_format.load_weights_from_hdf5_group(f, layers)
  1833. # Update the log directory
  1834. self.set_log_dir(filepath)
  1835. def get_imagenet_weights(self):
  1836. """Downloads ImageNet trained weights from Keras.
  1837. Returns path to weights file.
  1838. """
  1839. from keras.utils.data_utils import get_file
  1840. TF_WEIGHTS_PATH_NO_TOP = 'https://github.com/fchollet/deep-learning-models/'\
  1841. 'releases/download/v0.2/'\
  1842. 'resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'
  1843. weights_path = get_file('resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5',
  1844. TF_WEIGHTS_PATH_NO_TOP,
  1845. cache_subdir='models',
  1846. md5_hash='a268eb855778b3df3c7506639542a6af')
  1847. return weights_path
  1848. def compile(self, learning_rate, momentum):
  1849. """Gets the model ready for training. Adds losses, regularization, and
  1850. metrics. Then calls the Keras compile() function.
  1851. """
  1852. # Optimizer object
  1853. optimizer = keras.optimizers.SGD(
  1854. lr=learning_rate, momentum=momentum,
  1855. clipnorm=self.config.GRADIENT_CLIP_NORM)
  1856. # Add Losses
  1857. loss_names = [
  1858. "rpn_class_loss", "rpn_bbox_loss",
  1859. "mrcnn_class_loss", "mrcnn_bbox_loss", "mrcnn_mask_loss"]
  1860. for name in loss_names:
  1861. layer = self.keras_model.get_layer(name)
  1862. if layer.output in self.keras_model.losses:
  1863. continue
  1864. loss = (
  1865. tf.reduce_mean(input_tensor=layer.output, keepdims=True)
  1866. * self.config.LOSS_WEIGHTS.get(name, 1.))
  1867. self.keras_model.add_loss(loss)
  1868. # Add L2 Regularization
  1869. # Skip gamma and beta weights of batch normalization layers.
  1870. reg_losses = [
  1871. keras.regularizers.l2(self.config.WEIGHT_DECAY)(w) / tf.cast(tf.size(input=w), tf.float32)
  1872. for w in self.keras_model.trainable_weights
  1873. if 'gamma' not in w.name and 'beta' not in w.name]
  1874. self.keras_model.add_loss(tf.add_n(reg_losses))
  1875. # Compile
  1876. self.keras_model.compile(
  1877. optimizer=optimizer,
  1878. loss=[None] * len(self.keras_model.outputs))
  1879. # Add metrics for losses
  1880. for name in loss_names:
  1881. if name in self.keras_model.metrics_names:
  1882. continue
  1883. layer = self.keras_model.get_layer(name)
  1884. self.keras_model.metrics_names.append(name)
  1885. loss = (
  1886. tf.reduce_mean(input_tensor=layer.output, keepdims=True)
  1887. * self.config.LOSS_WEIGHTS.get(name, 1.))
  1888. self.keras_model.add_metric(loss, name=name, aggregation='mean')
  1889. def set_trainable(self, layer_regex, keras_model=None, indent=0, verbose=1):
  1890. """Sets model layers as trainable if their names match
  1891. the given regular expression.
  1892. """
  1893. # Print message on the first call (but not on recursive calls)
  1894. if verbose > 0 and keras_model is None:
  1895. log("Selecting layers to train")
  1896. keras_model = keras_model or self.keras_model
  1897. # In multi-GPU training, we wrap the model. Get layers
  1898. # of the inner model because they have the weights.
  1899. layers = keras_model.inner_model.layers if hasattr(keras_model, "inner_model")\
  1900. else keras_model.layers
  1901. for layer in layers:
  1902. # Is the layer a model?
  1903. if layer.__class__.__name__ == 'Model':
  1904. print("In model: ", layer.name)
  1905. self.set_trainable(
  1906. layer_regex, keras_model=layer, indent=indent + 4)
  1907. continue
  1908. if not layer.weights:
  1909. continue
  1910. # Is it trainable?
  1911. trainable = bool(re.fullmatch(layer_regex, layer.name))
  1912. # Update layer. If layer is a container, update inner layer.
  1913. if layer.__class__.__name__ == 'TimeDistributed':
  1914. layer.layer.trainable = trainable
  1915. else:
  1916. layer.trainable = trainable
  1917. # Print trainable layer names
  1918. if trainable and verbose > 0:
  1919. log("{}{:20} ({})".format(" " * indent, layer.name,
  1920. layer.__class__.__name__))
  1921. def set_log_dir(self, model_path=None):
  1922. """Sets the model log directory and epoch counter.
  1923. model_path: If None, or a format different from what this code uses
  1924. then set a new log directory and start epochs from 0. Otherwise,
  1925. extract the log directory and the epoch counter from the file
  1926. name.
  1927. """
  1928. # Set date and epoch counter as if starting a new model
  1929. self.epoch = 0
  1930. now = datetime.datetime.now()
  1931. # If we have a model path with date and epochs use them
  1932. if model_path:
  1933. # Continue from we left of. Get epoch and date from the file name
  1934. # A sample model path might look like:
  1935. # \path\to\logs\coco20171029T2315\mask_rcnn_coco_0001.h5 (Windows)
  1936. # /path/to/logs/coco20171029T2315/mask_rcnn_coco_0001.h5 (Linux)
  1937. regex = r".*[/\\][\w-]+(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})[/\\]mask\_rcnn\_[\w-]+(\d{4})\.h5"
  1938. # Use string for regex since we might want to use pathlib.Path as model_path
  1939. m = re.match(regex, str(model_path))
  1940. if m:
  1941. now = datetime.datetime(int(m.group(1)), int(m.group(2)), int(m.group(3)),
  1942. int(m.group(4)), int(m.group(5)))
  1943. # Epoch number in file is 1-based, and in Keras code it's 0-based.
  1944. # So, adjust for that then increment by one to start from the next epoch
  1945. self.epoch = int(m.group(6)) - 1 + 1
  1946. print('Re-starting from epoch %d' % self.epoch)
  1947. # Directory for training logs
  1948. self.log_dir = os.path.join(self.model_dir, "{}{:%Y%m%dT%H%M}".format(
  1949. self.config.NAME.lower(), now))
  1950. # Path to save after each epoch. Include placeholders that get filled by Keras.
  1951. self.checkpoint_path = os.path.join(self.log_dir, "mask_rcnn_{}_*epoch*.h5".format(
  1952. self.config.NAME.lower()))
  1953. self.checkpoint_path = self.checkpoint_path.replace(
  1954. "*epoch*", "{epoch:04d}")
  1955. def train(self, train_dataset, val_dataset, learning_rate, epochs, layers,
  1956. augmentation=None, custom_callbacks=None, no_augmentation_sources=None):
  1957. """Train the model.
  1958. train_dataset, val_dataset: Training and validation Dataset objects.
  1959. learning_rate: The learning rate to train with
  1960. epochs: Number of training epochs. Note that previous training epochs
  1961. are considered to be done alreay, so this actually determines
  1962. the epochs to train in total rather than in this particaular
  1963. call.
  1964. layers: Allows selecting wich layers to train. It can be:
  1965. - A regular expression to match layer names to train
  1966. - One of these predefined values:
  1967. heads: The RPN, classifier and mask heads of the network
  1968. all: All the layers
  1969. 3+: Train Resnet stage 3 and up
  1970. 4+: Train Resnet stage 4 and up
  1971. 5+: Train Resnet stage 5 and up
  1972. augmentation: Optional. An imgaug (https://github.com/aleju/imgaug)
  1973. augmentation. For example, passing imgaug.augmenters.Fliplr(0.5)
  1974. flips images right/left 50% of the time. You can pass complex
  1975. augmentations as well. This augmentation applies 50% of the
  1976. time, and when it does it flips images right/left half the time
  1977. and adds a Gaussian blur with a random sigma in range 0 to 5.
  1978. augmentation = imgaug.augmenters.Sometimes(0.5, [
  1979. imgaug.augmenters.Fliplr(0.5),
  1980. imgaug.augmenters.GaussianBlur(sigma=(0.0, 5.0))
  1981. ])
  1982. custom_callbacks: Optional. Add custom callbacks to be called
  1983. with the keras fit_generator method. Must be list of type keras.callbacks.
  1984. no_augmentation_sources: Optional. List of sources to exclude for
  1985. augmentation. A source is string that identifies a dataset and is
  1986. defined in the Dataset class.
  1987. """
  1988. assert self.mode == "training", "Create model in training mode."
  1989. # Pre-defined layer regular expressions
  1990. layer_regex = {
  1991. # all layers but the backbone
  1992. "heads": r"(mrcnn\_.*)|(rpn\_.*)|(fpn\_.*)",
  1993. # From a specific Resnet stage and up
  1994. "3+": r"(res3.*)|(bn3.*)|(res4.*)|(bn4.*)|(res5.*)|(bn5.*)|(mrcnn\_.*)|(rpn\_.*)|(fpn\_.*)",
  1995. "4+": r"(res4.*)|(bn4.*)|(res5.*)|(bn5.*)|(mrcnn\_.*)|(rpn\_.*)|(fpn\_.*)",
  1996. "5+": r"(res5.*)|(bn5.*)|(mrcnn\_.*)|(rpn\_.*)|(fpn\_.*)",
  1997. # All layers
  1998. "all": ".*",
  1999. }
  2000. if layers in layer_regex.keys():
  2001. layers = layer_regex[layers]
  2002. # Data generators
  2003. train_generator = DataGenerator(train_dataset, self.config, shuffle=True,
  2004. augmentation=augmentation)
  2005. val_generator = DataGenerator(val_dataset, self.config, shuffle=True)
  2006. # Create log_dir if it does not exist
  2007. if not os.path.exists(self.log_dir):
  2008. os.makedirs(self.log_dir)
  2009. # Callbacks
  2010. callbacks = [
  2011. keras.callbacks.TensorBoard(log_dir=self.log_dir,
  2012. histogram_freq=0, write_graph=True, write_images=False),
  2013. keras.callbacks.ModelCheckpoint(self.checkpoint_path,
  2014. verbose=0, save_weights_only=True),
  2015. ]
  2016. # Add custom callbacks to the list
  2017. if custom_callbacks:
  2018. callbacks += custom_callbacks
  2019. # Train
  2020. log("\nStarting at epoch {}. LR={}\n".format(self.epoch, learning_rate))
  2021. log("Checkpoint Path: {}".format(self.checkpoint_path))
  2022. self.set_trainable(layers)
  2023. self.compile(learning_rate, self.config.LEARNING_MOMENTUM)
  2024. # Work-around for Windows: Keras fails on Windows when using
  2025. # multiprocessing workers. See discussion here:
  2026. # https://github.com/matterport/Mask_RCNN/issues/13#issuecomment-353124009
  2027. if os.name == 'nt':
  2028. workers = 0
  2029. else:
  2030. workers = multiprocessing.cpu_count()
  2031. self.keras_model.fit(
  2032. train_generator,
  2033. initial_epoch=self.epoch,
  2034. epochs=epochs,
  2035. steps_per_epoch=self.config.STEPS_PER_EPOCH,
  2036. callbacks=callbacks,
  2037. validation_data=val_generator,
  2038. validation_steps=self.config.VALIDATION_STEPS,
  2039. max_queue_size=100,
  2040. workers=workers,
  2041. use_multiprocessing=workers > 1,
  2042. )
  2043. self.epoch = max(self.epoch, epochs)
  2044. def mold_inputs(self, images):
  2045. """Takes a list of images and modifies them to the format expected
  2046. as an input to the neural network.
  2047. images: List of image matrices [height,width,depth]. Images can have
  2048. different sizes.
  2049. Returns 3 Numpy matrices:
  2050. molded_images: [N, h, w, 3]. Images resized and normalized.
  2051. image_metas: [N, length of meta data]. Details about each image.
  2052. windows: [N, (y1, x1, y2, x2)]. The portion of the image that has the
  2053. original image (padding excluded).
  2054. """
  2055. molded_images = []
  2056. image_metas = []
  2057. windows = []
  2058. for image in images:
  2059. # Resize image
  2060. # TODO: move resizing to mold_image()
  2061. molded_image, window, scale, padding, crop = utils.resize_image(
  2062. image,
  2063. min_dim=self.config.IMAGE_MIN_DIM,
  2064. min_scale=self.config.IMAGE_MIN_SCALE,
  2065. max_dim=self.config.IMAGE_MAX_DIM,
  2066. mode=self.config.IMAGE_RESIZE_MODE)
  2067. molded_image = mold_image(molded_image, self.config)
  2068. # Build image_meta
  2069. image_meta = compose_image_meta(
  2070. 0, image.shape, molded_image.shape, window, scale,
  2071. np.zeros([self.config.NUM_CLASSES], dtype=np.int32))
  2072. # Append
  2073. molded_images.append(molded_image)
  2074. windows.append(window)
  2075. image_metas.append(image_meta)
  2076. # Pack into arrays
  2077. molded_images = np.stack(molded_images)
  2078. image_metas = np.stack(image_metas)
  2079. windows = np.stack(windows)
  2080. return molded_images, image_metas, windows
  2081. def unmold_detections(self, detections, mrcnn_mask, original_image_shape,
  2082. image_shape, window):
  2083. """Reformats the detections of one image from the format of the neural
  2084. network output to a format suitable for use in the rest of the
  2085. application.
  2086. detections: [N, (y1, x1, y2, x2, class_id, score)] in normalized coordinates
  2087. mrcnn_mask: [N, height, width, num_classes]
  2088. original_image_shape: [H, W, C] Original image shape before resizing
  2089. image_shape: [H, W, C] Shape of the image after resizing and padding
  2090. window: [y1, x1, y2, x2] Pixel coordinates of box in the image where the real
  2091. image is excluding the padding.
  2092. Returns:
  2093. boxes: [N, (y1, x1, y2, x2)] Bounding boxes in pixels
  2094. class_ids: [N] Integer class IDs for each bounding box
  2095. scores: [N] Float probability scores of the class_id
  2096. masks: [height, width, num_instances] Instance masks
  2097. """
  2098. # How many detections do we have?
  2099. # Detections array is padded with zeros. Find the first class_id == 0.
  2100. zero_ix = np.where(detections[:, 4] == 0)[0]
  2101. N = zero_ix[0] if zero_ix.shape[0] > 0 else detections.shape[0]
  2102. # Extract boxes, class_ids, scores, and class-specific masks
  2103. boxes = detections[:N, :4]
  2104. class_ids = detections[:N, 4].astype(np.int32)
  2105. scores = detections[:N, 5]
  2106. masks = mrcnn_mask[np.arange(N), :, :, class_ids]
  2107. # Translate normalized coordinates in the resized image to pixel
  2108. # coordinates in the original image before resizing
  2109. window = utils.norm_boxes(window, image_shape[:2])
  2110. wy1, wx1, wy2, wx2 = window
  2111. shift = np.array([wy1, wx1, wy1, wx1])
  2112. wh = wy2 - wy1 # window height
  2113. ww = wx2 - wx1 # window width
  2114. scale = np.array([wh, ww, wh, ww])
  2115. # Convert boxes to normalized coordinates on the window
  2116. boxes = np.divide(boxes - shift, scale)
  2117. # Convert boxes to pixel coordinates on the original image
  2118. boxes = utils.denorm_boxes(boxes, original_image_shape[:2])
  2119. # Filter out detections with zero area. Happens in early training when
  2120. # network weights are still random
  2121. exclude_ix = np.where(
  2122. (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]) <= 0)[0]
  2123. if exclude_ix.shape[0] > 0:
  2124. boxes = np.delete(boxes, exclude_ix, axis=0)
  2125. class_ids = np.delete(class_ids, exclude_ix, axis=0)
  2126. scores = np.delete(scores, exclude_ix, axis=0)
  2127. masks = np.delete(masks, exclude_ix, axis=0)
  2128. N = class_ids.shape[0]
  2129. # Resize masks to original image size and set boundary threshold.
  2130. full_masks = []
  2131. for i in range(N):
  2132. # Convert neural network mask to full size mask
  2133. full_mask = utils.unmold_mask(masks[i], boxes[i], original_image_shape)
  2134. full_masks.append(full_mask)
  2135. full_masks = np.stack(full_masks, axis=-1)\
  2136. if full_masks else np.empty(original_image_shape[:2] + (0,))
  2137. return boxes, class_ids, scores, full_masks
  2138. def detect(self, images, verbose=0):
  2139. """Runs the detection pipeline.
  2140. images: List of images, potentially of different sizes.
  2141. Returns a list of dicts, one dict per image. The dict contains:
  2142. rois: [N, (y1, x1, y2, x2)] detection bounding boxes
  2143. class_ids: [N] int class IDs
  2144. scores: [N] float probability scores for the class IDs
  2145. masks: [H, W, N] instance binary masks
  2146. """
  2147. assert self.mode == "inference", "Create model in inference mode."
  2148. assert len(
  2149. images) == self.config.BATCH_SIZE, "len(images) must be equal to BATCH_SIZE"
  2150. if verbose:
  2151. log("Processing {} images".format(len(images)))
  2152. for image in images:
  2153. log("image", image)
  2154. # Mold inputs to format expected by the neural network
  2155. molded_images, image_metas, windows = self.mold_inputs(images)
  2156. # Validate image sizes
  2157. # All images in a batch MUST be of the same size
  2158. image_shape = molded_images[0].shape
  2159. for g in molded_images[1:]:
  2160. assert g.shape == image_shape,\
  2161. "After resizing, all images must have the same size. Check IMAGE_RESIZE_MODE and image sizes."
  2162. # Anchors
  2163. anchors = self.get_anchors(image_shape)
  2164. # Duplicate across the batch dimension because Keras requires it
  2165. # TODO: can this be optimized to avoid duplicating the anchors?
  2166. anchors = np.broadcast_to(anchors, (self.config.BATCH_SIZE,) + anchors.shape)
  2167. if verbose:
  2168. log("molded_images", molded_images)
  2169. log("image_metas", image_metas)
  2170. log("anchors", anchors)
  2171. # Run object detection
  2172. detections, _, _, mrcnn_mask, _, _, _ =\
  2173. self.keras_model.predict([molded_images, image_metas, anchors], verbose=0)
  2174. # Process detections
  2175. results = []
  2176. for i, image in enumerate(images):
  2177. final_rois, final_class_ids, final_scores, final_masks =\
  2178. self.unmold_detections(detections[i], mrcnn_mask[i],
  2179. image.shape, molded_images[i].shape,
  2180. windows[i])
  2181. results.append({
  2182. "rois": final_rois,
  2183. "class_ids": final_class_ids,
  2184. "scores": final_scores,
  2185. "masks": final_masks,
  2186. })
  2187. return results
  2188. def detect_molded(self, molded_images, image_metas, verbose=0):
  2189. """Runs the detection pipeline, but expect inputs that are
  2190. molded already. Used mostly for debugging and inspecting
  2191. the model.
  2192. molded_images: List of images loaded using load_image_gt()
  2193. image_metas: image meta data, also returned by load_image_gt()
  2194. Returns a list of dicts, one dict per image. The dict contains:
  2195. rois: [N, (y1, x1, y2, x2)] detection bounding boxes
  2196. class_ids: [N] int class IDs
  2197. scores: [N] float probability scores for the class IDs
  2198. masks: [H, W, N] instance binary masks
  2199. """
  2200. assert self.mode == "inference", "Create model in inference mode."
  2201. assert len(molded_images) == self.config.BATCH_SIZE,\
  2202. "Number of images must be equal to BATCH_SIZE"
  2203. if verbose:
  2204. log("Processing {} images".format(len(molded_images)))
  2205. for image in molded_images:
  2206. log("image", image)
  2207. # Validate image sizes
  2208. # All images in a batch MUST be of the same size
  2209. image_shape = molded_images[0].shape
  2210. for g in molded_images[1:]:
  2211. assert g.shape == image_shape, "Images must have the same size"
  2212. # Anchors
  2213. anchors = self.get_anchors(image_shape)
  2214. # Duplicate across the batch dimension because Keras requires it
  2215. # TODO: can this be optimized to avoid duplicating the anchors?
  2216. anchors = np.broadcast_to(anchors, (self.config.BATCH_SIZE,) + anchors.shape)
  2217. if verbose:
  2218. log("molded_images", molded_images)
  2219. log("image_metas", image_metas)
  2220. log("anchors", anchors)
  2221. # Run object detection
  2222. detections, _, _, mrcnn_mask, _, _, _ =\
  2223. self.keras_model.predict([molded_images, image_metas, anchors], verbose=0)
  2224. # Process detections
  2225. results = []
  2226. for i, image in enumerate(molded_images):
  2227. window = [0, 0, image.shape[0], image.shape[1]]
  2228. final_rois, final_class_ids, final_scores, final_masks =\
  2229. self.unmold_detections(detections[i], mrcnn_mask[i],
  2230. image.shape, molded_images[i].shape,
  2231. window)
  2232. results.append({
  2233. "rois": final_rois,
  2234. "class_ids": final_class_ids,
  2235. "scores": final_scores,
  2236. "masks": final_masks,
  2237. })
  2238. return results
  2239. def get_anchors(self, image_shape):
  2240. """Returns anchor pyramid for the given image size."""
  2241. backbone_shapes = compute_backbone_shapes(self.config, image_shape)
  2242. # Cache anchors and reuse if image shape is the same
  2243. if not hasattr(self, "_anchor_cache"):
  2244. self._anchor_cache = {}
  2245. if not tuple(image_shape) in self._anchor_cache:
  2246. # Generate Anchors
  2247. a = utils.generate_pyramid_anchors(
  2248. self.config.RPN_ANCHOR_SCALES,
  2249. self.config.RPN_ANCHOR_RATIOS,
  2250. backbone_shapes,
  2251. self.config.BACKBONE_STRIDES,
  2252. self.config.RPN_ANCHOR_STRIDE)
  2253. # Keep a copy of the latest anchors in pixel coordinates because
  2254. # it's used in inspect_model notebooks.
  2255. # TODO: Remove this after the notebook are refactored to not use it
  2256. self.anchors = a
  2257. # Normalize coordinates
  2258. self._anchor_cache[tuple(image_shape)] = utils.norm_boxes(a, image_shape[:2])
  2259. return self._anchor_cache[tuple(image_shape)]
  2260. def ancestor(self, tensor, name, checked=None):
  2261. """Finds the ancestor of a TF tensor in the computation graph.
  2262. tensor: TensorFlow symbolic tensor.
  2263. name: Name of ancestor tensor to find
  2264. checked: For internal use. A list of tensors that were already
  2265. searched to avoid loops in traversing the graph.
  2266. """
  2267. checked = checked if checked is not None else []
  2268. # Put a limit on how deep we go to avoid very long loops
  2269. if len(checked) > 500:
  2270. return None
  2271. # Convert name to a regex and allow matching a number prefix
  2272. # because Keras adds them automatically
  2273. if isinstance(name, str):
  2274. name = re.compile(name.replace("/", r"(\_\d+)*/"))
  2275. parents = tensor.op.inputs
  2276. for p in parents:
  2277. if p in checked:
  2278. continue
  2279. if bool(re.fullmatch(name, p.name)):
  2280. return p
  2281. checked.append(p)
  2282. a = self.ancestor(p, name, checked)
  2283. if a is not None:
  2284. return a
  2285. return None
  2286. def find_trainable_layer(self, layer):
  2287. """If a layer is encapsulated by another layer, this function
  2288. digs through the encapsulation and returns the layer that holds
  2289. the weights.
  2290. """
  2291. if layer.__class__.__name__ == 'TimeDistributed':
  2292. return self.find_trainable_layer(layer.layer)
  2293. return layer
  2294. def get_trainable_layers(self):
  2295. """Returns a list of layers that have weights."""
  2296. layers = []
  2297. # Loop through all layers
  2298. for l in self.keras_model.layers:
  2299. # If layer is a wrapper, find inner trainable layer
  2300. l = self.find_trainable_layer(l)
  2301. # Include layer if it has weights
  2302. if l.get_weights():
  2303. layers.append(l)
  2304. return layers
  2305. def run_graph(self, images, outputs, image_metas=None):
  2306. """Runs a sub-set of the computation graph that computes the given
  2307. outputs.
  2308. image_metas: If provided, the images are assumed to be already
  2309. molded (i.e. resized, padded, and normalized)
  2310. outputs: List of tuples (name, tensor) to compute. The tensors are
  2311. symbolic TensorFlow tensors and the names are for easy tracking.
  2312. Returns an ordered dict of results. Keys are the names received in the
  2313. input and values are Numpy arrays.
  2314. """
  2315. model = self.keras_model
  2316. # Organize desired outputs into an ordered dict
  2317. outputs = OrderedDict(outputs)
  2318. for o in outputs.values():
  2319. assert o is not None
  2320. # Build a Keras function to run parts of the computation graph
  2321. inputs = model.inputs
  2322. # if model.uses_learning_phase and not isinstance(K.learning_phase(), int):
  2323. # inputs += [K.learning_phase()]
  2324. kf = K.function(model.inputs, list(outputs.values()))
  2325. # Prepare inputs
  2326. if image_metas is None:
  2327. molded_images, image_metas, _ = self.mold_inputs(images)
  2328. else:
  2329. molded_images = images
  2330. image_shape = molded_images[0].shape
  2331. # Anchors
  2332. anchors = self.get_anchors(image_shape)
  2333. # Duplicate across the batch dimension because Keras requires it
  2334. # TODO: can this be optimized to avoid duplicating the anchors?
  2335. anchors = np.broadcast_to(anchors, (self.config.BATCH_SIZE,) + anchors.shape)
  2336. model_in = [molded_images, image_metas, anchors]
  2337. # Run inference
  2338. # if model.uses_learning_phase and not isinstance(K.learning_phase(), int):
  2339. # model_in.append(0.)
  2340. outputs_np = kf(model_in)
  2341. # Pack the generated Numpy arrays into a a dict and log the results.
  2342. outputs_np = OrderedDict([(k, v)
  2343. for k, v in zip(outputs.keys(), outputs_np)])
  2344. for k, v in outputs_np.items():
  2345. log(k, v)
  2346. return outputs_np
  2347. ############################################################
  2348. # Data Formatting
  2349. ############################################################
  2350. def compose_image_meta(image_id, original_image_shape, image_shape,
  2351. window, scale, active_class_ids):
  2352. """Takes attributes of an image and puts them in one 1D array.
  2353. image_id: An int ID of the image. Useful for debugging.
  2354. original_image_shape: [H, W, C] before resizing or padding.
  2355. image_shape: [H, W, C] after resizing and padding
  2356. window: (y1, x1, y2, x2) in pixels. The area of the image where the real
  2357. image is (excluding the padding)
  2358. scale: The scaling factor applied to the original image (float32)
  2359. active_class_ids: List of class_ids available in the dataset from which
  2360. the image came. Useful if training on images from multiple datasets
  2361. where not all classes are present in all datasets.
  2362. """
  2363. meta = np.array(
  2364. [image_id] + # size=1
  2365. list(original_image_shape) + # size=3
  2366. list(image_shape) + # size=3
  2367. list(window) + # size=4 (y1, x1, y2, x2) in image cooredinates
  2368. [scale] + # size=1
  2369. list(active_class_ids) # size=num_classes
  2370. )
  2371. return meta
  2372. def parse_image_meta(meta):
  2373. """Parses an array that contains image attributes to its components.
  2374. See compose_image_meta() for more details.
  2375. meta: [batch, meta length] where meta length depends on NUM_CLASSES
  2376. Returns a dict of the parsed values.
  2377. """
  2378. image_id = meta[:, 0]
  2379. original_image_shape = meta[:, 1:4]
  2380. image_shape = meta[:, 4:7]
  2381. window = meta[:, 7:11] # (y1, x1, y2, x2) window of image in in pixels
  2382. scale = meta[:, 11]
  2383. active_class_ids = meta[:, 12:]
  2384. return {
  2385. "image_id": image_id.astype(np.int32),
  2386. "original_image_shape": original_image_shape.astype(np.int32),
  2387. "image_shape": image_shape.astype(np.int32),
  2388. "window": window.astype(np.int32),
  2389. "scale": scale.astype(np.float32),
  2390. "active_class_ids": active_class_ids.astype(np.int32),
  2391. }
  2392. def parse_image_meta_graph(meta):
  2393. """Parses a tensor that contains image attributes to its components.
  2394. See compose_image_meta() for more details.
  2395. meta: [batch, meta length] where meta length depends on NUM_CLASSES
  2396. Returns a dict of the parsed tensors.
  2397. """
  2398. image_id = meta[:, 0]
  2399. original_image_shape = meta[:, 1:4]
  2400. image_shape = meta[:, 4:7]
  2401. window = meta[:, 7:11] # (y1, x1, y2, x2) window of image in in pixels
  2402. scale = meta[:, 11]
  2403. active_class_ids = meta[:, 12:]
  2404. return {
  2405. "image_id": image_id,
  2406. "original_image_shape": original_image_shape,
  2407. "image_shape": image_shape,
  2408. "window": window,
  2409. "scale": scale,
  2410. "active_class_ids": active_class_ids,
  2411. }
  2412. def mold_image(images, config):
  2413. """Expects an RGB image (or array of images) and subtracts
  2414. the mean pixel and converts it to float. Expects image
  2415. colors in RGB order.
  2416. """
  2417. return images.astype(np.float32) - config.MEAN_PIXEL
  2418. def unmold_image(normalized_images, config):
  2419. """Takes a image normalized with mold() and returns the original."""
  2420. return (normalized_images + config.MEAN_PIXEL).astype(np.uint8)
  2421. ############################################################
  2422. # Miscellenous Graph Functions
  2423. ############################################################
  2424. def trim_zeros_graph(boxes, name='trim_zeros'):
  2425. """Often boxes are represented with matrices of shape [N, 4] and
  2426. are padded with zeros. This removes zero boxes.
  2427. boxes: [N, 4] matrix of boxes.
  2428. non_zeros: [N] a 1D boolean mask identifying the rows to keep
  2429. """
  2430. non_zeros = tf.cast(tf.reduce_sum(input_tensor=tf.abs(boxes), axis=1), tf.bool)
  2431. boxes = tf.boolean_mask(tensor=boxes, mask=non_zeros, name=name)
  2432. return boxes, non_zeros
  2433. def batch_pack_graph(x, counts, num_rows):
  2434. """Picks different number of values from each row
  2435. in x depending on the values in counts.
  2436. """
  2437. outputs = []
  2438. for i in range(num_rows):
  2439. outputs.append(x[i, :counts[i]])
  2440. return tf.concat(outputs, axis=0)
  2441. def norm_boxes_graph(boxes, shape):
  2442. """Converts boxes from pixel coordinates to normalized coordinates.
  2443. boxes: [..., (y1, x1, y2, x2)] in pixel coordinates
  2444. shape: [..., (height, width)] in pixels
  2445. Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
  2446. coordinates it's inside the box.
  2447. Returns:
  2448. [..., (y1, x1, y2, x2)] in normalized coordinates
  2449. """
  2450. h, w = tf.split(tf.cast(shape, tf.float32), 2)
  2451. scale = tf.concat([h, w, h, w], axis=-1) - K.constant(1.0)
  2452. shift = K.constant([0., 0., 1., 1.])
  2453. return tf.divide(boxes - shift, scale)
  2454. def denorm_boxes_graph(boxes, shape):
  2455. """Converts boxes from normalized coordinates to pixel coordinates.
  2456. boxes: [..., (y1, x1, y2, x2)] in normalized coordinates
  2457. shape: [..., (height, width)] in pixels
  2458. Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
  2459. coordinates it's inside the box.
  2460. Returns:
  2461. [..., (y1, x1, y2, x2)] in pixel coordinates
  2462. """
  2463. h, w = tf.split(tf.cast(shape, tf.float32), 2)
  2464. scale = tf.concat([h, w, h, w], axis=-1) - K.constant(1.0)
  2465. shift = K.constant([0., 0., 1., 1.])
  2466. return tf.cast(tf.round(tf.multiply(boxes, scale) + shift), tf.int32)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...