File size: 50,624 Bytes
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
 
a80d6bb
 
 
 
 
 
 
c74a070
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
a80d6bb
 
 
 
 
 
 
 
 
 
c74a070
 
 
 
 
 
 
 
 
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
 
 
 
 
 
a80d6bb
 
c74a070
 
 
 
 
 
 
a80d6bb
 
 
 
 
c74a070
 
 
 
a80d6bb
 
 
 
 
 
 
 
c74a070
 
 
 
 
 
a80d6bb
 
c74a070
 
a80d6bb
 
 
 
 
c74a070
a80d6bb
 
 
 
 
 
 
c74a070
a80d6bb
c74a070
 
 
a80d6bb
c74a070
 
 
a80d6bb
 
 
c74a070
 
 
 
 
a80d6bb
 
 
c74a070
 
 
 
 
 
 
 
a80d6bb
 
 
 
c74a070
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
a80d6bb
 
 
 
 
 
 
 
 
 
 
c74a070
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
a80d6bb
 
 
 
 
c74a070
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
c74a070
a80d6bb
c74a070
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
 
a80d6bb
 
 
 
 
 
 
 
c74a070
a80d6bb
 
 
c74a070
a80d6bb
 
 
 
c74a070
a80d6bb
 
 
 
 
 
 
c74a070
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
c74a070
a80d6bb
c74a070
a80d6bb
 
 
 
c74a070
 
 
 
a80d6bb
c74a070
 
 
 
 
 
 
 
a80d6bb
 
c74a070
 
 
 
a80d6bb
 
 
c74a070
 
 
 
 
 
 
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
a80d6bb
 
 
c74a070
 
a80d6bb
 
 
 
 
 
 
 
 
c74a070
a80d6bb
 
 
 
 
c74a070
 
 
 
 
 
 
 
 
 
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
a80d6bb
c74a070
a80d6bb
c74a070
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
 
 
 
a80d6bb
 
 
 
 
 
 
c74a070
 
 
 
 
 
a80d6bb
c74a070
 
 
 
 
a80d6bb
 
 
 
c74a070
 
 
 
a80d6bb
 
 
 
 
 
c74a070
 
 
 
 
 
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
 
 
 
 
 
a80d6bb
 
 
c74a070
 
a80d6bb
c74a070
 
a80d6bb
c74a070
 
a80d6bb
 
c74a070
 
 
 
 
 
 
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
a80d6bb
 
 
 
c74a070
a80d6bb
 
 
 
 
c74a070
 
a80d6bb
 
 
 
 
 
 
 
c74a070
 
a80d6bb
 
 
 
 
 
 
 
 
 
c74a070
a80d6bb
 
 
c74a070
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
a80d6bb
 
 
 
 
 
c74a070
a80d6bb
c74a070
a80d6bb
 
 
 
 
 
 
 
c74a070
 
 
 
a80d6bb
c74a070
 
 
 
 
 
 
 
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
 
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
a80d6bb
 
 
 
 
c74a070
 
a80d6bb
 
 
 
 
c74a070
 
a80d6bb
 
 
c74a070
 
 
 
 
 
 
 
 
 
 
a80d6bb
c74a070
 
 
a80d6bb
 
 
c74a070
 
 
a80d6bb
 
 
c74a070
 
 
 
 
 
 
 
 
 
 
 
a80d6bb
 
c74a070
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a80d6bb
 
 
 
 
 
 
c74a070
 
 
 
 
 
 
 
 
 
 
 
a80d6bb
 
 
 
 
 
 
 
c74a070
 
 
 
 
 
 
 
 
 
 
 
a80d6bb
 
 
 
 
 
c74a070
 
 
 
 
 
 
a80d6bb
 
 
 
 
 
 
 
c74a070
 
a80d6bb
 
 
 
 
c74a070
a80d6bb
 
 
 
 
c74a070
 
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
a80d6bb
 
 
 
 
 
 
 
 
 
c74a070
 
 
 
 
 
 
 
 
 
 
 
 
a80d6bb
 
 
 
 
c74a070
 
 
 
 
 
 
 
 
 
 
 
 
a80d6bb
 
 
c74a070
 
 
 
 
 
 
 
 
 
 
 
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
 
 
 
a80d6bb
 
 
c74a070
 
 
 
a80d6bb
 
 
 
 
 
c74a070
a80d6bb
c74a070
a80d6bb
 
c74a070
 
 
 
a80d6bb
 
 
 
 
c74a070
 
a80d6bb
 
 
 
c74a070
 
a80d6bb
 
c74a070
 
 
 
 
 
 
 
 
 
 
a80d6bb
c74a070
 
 
a80d6bb
 
 
c74a070
a80d6bb
 
 
c74a070
 
 
 
 
 
 
 
 
 
 
 
a80d6bb
 
c74a070
a80d6bb
 
 
 
 
 
 
 
 
c74a070
 
 
 
 
 
 
 
 
 
 
 
a80d6bb
 
 
 
 
 
 
c74a070
 
 
 
 
 
 
 
 
 
 
 
 
a80d6bb
 
 
 
c74a070
a80d6bb
 
c74a070
 
 
 
 
 
 
 
 
 
 
 
 
a80d6bb
 
 
 
 
 
 
c74a070
 
 
 
 
 
 
a80d6bb
 
 
 
 
 
 
c74a070
a80d6bb
 
 
 
 
c74a070
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
 
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
 
 
 
 
 
 
 
 
 
 
 
 
a80d6bb
 
 
 
c74a070
 
 
 
 
 
 
a80d6bb
 
 
c74a070
a80d6bb
 
c74a070
 
 
 
 
 
 
 
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a80d6bb
c74a070
 
 
 
 
 
 
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
 
 
 
 
 
 
a80d6bb
 
 
 
 
 
c74a070
 
 
 
 
 
 
a80d6bb
 
 
 
 
 
 
c74a070
a80d6bb
 
 
 
c74a070
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
 
a80d6bb
 
 
 
 
 
 
 
 
 
 
 
 
c74a070
a80d6bb
 
 
c74a070
 
 
 
 
 
 
 
 
 
a80d6bb
c74a070
a80d6bb
 
 
c74a070
a80d6bb
c74a070
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
"""
Code adapted from https://github.com/rpautrat/SuperPoint
Module used to generate geometrical synthetic shapes
"""
import math
import cv2 as cv
import numpy as np
import shapely.geometry
from itertools import combinations

random_state = np.random.RandomState(None)


def set_random_state(state):
    global random_state
    random_state = state


def get_random_color(background_color):
    """Output a random scalar in grayscale with a least a small contrast
    with the background color."""
    color = random_state.randint(256)
    if abs(color - background_color) < 30:  # not enough contrast
        color = (color + 128) % 256
    return color


def get_different_color(previous_colors, min_dist=50, max_count=20):
    """Output a color that contrasts with the previous colors.
    Parameters:
      previous_colors: np.array of the previous colors
      min_dist: the difference between the new color and
                the previous colors must be at least min_dist
      max_count: maximal number of iterations
    """
    color = random_state.randint(256)
    count = 0
    while np.any(np.abs(previous_colors - color) < min_dist) and count < max_count:
        count += 1
        color = random_state.randint(256)
    return color


def add_salt_and_pepper(img):
    """Add salt and pepper noise to an image."""
    noise = np.zeros((img.shape[0], img.shape[1]), dtype=np.uint8)
    cv.randu(noise, 0, 255)
    black = noise < 30
    white = noise > 225
    img[white > 0] = 255
    img[black > 0] = 0
    cv.blur(img, (5, 5), img)
    return np.empty((0, 2), dtype=np.int)


def generate_background(
    size=(960, 1280),
    nb_blobs=100,
    min_rad_ratio=0.01,
    max_rad_ratio=0.05,
    min_kernel_size=50,
    max_kernel_size=300,
):
    """Generate a customized background image.
    Parameters:
      size: size of the image
      nb_blobs: number of circles to draw
      min_rad_ratio: the radius of blobs is at least min_rad_size * max(size)
      max_rad_ratio: the radius of blobs is at most max_rad_size * max(size)
      min_kernel_size: minimal size of the kernel
      max_kernel_size: maximal size of the kernel
    """
    img = np.zeros(size, dtype=np.uint8)
    dim = max(size)
    cv.randu(img, 0, 255)
    cv.threshold(img, random_state.randint(256), 255, cv.THRESH_BINARY, img)
    background_color = int(np.mean(img))
    blobs = np.concatenate(
        [
            random_state.randint(0, size[1], size=(nb_blobs, 1)),
            random_state.randint(0, size[0], size=(nb_blobs, 1)),
        ],
        axis=1,
    )
    for i in range(nb_blobs):
        col = get_random_color(background_color)
        cv.circle(
            img,
            (blobs[i][0], blobs[i][1]),
            np.random.randint(int(dim * min_rad_ratio), int(dim * max_rad_ratio)),
            col,
            -1,
        )
    kernel_size = random_state.randint(min_kernel_size, max_kernel_size)
    cv.blur(img, (kernel_size, kernel_size), img)
    return img


def generate_custom_background(
    size, background_color, nb_blobs=3000, kernel_boundaries=(50, 100)
):
    """Generate a customized background to fill the shapes.
    Parameters:
      background_color: average color of the background image
      nb_blobs: number of circles to draw
      kernel_boundaries: interval of the possible sizes of the kernel
    """
    img = np.zeros(size, dtype=np.uint8)
    img = img + get_random_color(background_color)
    blobs = np.concatenate(
        [
            np.random.randint(0, size[1], size=(nb_blobs, 1)),
            np.random.randint(0, size[0], size=(nb_blobs, 1)),
        ],
        axis=1,
    )
    for i in range(nb_blobs):
        col = get_random_color(background_color)
        cv.circle(img, (blobs[i][0], blobs[i][1]), np.random.randint(20), col, -1)
    kernel_size = np.random.randint(kernel_boundaries[0], kernel_boundaries[1])
    cv.blur(img, (kernel_size, kernel_size), img)
    return img


def final_blur(img, kernel_size=(5, 5)):
    """Gaussian blur applied to an image.
    Parameters:
      kernel_size: size of the kernel
    """
    cv.GaussianBlur(img, kernel_size, 0, img)


def ccw(A, B, C, dim):
    """Check if the points are listed in counter-clockwise order."""
    if dim == 2:  # only 2 dimensions
        return (C[:, 1] - A[:, 1]) * (B[:, 0] - A[:, 0]) > (B[:, 1] - A[:, 1]) * (
            C[:, 0] - A[:, 0]
        )
    else:  # dim should be equal to 3
        return (C[:, 1, :] - A[:, 1, :]) * (B[:, 0, :] - A[:, 0, :]) > (
            B[:, 1, :] - A[:, 1, :]
        ) * (C[:, 0, :] - A[:, 0, :])


def intersect(A, B, C, D, dim):
    """Return true if line segments AB and CD intersect"""
    return np.any(
        (ccw(A, C, D, dim) != ccw(B, C, D, dim))
        & (ccw(A, B, C, dim) != ccw(A, B, D, dim))
    )


def keep_points_inside(points, size):
    """Keep only the points whose coordinates are inside the dimensions of
    the image of size 'size'"""
    mask = (
        (points[:, 0] >= 0)
        & (points[:, 0] < size[1])
        & (points[:, 1] >= 0)
        & (points[:, 1] < size[0])
    )
    return points[mask, :]


def get_unique_junctions(segments, min_label_len):
    """Get unique junction points from line segments."""
    # Get all junctions from segments
    junctions_all = np.concatenate((segments[:, :2], segments[:, 2:]), axis=0)
    if junctions_all.shape[0] == 0:
        junc_points = None
        line_map = None

    # Get all unique junction points
    else:
        junc_points = np.unique(junctions_all, axis=0)
        # Generate line map from points and segments
        line_map = get_line_map(junc_points, segments)

    return junc_points, line_map


def get_line_map(points: np.ndarray, segments: np.ndarray) -> np.ndarray:
    """Get line map given the points and segment sets."""
    # create empty line map
    num_point = points.shape[0]
    line_map = np.zeros([num_point, num_point])

    # Iterate through every segment
    for idx in range(segments.shape[0]):
        # Get the junctions from a single segement
        seg = segments[idx, :]
        junction1 = seg[:2]
        junction2 = seg[2:]

        # Get index
        idx_junction1 = np.where((points == junction1).sum(axis=1) == 2)[0]
        idx_junction2 = np.where((points == junction2).sum(axis=1) == 2)[0]

        # label the corresponding entries
        line_map[idx_junction1, idx_junction2] = 1
        line_map[idx_junction2, idx_junction1] = 1

    return line_map


def get_line_heatmap(junctions, line_map, size=[480, 640], thickness=1):
    """Get line heat map from junctions and line map."""
    # Make sure that the thickness is 1
    if not isinstance(thickness, int):
        thickness = int(thickness)

    # If the junction points are not int => round them and convert to int
    if not junctions.dtype == np.int:
        junctions = (np.round(junctions)).astype(np.int)

    # Initialize empty map
    heat_map = np.zeros(size)

    if junctions.shape[0] > 0:  # If empty, just return zero map
        # Iterate through all the junctions
        for idx in range(junctions.shape[0]):
            # if no connectivity, just skip it
            if line_map[idx, :].sum() == 0:
                continue
            # Plot the line segment
            else:
                # Iterate through all the connected junctions
                for idx2 in np.where(line_map[idx, :] == 1)[0]:
                    point1 = junctions[idx, :]
                    point2 = junctions[idx2, :]

                    # Draw line
                    cv.line(heat_map, tuple(point1), tuple(point2), 1.0, thickness)

    return heat_map


def draw_lines(img, nb_lines=10, min_len=32, min_label_len=32):
    """Draw random lines and output the positions of the pair of junctions
        and line associativities.
    Parameters:
      nb_lines: maximal number of lines
    """
    # Set line number and points placeholder
    num_lines = random_state.randint(1, nb_lines)
    segments = np.empty((0, 4), dtype=np.int)
    points = np.empty((0, 2), dtype=np.int)
    background_color = int(np.mean(img))
    min_dim = min(img.shape)

    # Convert length constrain to pixel if given float number
    if isinstance(min_len, float) and min_len <= 1.0:
        min_len = int(min_dim * min_len)
    if isinstance(min_label_len, float) and min_label_len <= 1.0:
        min_label_len = int(min_dim * min_label_len)

    # Generate lines one by one
    for i in range(num_lines):
        x1 = random_state.randint(img.shape[1])
        y1 = random_state.randint(img.shape[0])
        p1 = np.array([[x1, y1]])
        x2 = random_state.randint(img.shape[1])
        y2 = random_state.randint(img.shape[0])
        p2 = np.array([[x2, y2]])

        # Check the length of the line
        line_length = np.sqrt(np.sum((p1 - p2) ** 2))
        if line_length < min_len:
            continue

        # Check that there is no overlap
        if intersect(segments[:, 0:2], segments[:, 2:4], p1, p2, 2):
            continue

        col = get_random_color(background_color)
        thickness = random_state.randint(min_dim * 0.01, min_dim * 0.02)
        cv.line(img, (x1, y1), (x2, y2), col, thickness)

        # Only record the segments longer than min_label_len
        seg_len = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
        if seg_len >= min_label_len:
            segments = np.concatenate([segments, np.array([[x1, y1, x2, y2]])], axis=0)
            points = np.concatenate([points, np.array([[x1, y1], [x2, y2]])], axis=0)

    # If no line is drawn, recursively call the function
    if points.shape[0] == 0:
        return draw_lines(img, nb_lines, min_len, min_label_len)

    # Get the line associativity map
    line_map = get_line_map(points, segments)

    return {"points": points, "line_map": line_map}


def check_segment_len(segments, min_len=32):
    """Check if one of the segments is too short (True means too short)."""
    point1_vec = segments[:, :2]
    point2_vec = segments[:, 2:]
    diff = point1_vec - point2_vec

    dist = np.sqrt(np.sum(diff**2, axis=1))
    if np.any(dist < min_len):
        return True
    else:
        return False


def draw_polygon(img, max_sides=8, min_len=32, min_label_len=64):
    """Draw a polygon with a random number of corners and return the position
        of the junctions + line map.
    Parameters:
      max_sides: maximal number of sides + 1
    """
    num_corners = random_state.randint(3, max_sides)
    min_dim = min(img.shape[0], img.shape[1])
    rad = max(random_state.rand() * min_dim / 2, min_dim / 10)
    # Center of a circle
    x = random_state.randint(rad, img.shape[1] - rad)
    y = random_state.randint(rad, img.shape[0] - rad)

    # Convert length constrain to pixel if given float number
    if isinstance(min_len, float) and min_len <= 1.0:
        min_len = int(min_dim * min_len)
    if isinstance(min_label_len, float) and min_label_len <= 1.0:
        min_label_len = int(min_dim * min_label_len)

    # Sample num_corners points inside the circle
    slices = np.linspace(0, 2 * math.pi, num_corners + 1)
    angles = [
        slices[i] + random_state.rand() * (slices[i + 1] - slices[i])
        for i in range(num_corners)
    ]
    points = np.array(
        [
            [
                int(x + max(random_state.rand(), 0.4) * rad * math.cos(a)),
                int(y + max(random_state.rand(), 0.4) * rad * math.sin(a)),
            ]
            for a in angles
        ]
    )

    # Filter the points that are too close or that have an angle too flat
    norms = [
        np.linalg.norm(points[(i - 1) % num_corners, :] - points[i, :])
        for i in range(num_corners)
    ]
    mask = np.array(norms) > 0.01
    points = points[mask, :]
    num_corners = points.shape[0]
    corner_angles = [
        angle_between_vectors(
            points[(i - 1) % num_corners, :] - points[i, :],
            points[(i + 1) % num_corners, :] - points[i, :],
        )
        for i in range(num_corners)
    ]
    mask = np.array(corner_angles) < (2 * math.pi / 3)
    points = points[mask, :]
    num_corners = points.shape[0]

    # Get junction pairs from points
    segments = np.zeros([0, 4])
    # Used to record all the segments no matter we are going to label it or not.
    segments_raw = np.zeros([0, 4])
    for idx in range(num_corners):
        if idx == (num_corners - 1):
            p1 = points[idx]
            p2 = points[0]
        else:
            p1 = points[idx]
            p2 = points[idx + 1]

        segment = np.concatenate((p1, p2), axis=0)
        # Only record the segments longer than min_label_len
        seg_len = np.sqrt(np.sum((p1 - p2) ** 2))
        if seg_len >= min_label_len:
            segments = np.concatenate((segments, segment[None, ...]), axis=0)
        segments_raw = np.concatenate((segments_raw, segment[None, ...]), axis=0)

    # If not enough corner, just regenerate one
    if (num_corners < 3) or check_segment_len(segments_raw, min_len):
        return draw_polygon(img, max_sides, min_len, min_label_len)

    # Get junctions from segments
    junctions_all = np.concatenate((segments[:, :2], segments[:, 2:]), axis=0)
    if junctions_all.shape[0] == 0:
        junc_points = None
        line_map = None

    else:
        junc_points = np.unique(junctions_all, axis=0)

        # Get the line map
        line_map = get_line_map(junc_points, segments)

    corners = points.reshape((-1, 1, 2))
    col = get_random_color(int(np.mean(img)))
    cv.fillPoly(img, [corners], col)

    return {"points": junc_points, "line_map": line_map}


def overlap(center, rad, centers, rads):
    """Check that the circle with (center, rad)
    doesn't overlap with the other circles."""
    flag = False
    for i in range(len(rads)):
        if np.linalg.norm(center - centers[i]) < rad + rads[i]:
            flag = True
            break
    return flag


def angle_between_vectors(v1, v2):
    """Compute the angle (in rad) between the two vectors v1 and v2."""
    v1_u = v1 / np.linalg.norm(v1)
    v2_u = v2 / np.linalg.norm(v2)
    return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))


def draw_multiple_polygons(
    img,
    max_sides=8,
    nb_polygons=30,
    min_len=32,
    min_label_len=64,
    safe_margin=5,
    **extra
):
    """Draw multiple polygons with a random number of corners
        and return the junction points + line map.
    Parameters:
      max_sides: maximal number of sides + 1
      nb_polygons: maximal number of polygons
    """
    segments = np.empty((0, 4), dtype=np.int)
    label_segments = np.empty((0, 4), dtype=np.int)
    centers = []
    rads = []
    points = np.empty((0, 2), dtype=np.int)
    background_color = int(np.mean(img))

    min_dim = min(img.shape[0], img.shape[1])
    # Convert length constrain to pixel if given float number
    if isinstance(min_len, float) and min_len <= 1.0:
        min_len = int(min_dim * min_len)
    if isinstance(min_label_len, float) and min_label_len <= 1.0:
        min_label_len = int(min_dim * min_label_len)
    if isinstance(safe_margin, float) and safe_margin <= 1.0:
        safe_margin = int(min_dim * safe_margin)

    # Sequentially generate polygons
    for i in range(nb_polygons):
        num_corners = random_state.randint(3, max_sides)
        min_dim = min(img.shape[0], img.shape[1])

        # Also add the real radius
        rad = max(random_state.rand() * min_dim / 2, min_dim / 9)
        rad_real = rad - safe_margin

        # Center of a circle
        x = random_state.randint(rad, img.shape[1] - rad)
        y = random_state.randint(rad, img.shape[0] - rad)

        # Sample num_corners points inside the circle
        slices = np.linspace(0, 2 * math.pi, num_corners + 1)
        angles = [
            slices[i] + random_state.rand() * (slices[i + 1] - slices[i])
            for i in range(num_corners)
        ]

        # Sample outer points and inner points
        new_points = []
        new_points_real = []
        for a in angles:
            x_offset = max(random_state.rand(), 0.4)
            y_offset = max(random_state.rand(), 0.4)
            new_points.append(
                [
                    int(x + x_offset * rad * math.cos(a)),
                    int(y + y_offset * rad * math.sin(a)),
                ]
            )
            new_points_real.append(
                [
                    int(x + x_offset * rad_real * math.cos(a)),
                    int(y + y_offset * rad_real * math.sin(a)),
                ]
            )
        new_points = np.array(new_points)
        new_points_real = np.array(new_points_real)

        # Filter the points that are too close or that have an angle too flat
        norms = [
            np.linalg.norm(new_points[(i - 1) % num_corners, :] - new_points[i, :])
            for i in range(num_corners)
        ]
        mask = np.array(norms) > 0.01
        new_points = new_points[mask, :]
        new_points_real = new_points_real[mask, :]

        num_corners = new_points.shape[0]
        corner_angles = [
            angle_between_vectors(
                new_points[(i - 1) % num_corners, :] - new_points[i, :],
                new_points[(i + 1) % num_corners, :] - new_points[i, :],
            )
            for i in range(num_corners)
        ]
        mask = np.array(corner_angles) < (2 * math.pi / 3)
        new_points = new_points[mask, :]
        new_points_real = new_points_real[mask, :]
        num_corners = new_points.shape[0]

        # Not enough corners
        if num_corners < 3:
            continue

        # Segments for checking overlap (outer circle)
        new_segments = np.zeros((1, 4, num_corners))
        new_segments[:, 0, :] = [new_points[i][0] for i in range(num_corners)]
        new_segments[:, 1, :] = [new_points[i][1] for i in range(num_corners)]
        new_segments[:, 2, :] = [
            new_points[(i + 1) % num_corners][0] for i in range(num_corners)
        ]
        new_segments[:, 3, :] = [
            new_points[(i + 1) % num_corners][1] for i in range(num_corners)
        ]

        # Segments to record (inner circle)
        new_segments_real = np.zeros((1, 4, num_corners))
        new_segments_real[:, 0, :] = [new_points_real[i][0] for i in range(num_corners)]
        new_segments_real[:, 1, :] = [new_points_real[i][1] for i in range(num_corners)]
        new_segments_real[:, 2, :] = [
            new_points_real[(i + 1) % num_corners][0] for i in range(num_corners)
        ]
        new_segments_real[:, 3, :] = [
            new_points_real[(i + 1) % num_corners][1] for i in range(num_corners)
        ]

        # Check that the polygon will not overlap with pre-existing shapes
        if intersect(
            segments[:, 0:2, None],
            segments[:, 2:4, None],
            new_segments[:, 0:2, :],
            new_segments[:, 2:4, :],
            3,
        ) or overlap(np.array([x, y]), rad, centers, rads):
            continue

        # Check that the the edges of the polygon is not too short
        if check_segment_len(new_segments_real, min_len):
            continue

        # If the polygon is valid, append it to the polygon set
        centers.append(np.array([x, y]))
        rads.append(rad)
        new_segments = np.reshape(np.swapaxes(new_segments, 0, 2), (-1, 4))
        segments = np.concatenate([segments, new_segments], axis=0)

        # Only record the segments longer than min_label_len
        new_segments_real = np.reshape(np.swapaxes(new_segments_real, 0, 2), (-1, 4))
        points1 = new_segments_real[:, :2]
        points2 = new_segments_real[:, 2:]
        seg_len = np.sqrt(np.sum((points1 - points2) ** 2, axis=1))
        new_label_segment = new_segments_real[seg_len >= min_label_len, :]
        label_segments = np.concatenate([label_segments, new_label_segment], axis=0)

        # Color the polygon with a custom background
        corners = new_points_real.reshape((-1, 1, 2))
        mask = np.zeros(img.shape, np.uint8)
        custom_background = generate_custom_background(
            img.shape, background_color, **extra
        )

        cv.fillPoly(mask, [corners], 255)
        locs = np.where(mask != 0)
        img[locs[0], locs[1]] = custom_background[locs[0], locs[1]]
        points = np.concatenate([points, new_points], axis=0)

    # Get all junctions from label segments
    junctions_all = np.concatenate(
        (label_segments[:, :2], label_segments[:, 2:]), axis=0
    )
    if junctions_all.shape[0] == 0:
        junc_points = None
        line_map = None

    else:
        junc_points = np.unique(junctions_all, axis=0)

        # Generate line map from points and segments
        line_map = get_line_map(junc_points, label_segments)

    return {"points": junc_points, "line_map": line_map}


def draw_ellipses(img, nb_ellipses=20):
    """Draw several ellipses.
    Parameters:
      nb_ellipses: maximal number of ellipses
    """
    centers = np.empty((0, 2), dtype=np.int)
    rads = np.empty((0, 1), dtype=np.int)
    min_dim = min(img.shape[0], img.shape[1]) / 4
    background_color = int(np.mean(img))
    for i in range(nb_ellipses):
        ax = int(max(random_state.rand() * min_dim, min_dim / 5))
        ay = int(max(random_state.rand() * min_dim, min_dim / 5))
        max_rad = max(ax, ay)
        x = random_state.randint(max_rad, img.shape[1] - max_rad)  # center
        y = random_state.randint(max_rad, img.shape[0] - max_rad)
        new_center = np.array([[x, y]])

        # Check that the ellipsis will not overlap with pre-existing shapes
        diff = centers - new_center
        if np.any(max_rad > (np.sqrt(np.sum(diff * diff, axis=1)) - rads)):
            continue
        centers = np.concatenate([centers, new_center], axis=0)
        rads = np.concatenate([rads, np.array([[max_rad]])], axis=0)

        col = get_random_color(background_color)
        angle = random_state.rand() * 90
        cv.ellipse(img, (x, y), (ax, ay), angle, 0, 360, col, -1)
    return np.empty((0, 2), dtype=np.int)


def draw_star(img, nb_branches=6, min_len=32, min_label_len=64):
    """Draw a star and return the junction points + line map.
    Parameters:
      nb_branches: number of branches of the star
    """
    num_branches = random_state.randint(3, nb_branches)
    min_dim = min(img.shape[0], img.shape[1])
    # Convert length constrain to pixel if given float number
    if isinstance(min_len, float) and min_len <= 1.0:
        min_len = int(min_dim * min_len)
    if isinstance(min_label_len, float) and min_label_len <= 1.0:
        min_label_len = int(min_dim * min_label_len)

    thickness = random_state.randint(min_dim * 0.01, min_dim * 0.025)
    rad = max(random_state.rand() * min_dim / 2, min_dim / 5)
    x = random_state.randint(rad, img.shape[1] - rad)
    y = random_state.randint(rad, img.shape[0] - rad)
    # Sample num_branches points inside the circle
    slices = np.linspace(0, 2 * math.pi, num_branches + 1)
    angles = [
        slices[i] + random_state.rand() * (slices[i + 1] - slices[i])
        for i in range(num_branches)
    ]
    points = np.array(
        [
            [
                int(x + max(random_state.rand(), 0.3) * rad * math.cos(a)),
                int(y + max(random_state.rand(), 0.3) * rad * math.sin(a)),
            ]
            for a in angles
        ]
    )
    points = np.concatenate(([[x, y]], points), axis=0)

    # Generate segments and check the length
    segments = np.array([[x, y, _[0], _[1]] for _ in points[1:, :]])
    if check_segment_len(segments, min_len):
        return draw_star(img, nb_branches, min_len, min_label_len)

    # Only record the segments longer than min_label_len
    points1 = segments[:, :2]
    points2 = segments[:, 2:]
    seg_len = np.sqrt(np.sum((points1 - points2) ** 2, axis=1))
    label_segments = segments[seg_len >= min_label_len, :]

    # Get all junctions from label segments
    junctions_all = np.concatenate(
        (label_segments[:, :2], label_segments[:, 2:]), axis=0
    )
    if junctions_all.shape[0] == 0:
        junc_points = None
        line_map = None

    # Get all unique junction points
    else:
        junc_points = np.unique(junctions_all, axis=0)
        # Generate line map from points and segments
        line_map = get_line_map(junc_points, label_segments)

    background_color = int(np.mean(img))
    for i in range(1, num_branches + 1):
        col = get_random_color(background_color)
        cv.line(
            img,
            (points[0][0], points[0][1]),
            (points[i][0], points[i][1]),
            col,
            thickness,
        )
    return {"points": junc_points, "line_map": line_map}


def draw_checkerboard_multiseg(
    img,
    max_rows=7,
    max_cols=7,
    transform_params=(0.05, 0.15),
    min_label_len=64,
    seed=None,
):
    """Draw a checkerboard and output the junctions + line segments
    Parameters:
      max_rows: maximal number of rows + 1
      max_cols: maximal number of cols + 1
      transform_params: set the range of the parameters of the transformations
    """
    if seed is None:
        global random_state
    else:
        random_state = np.random.RandomState(seed)

    background_color = int(np.mean(img))

    min_dim = min(img.shape)
    if isinstance(min_label_len, float) and min_label_len <= 1.0:
        min_label_len = int(min_dim * min_label_len)
    # Create the grid
    rows = random_state.randint(3, max_rows)  # number of rows
    cols = random_state.randint(3, max_cols)  # number of cols
    s = min((img.shape[1] - 1) // cols, (img.shape[0] - 1) // rows)
    x_coord = np.tile(range(cols + 1), rows + 1).reshape(((rows + 1) * (cols + 1), 1))
    y_coord = np.repeat(range(rows + 1), cols + 1).reshape(((rows + 1) * (cols + 1), 1))
    # points are the grid coordinates
    points = s * np.concatenate([x_coord, y_coord], axis=1)

    # Warp the grid using an affine transformation and an homography
    alpha_affine = np.max(img.shape) * (
        transform_params[0] + random_state.rand() * transform_params[1]
    )
    center_square = np.float32(img.shape) // 2
    min_dim = min(img.shape)
    square_size = min_dim // 3
    pts1 = np.float32(
        [
            center_square + square_size,
            [center_square[0] + square_size, center_square[1] - square_size],
            center_square - square_size,
            [center_square[0] - square_size, center_square[1] + square_size],
        ]
    )
    pts2 = pts1 + random_state.uniform(
        -alpha_affine, alpha_affine, size=pts1.shape
    ).astype(np.float32)
    affine_transform = cv.getAffineTransform(pts1[:3], pts2[:3])
    pts2 = pts1 + random_state.uniform(
        -alpha_affine / 2, alpha_affine / 2, size=pts1.shape
    ).astype(np.float32)
    perspective_transform = cv.getPerspectiveTransform(pts1, pts2)

    # Apply the affine transformation
    points = np.transpose(
        np.concatenate((points, np.ones(((rows + 1) * (cols + 1), 1))), axis=1)
    )
    warped_points = np.transpose(np.dot(affine_transform, points))

    # Apply the homography
    warped_col0 = np.add(
        np.sum(np.multiply(warped_points, perspective_transform[0, :2]), axis=1),
        perspective_transform[0, 2],
    )
    warped_col1 = np.add(
        np.sum(np.multiply(warped_points, perspective_transform[1, :2]), axis=1),
        perspective_transform[1, 2],
    )
    warped_col2 = np.add(
        np.sum(np.multiply(warped_points, perspective_transform[2, :2]), axis=1),
        perspective_transform[2, 2],
    )
    warped_col0 = np.divide(warped_col0, warped_col2)
    warped_col1 = np.divide(warped_col1, warped_col2)
    warped_points = np.concatenate([warped_col0[:, None], warped_col1[:, None]], axis=1)
    warped_points_float = warped_points.copy()
    warped_points = warped_points.astype(int)

    # Fill the rectangles
    colors = np.zeros((rows * cols,), np.int32)
    for i in range(rows):
        for j in range(cols):
            # Get a color that contrast with the neighboring cells
            if i == 0 and j == 0:
                col = get_random_color(background_color)
            else:
                neighboring_colors = []
                if i != 0:
                    neighboring_colors.append(colors[(i - 1) * cols + j])
                if j != 0:
                    neighboring_colors.append(colors[i * cols + j - 1])
                col = get_different_color(np.array(neighboring_colors))
            colors[i * cols + j] = col

            # Fill the cell
            cv.fillConvexPoly(
                img,
                np.array(
                    [
                        (
                            warped_points[i * (cols + 1) + j, 0],
                            warped_points[i * (cols + 1) + j, 1],
                        ),
                        (
                            warped_points[i * (cols + 1) + j + 1, 0],
                            warped_points[i * (cols + 1) + j + 1, 1],
                        ),
                        (
                            warped_points[(i + 1) * (cols + 1) + j + 1, 0],
                            warped_points[(i + 1) * (cols + 1) + j + 1, 1],
                        ),
                        (
                            warped_points[(i + 1) * (cols + 1) + j, 0],
                            warped_points[(i + 1) * (cols + 1) + j, 1],
                        ),
                    ]
                ),
                col,
            )

    label_segments = np.empty([0, 4], dtype=np.int)
    # Iterate through rows
    for row_idx in range(rows + 1):
        # Include all the combination of the junctions
        # Iterate through all the combination of junction index in that row
        multi_seg_lst = [
            np.array(
                [
                    warped_points_float[id1, 0],
                    warped_points_float[id1, 1],
                    warped_points_float[id2, 0],
                    warped_points_float[id2, 1],
                ]
            )[None, ...]
            for (id1, id2) in combinations(
                range(row_idx * (cols + 1), (row_idx + 1) * (cols + 1), 1), 2
            )
        ]
        multi_seg = np.concatenate(multi_seg_lst, axis=0)
        label_segments = np.concatenate((label_segments, multi_seg), axis=0)

    # Iterate through columns
    for col_idx in range(cols + 1):  # for 5 columns, we will have 5 + 1 edges
        # Include all the combination of the junctions
        # Iterate throuhg all the combination of junction index in that column
        multi_seg_lst = [
            np.array(
                [
                    warped_points_float[id1, 0],
                    warped_points_float[id1, 1],
                    warped_points_float[id2, 0],
                    warped_points_float[id2, 1],
                ]
            )[None, ...]
            for (id1, id2) in combinations(
                range(col_idx, col_idx + ((rows + 1) * (cols + 1)), cols + 1), 2
            )
        ]
        multi_seg = np.concatenate(multi_seg_lst, axis=0)
        label_segments = np.concatenate((label_segments, multi_seg), axis=0)

    label_segments_filtered = np.zeros([0, 4])
    # Define image boundary polygon (in x y manner)
    image_poly = shapely.geometry.Polygon(
        [
            [0, 0],
            [img.shape[1] - 1, 0],
            [img.shape[1] - 1, img.shape[0] - 1],
            [0, img.shape[0] - 1],
        ]
    )
    for idx in range(label_segments.shape[0]):
        # Get the line segment
        seg_raw = label_segments[idx, :]
        seg = shapely.geometry.LineString([seg_raw[:2], seg_raw[2:]])

        # The line segment is just inside the image.
        if seg.intersection(image_poly) == seg:
            label_segments_filtered = np.concatenate(
                (label_segments_filtered, seg_raw[None, ...]), axis=0
            )

        # Intersect with the image.
        elif seg.intersects(image_poly):
            # Check intersection
            try:
                p = np.array(seg.intersection(image_poly).coords).reshape([-1, 4])
            # If intersect with eact one point
            except:
                continue
            segment = p
            label_segments_filtered = np.concatenate(
                (label_segments_filtered, segment), axis=0
            )

        else:
            continue

    label_segments = np.round(label_segments_filtered).astype(np.int)

    # Only record the segments longer than min_label_len
    points1 = label_segments[:, :2]
    points2 = label_segments[:, 2:]
    seg_len = np.sqrt(np.sum((points1 - points2) ** 2, axis=1))
    label_segments = label_segments[seg_len >= min_label_len, :]

    # Get all junctions from label segments
    junc_points, line_map = get_unique_junctions(label_segments, min_label_len)

    # Draw lines on the boundaries of the board at random
    nb_rows = random_state.randint(2, rows + 2)
    nb_cols = random_state.randint(2, cols + 2)
    thickness = random_state.randint(min_dim * 0.01, min_dim * 0.015)
    for _ in range(nb_rows):
        row_idx = random_state.randint(rows + 1)
        col_idx1 = random_state.randint(cols + 1)
        col_idx2 = random_state.randint(cols + 1)
        col = get_random_color(background_color)
        cv.line(
            img,
            (
                warped_points[row_idx * (cols + 1) + col_idx1, 0],
                warped_points[row_idx * (cols + 1) + col_idx1, 1],
            ),
            (
                warped_points[row_idx * (cols + 1) + col_idx2, 0],
                warped_points[row_idx * (cols + 1) + col_idx2, 1],
            ),
            col,
            thickness,
        )
    for _ in range(nb_cols):
        col_idx = random_state.randint(cols + 1)
        row_idx1 = random_state.randint(rows + 1)
        row_idx2 = random_state.randint(rows + 1)
        col = get_random_color(background_color)
        cv.line(
            img,
            (
                warped_points[row_idx1 * (cols + 1) + col_idx, 0],
                warped_points[row_idx1 * (cols + 1) + col_idx, 1],
            ),
            (
                warped_points[row_idx2 * (cols + 1) + col_idx, 0],
                warped_points[row_idx2 * (cols + 1) + col_idx, 1],
            ),
            col,
            thickness,
        )

    # Keep only the points inside the image
    points = keep_points_inside(warped_points, img.shape[:2])
    return {"points": junc_points, "line_map": line_map}


def draw_stripes_multiseg(
    img,
    max_nb_cols=13,
    min_len=0.04,
    min_label_len=64,
    transform_params=(0.05, 0.15),
    seed=None,
):
    """Draw stripes in a distorted rectangle
        and output the junctions points + line map.
    Parameters:
      max_nb_cols: maximal number of stripes to be drawn
      min_width_ratio: the minimal width of a stripe is
                       min_width_ratio * smallest dimension of the image
      transform_params: set the range of the parameters of the transformations
    """
    # Set the optional random seed (most for debugging)
    if seed is None:
        global random_state
    else:
        random_state = np.random.RandomState(seed)

    background_color = int(np.mean(img))
    # Create the grid
    board_size = (
        int(img.shape[0] * (1 + random_state.rand())),
        int(img.shape[1] * (1 + random_state.rand())),
    )

    # Number of cols
    col = random_state.randint(5, max_nb_cols)
    cols = np.concatenate(
        [board_size[1] * random_state.rand(col - 1), np.array([0, board_size[1] - 1])],
        axis=0,
    )
    cols = np.unique(cols.astype(int))

    # Remove the indices that are too close
    min_dim = min(img.shape)

    # Convert length constrain to pixel if given float number
    if isinstance(min_len, float) and min_len <= 1.0:
        min_len = int(min_dim * min_len)
    if isinstance(min_label_len, float) and min_label_len <= 1.0:
        min_label_len = int(min_dim * min_label_len)

    cols = cols[
        (np.concatenate([cols[1:], np.array([board_size[1] + min_len])], axis=0) - cols)
        >= min_len
    ]
    # Update the number of cols
    col = cols.shape[0] - 1
    cols = np.reshape(cols, (col + 1, 1))
    cols1 = np.concatenate([cols, np.zeros((col + 1, 1), np.int32)], axis=1)
    cols2 = np.concatenate(
        [cols, (board_size[0] - 1) * np.ones((col + 1, 1), np.int32)], axis=1
    )
    points = np.concatenate([cols1, cols2], axis=0)

    # Warp the grid using an affine transformation and a homography
    alpha_affine = np.max(img.shape) * (
        transform_params[0] + random_state.rand() * transform_params[1]
    )
    center_square = np.float32(img.shape) // 2
    square_size = min(img.shape) // 3
    pts1 = np.float32(
        [
            center_square + square_size,
            [center_square[0] + square_size, center_square[1] - square_size],
            center_square - square_size,
            [center_square[0] - square_size, center_square[1] + square_size],
        ]
    )
    pts2 = pts1 + random_state.uniform(
        -alpha_affine, alpha_affine, size=pts1.shape
    ).astype(np.float32)
    affine_transform = cv.getAffineTransform(pts1[:3], pts2[:3])
    pts2 = pts1 + random_state.uniform(
        -alpha_affine / 2, alpha_affine / 2, size=pts1.shape
    ).astype(np.float32)
    perspective_transform = cv.getPerspectiveTransform(pts1, pts2)

    # Apply the affine transformation
    points = np.transpose(np.concatenate((points, np.ones((2 * (col + 1), 1))), axis=1))
    warped_points = np.transpose(np.dot(affine_transform, points))

    # Apply the homography
    warped_col0 = np.add(
        np.sum(np.multiply(warped_points, perspective_transform[0, :2]), axis=1),
        perspective_transform[0, 2],
    )
    warped_col1 = np.add(
        np.sum(np.multiply(warped_points, perspective_transform[1, :2]), axis=1),
        perspective_transform[1, 2],
    )
    warped_col2 = np.add(
        np.sum(np.multiply(warped_points, perspective_transform[2, :2]), axis=1),
        perspective_transform[2, 2],
    )
    warped_col0 = np.divide(warped_col0, warped_col2)
    warped_col1 = np.divide(warped_col1, warped_col2)
    warped_points = np.concatenate([warped_col0[:, None], warped_col1[:, None]], axis=1)
    warped_points_float = warped_points.copy()
    warped_points = warped_points.astype(int)

    # Fill the rectangles and get the segments
    color = get_random_color(background_color)
    # segments_debug = np.zeros([0, 4])
    for i in range(col):
        # Fill the color
        color = (color + 128 + random_state.randint(-30, 30)) % 256
        cv.fillConvexPoly(
            img,
            np.array(
                [
                    (warped_points[i, 0], warped_points[i, 1]),
                    (warped_points[i + 1, 0], warped_points[i + 1, 1]),
                    (warped_points[i + col + 2, 0], warped_points[i + col + 2, 1]),
                    (warped_points[i + col + 1, 0], warped_points[i + col + 1, 1]),
                ]
            ),
            color,
        )

    segments = np.zeros([0, 4])
    row = 1  # in stripes case
    # Iterate through rows
    for row_idx in range(row + 1):
        # Include all the combination of the junctions
        # Iterate through all the combination of junction index in that row
        multi_seg_lst = [
            np.array(
                [
                    warped_points_float[id1, 0],
                    warped_points_float[id1, 1],
                    warped_points_float[id2, 0],
                    warped_points_float[id2, 1],
                ]
            )[None, ...]
            for (id1, id2) in combinations(
                range(row_idx * (col + 1), (row_idx + 1) * (col + 1), 1), 2
            )
        ]
        multi_seg = np.concatenate(multi_seg_lst, axis=0)
        segments = np.concatenate((segments, multi_seg), axis=0)

    # Iterate through columns
    for col_idx in range(col + 1):  # for 5 columns, we will have 5 + 1 edges.
        # Include all the combination of the junctions
        # Iterate throuhg all the combination of junction index in that column
        multi_seg_lst = [
            np.array(
                [
                    warped_points_float[id1, 0],
                    warped_points_float[id1, 1],
                    warped_points_float[id2, 0],
                    warped_points_float[id2, 1],
                ]
            )[None, ...]
            for (id1, id2) in combinations(
                range(col_idx, col_idx + (row * col) + 2, col + 1), 2
            )
        ]
        multi_seg = np.concatenate(multi_seg_lst, axis=0)
        segments = np.concatenate((segments, multi_seg), axis=0)

    # Select and refine the segments
    segments_new = np.zeros([0, 4])
    # Define image boundary polygon (in x y manner)
    image_poly = shapely.geometry.Polygon(
        [
            [0, 0],
            [img.shape[1] - 1, 0],
            [img.shape[1] - 1, img.shape[0] - 1],
            [0, img.shape[0] - 1],
        ]
    )
    for idx in range(segments.shape[0]):
        # Get the line segment
        seg_raw = segments[idx, :]
        seg = shapely.geometry.LineString([seg_raw[:2], seg_raw[2:]])

        # The line segment is just inside the image.
        if seg.intersection(image_poly) == seg:
            segments_new = np.concatenate((segments_new, seg_raw[None, ...]), axis=0)

        # Intersect with the image.
        elif seg.intersects(image_poly):
            # Check intersection
            try:
                p = np.array(seg.intersection(image_poly).coords).reshape([-1, 4])
            # If intersect at exact one point, just continue.
            except:
                continue
            segment = p
            segments_new = np.concatenate((segments_new, segment), axis=0)

        else:
            continue

    segments = (np.round(segments_new)).astype(np.int)

    # Only record the segments longer than min_label_len
    points1 = segments[:, :2]
    points2 = segments[:, 2:]
    seg_len = np.sqrt(np.sum((points1 - points2) ** 2, axis=1))
    label_segments = segments[seg_len >= min_label_len, :]

    # Get all junctions from label segments
    junctions_all = np.concatenate(
        (label_segments[:, :2], label_segments[:, 2:]), axis=0
    )
    if junctions_all.shape[0] == 0:
        junc_points = None
        line_map = None

    # Get all unique junction points
    else:
        junc_points = np.unique(junctions_all, axis=0)
        # Generate line map from points and segments
        line_map = get_line_map(junc_points, label_segments)

    # Draw lines on the boundaries of the stripes at random
    nb_rows = random_state.randint(2, 5)
    nb_cols = random_state.randint(2, col + 2)
    thickness = random_state.randint(min_dim * 0.01, min_dim * 0.011)
    for _ in range(nb_rows):
        row_idx = random_state.choice([0, col + 1])
        col_idx1 = random_state.randint(col + 1)
        col_idx2 = random_state.randint(col + 1)
        color = get_random_color(background_color)
        cv.line(
            img,
            (
                warped_points[row_idx + col_idx1, 0],
                warped_points[row_idx + col_idx1, 1],
            ),
            (
                warped_points[row_idx + col_idx2, 0],
                warped_points[row_idx + col_idx2, 1],
            ),
            color,
            thickness,
        )

    for _ in range(nb_cols):
        col_idx = random_state.randint(col + 1)
        color = get_random_color(background_color)
        cv.line(
            img,
            (warped_points[col_idx, 0], warped_points[col_idx, 1]),
            (warped_points[col_idx + col + 1, 0], warped_points[col_idx + col + 1, 1]),
            color,
            thickness,
        )

    # Keep only the points inside the image
    # points = keep_points_inside(warped_points, img.shape[:2])
    return {"points": junc_points, "line_map": line_map}


def draw_cube(
    img,
    min_size_ratio=0.2,
    min_label_len=64,
    scale_interval=(0.4, 0.6),
    trans_interval=(0.5, 0.2),
):
    """Draw a 2D projection of a cube and output the visible juntions.
    Parameters:
      min_size_ratio: min(img.shape) * min_size_ratio is the smallest
                      achievable cube side size
      scale_interval: the scale is between scale_interval[0] and
                      scale_interval[0]+scale_interval[1]
      trans_interval: the translation is between img.shape*trans_interval[0]
                      and img.shape*(trans_interval[0] + trans_interval[1])
    """
    # Generate a cube and apply to it an affine transformation
    # The order matters!
    # The indices of two adjacent vertices differ only of one bit (Gray code)
    background_color = int(np.mean(img))
    min_dim = min(img.shape[:2])
    min_side = min_dim * min_size_ratio
    lx = min_side + random_state.rand() * 2 * min_dim / 3  # dims of the cube
    ly = min_side + random_state.rand() * 2 * min_dim / 3
    lz = min_side + random_state.rand() * 2 * min_dim / 3
    cube = np.array(
        [
            [0, 0, 0],
            [lx, 0, 0],
            [0, ly, 0],
            [lx, ly, 0],
            [0, 0, lz],
            [lx, 0, lz],
            [0, ly, lz],
            [lx, ly, lz],
        ]
    )
    rot_angles = random_state.rand(3) * 3 * math.pi / 10.0 + math.pi / 10.0
    rotation_1 = np.array(
        [
            [math.cos(rot_angles[0]), -math.sin(rot_angles[0]), 0],
            [math.sin(rot_angles[0]), math.cos(rot_angles[0]), 0],
            [0, 0, 1],
        ]
    )
    rotation_2 = np.array(
        [
            [1, 0, 0],
            [0, math.cos(rot_angles[1]), -math.sin(rot_angles[1])],
            [0, math.sin(rot_angles[1]), math.cos(rot_angles[1])],
        ]
    )
    rotation_3 = np.array(
        [
            [math.cos(rot_angles[2]), 0, -math.sin(rot_angles[2])],
            [0, 1, 0],
            [math.sin(rot_angles[2]), 0, math.cos(rot_angles[2])],
        ]
    )
    scaling = np.array(
        [
            [scale_interval[0] + random_state.rand() * scale_interval[1], 0, 0],
            [0, scale_interval[0] + random_state.rand() * scale_interval[1], 0],
            [0, 0, scale_interval[0] + random_state.rand() * scale_interval[1]],
        ]
    )
    trans = np.array(
        [
            img.shape[1] * trans_interval[0]
            + random_state.randint(
                -img.shape[1] * trans_interval[1], img.shape[1] * trans_interval[1]
            ),
            img.shape[0] * trans_interval[0]
            + random_state.randint(
                -img.shape[0] * trans_interval[1], img.shape[0] * trans_interval[1]
            ),
            0,
        ]
    )
    cube = trans + np.transpose(
        np.dot(
            scaling,
            np.dot(
                rotation_1, np.dot(rotation_2, np.dot(rotation_3, np.transpose(cube)))
            ),
        )
    )

    # The hidden corner is 0 by construction
    # The front one is 7
    cube = cube[:, :2]  # project on the plane z=0
    cube = cube.astype(int)
    points = cube[1:, :]  # get rid of the hidden corner

    # Get the three visible faces
    faces = np.array([[7, 3, 1, 5], [7, 5, 4, 6], [7, 6, 2, 3]])

    # Get all visible line segments
    segments = np.zeros([0, 4])
    # Iterate through all the faces
    for face_idx in range(faces.shape[0]):
        face = faces[face_idx, :]
        # Brute-forcely expand all the segments
        segment = np.array(
            [
                np.concatenate((cube[face[0]], cube[face[1]]), axis=0),
                np.concatenate((cube[face[1]], cube[face[2]]), axis=0),
                np.concatenate((cube[face[2]], cube[face[3]]), axis=0),
                np.concatenate((cube[face[3]], cube[face[0]]), axis=0),
            ]
        )
        segments = np.concatenate((segments, segment), axis=0)

    # Select and refine the segments
    segments_new = np.zeros([0, 4])
    # Define image boundary polygon (in x y manner)
    image_poly = shapely.geometry.Polygon(
        [
            [0, 0],
            [img.shape[1] - 1, 0],
            [img.shape[1] - 1, img.shape[0] - 1],
            [0, img.shape[0] - 1],
        ]
    )
    for idx in range(segments.shape[0]):
        # Get the line segment
        seg_raw = segments[idx, :]
        seg = shapely.geometry.LineString([seg_raw[:2], seg_raw[2:]])

        # The line segment is just inside the image.
        if seg.intersection(image_poly) == seg:
            segments_new = np.concatenate((segments_new, seg_raw[None, ...]), axis=0)

        # Intersect with the image.
        elif seg.intersects(image_poly):
            try:
                p = np.array(seg.intersection(image_poly).coords).reshape([-1, 4])
            except:
                continue
            segment = p
            segments_new = np.concatenate((segments_new, segment), axis=0)

        else:
            continue

    segments = (np.round(segments_new)).astype(np.int)

    # Only record the segments longer than min_label_len
    points1 = segments[:, :2]
    points2 = segments[:, 2:]
    seg_len = np.sqrt(np.sum((points1 - points2) ** 2, axis=1))
    label_segments = segments[seg_len >= min_label_len, :]

    # Get all junctions from label segments
    junctions_all = np.concatenate(
        (label_segments[:, :2], label_segments[:, 2:]), axis=0
    )
    if junctions_all.shape[0] == 0:
        junc_points = None
        line_map = None

    # Get all unique junction points
    else:
        junc_points = np.unique(junctions_all, axis=0)
        # Generate line map from points and segments
        line_map = get_line_map(junc_points, label_segments)

    # Fill the faces and draw the contours
    col_face = get_random_color(background_color)
    for i in [0, 1, 2]:
        cv.fillPoly(img, [cube[faces[i]].reshape((-1, 1, 2))], col_face)
    thickness = random_state.randint(min_dim * 0.003, min_dim * 0.015)
    for i in [0, 1, 2]:
        for j in [0, 1, 2, 3]:
            col_edge = (
                col_face + 128 + random_state.randint(-64, 64)
            ) % 256  # color that constrats with the face color
            cv.line(
                img,
                (cube[faces[i][j], 0], cube[faces[i][j], 1]),
                (cube[faces[i][(j + 1) % 4], 0], cube[faces[i][(j + 1) % 4], 1]),
                col_edge,
                thickness,
            )

    return {"points": junc_points, "line_map": line_map}


def gaussian_noise(img):
    """Apply random noise to the image."""
    cv.randu(img, 0, 255)
    return {"points": None, "line_map": None}