-
Notifications
You must be signed in to change notification settings - Fork 56
/
QP.py
executable file
·3067 lines (2599 loc) · 117 KB
/
QP.py
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
from gurobipy import *
import cv2
import numpy as np
import sys
import csv
import copy
from utils import *
from floorplan_utils import *
from skimage import measure
# if len(sys.argv) == 2 and int(sys.argv[1]) == 1:
# withoutQP = True
# else:
# withoutQP = False
# pass
withoutQP = False
#GAP = 5
#GAPS = {'wall_extraction': 10, 'door_extraction': 5, 'icon_extraction': 5, 'wall_neighbor': 10, 'door_neighbor': 10, 'icon_neighbor': 10, 'wall_conflict': 10, 'door_conflict': 10, 'icon_conflict': 10, 'wall_icon_neighbor': 5, 'wall_icon_conflict': 5, 'wall_door_neighbor': 5}
#DISTANCES = {'wall_icon': 10, 'point': 10, 'wall': 10, 'door': 10, 'icon': 10}
GAPS = {'wall_extraction': 5, 'door_extraction': 5, 'icon_extraction': 5, 'wall_neighbor': 5, 'door_neighbor': 5, 'icon_neighbor': 5, 'wall_conflict': 5, 'door_conflict': 5, 'icon_conflict': 5, 'wall_icon_neighbor': 5, 'wall_icon_conflict': 5, 'wall_door_neighbor': 5, 'door_point_conflict': 5}
DISTANCES = {'wall_icon': 5, 'point': 5, 'wall': 10, 'door': 5, 'icon': 5}
LENGTH_THRESHOLDS = {'wall': 5, 'door': 5, 'icon': 5}
junctionWeight = 100
augmentedJunctionWeight = 50
labelWeight = 1
wallWeight = 10
doorWeight = 10
iconWeight = 10
#wallTypeWeight = 10
#doorTypeWeight = 10
iconTypeWeight = 10
wallLineWidth = 3
doorLineWidth = 2
#doorExposureWeight = 0
NUM_WALL_TYPES = 1
NUM_DOOR_TYPES = 2
#NUM_LABELS = NUM_WALL_TYPES + NUM_DOOR_TYPES + NUM_ICONS + NUM_ROOMS + 1
NUM_LABELS = NUM_ICONS + NUM_ROOMS
WALL_LABEL_OFFSET = NUM_FINAL_ROOMS
DOOR_LABEL_OFFSET = NUM_FINAL_ICONS + 1
ICON_LABEL_OFFSET = 0
ROOM_LABEL_OFFSET = NUM_ICONS
colorMap = ColorPalette(NUM_CORNERS).getColorMap()
#colorMap = np.random.rand(11, 3) * 255
#colorMap[0] = 160
# iconWallTypesMap[0] = 'bathtub'
# iconWallTypesMap[1] = 'cooking counter'
# iconWallTypesMap[2] = 'toilet'
# iconWallTypesMap[3] = 'entrance'
# iconWallTypesMap[4] = 'washing basin'
# iconWallTypesMap[5] = 'washing machine'
# iconWallTypesMap[6] = 'washing basin'
# iconWallTypesMap[7] = 'cross'
# iconWallTypesMap[8] = 'column'
# iconWallTypesMap[9] = 'stairs'
#floorplan = cv2.imread('test/floorplan.png')
width = 256
height = 256
maxDim = max(width, height)
sizes = np.array([width, height])
ORIENTATION_RANGES = getOrientationRanges(width, height)
#iconStyles = [1, 1, 1, 1, 1, 2, 1, 1, 3, 1]
iconNames = getIconNames()
iconNameNumberMap = dict(zip(iconNames, xrange(len(iconNames))))
iconNumberNameMap = dict(zip(xrange(len(iconNames)), iconNames))
#iconNumberStyleMap = dict(zip(xrange(len(iconStyles)), iconStyles))
def findMatches(pred_dict, gt_dict, distanceThreshold, width=256, height=256):
correctSums = {k: 0.0 for k in gt_dict}
countsGT = {k: 0.0 for k in gt_dict}
countsPred = {k: 0.0 for k in gt_dict}
for objectType, objects in gt_dict.iteritems():
if objectType not in pred_dict:
print(objectType + ' not in prediction')
continue
pointsGT = objects[0]
pointsPred = pred_dict[objectType][0]
if objectType == 'wall':
validPointMaskGT = {}
for line in objects[1]:
validPointMaskGT[line[0]] = True
validPointMaskGT[line[1]] = True
continue
validPointsGT = [pointsGT[pointIndex] for pointIndex in validPointMaskGT]
#print([(pred_dict[objectType][0][line[0]][:2], pred_dict[objectType][0][line[1]][:2]) for line in pred_dict[objectType][1]])
#exit(1)
validPointMaskPred = {}
for line in pred_dict[objectType][1]:
validPointMaskPred[line[0]] = True
validPointMaskPred[line[1]] = True
continue
validPointsPred = [pointsPred[pointIndex] for pointIndex in validPointMaskPred]
if True:
# degree insensitive
pointIndexMap = []
for pointIndexGT, pointGT in enumerate(validPointsGT):
matchedPointMask = {}
for pointIndexPred, pointPred in enumerate(validPointsPred):
if pointPred[2] == pointGT[2] and pointPred[3] == pointGT[3] and pointDistance(pointPred[0:2], pointGT[0:2]) < distanceThreshold:
matchedPointMask[pointIndexPred] = True
pass
continue
if len(matchedPointMask) == 0:
print(pointIndexGT, pointGT, 'point not found')
pass
pointIndexMap.append(matchedPointMask)
continue
correctSums[objectType] += len([indexMap for indexMap in pointIndexMap if len(indexMap) > 0])
countsGT[objectType] += len(validPointsGT)
countsPred[objectType] += len(validPointsPred)
else:
numMatches = 0
matchedMask = {}
pointMatchMap = {}
for pointIndexPred, pointPred in enumerate(validPointsPred):
minDistancePair = (10000, -1)
for pointIndexGT, pointGT in enumerate(validPointsGT):
distance = pointDistance(pointPred[0:2], pointGT[0:2])
if distance < minDistancePair[0]:
minDistancePair = (distance, pointIndexGT)
pass
continue
pointMatchMap[pointIndexPred] = minDistancePair[1]
continue
for pointIndexGT, pointGT in enumerate(validPointsGT):
matchedOrientations = {}
for orientation in POINT_ORIENTATIONS[pointGT[2]][pointGT[3]]:
matchedOrientations[orientation] = False
continue
for pointIndexPred, pointPred in enumerate(validPointsPred):
if pointMatchMap[pointIndexPred] != pointIndexGT:
continue
if pointDistance(pointPred[0:2], pointGT[0:2]) < distanceThreshold:
for orientation in POINT_ORIENTATIONS[pointPred[2]][pointPred[3]]:
if orientation in matchedOrientations and matchedOrientations[orientation] == False:
if (pointIndexPred, orientation) not in matchedMask:
matchedMask[(pointIndexPred, orientation)] = True
matchedOrientations[orientation] = True
pass
pass
continue
pass
continue
for orientation, hasMatch in matchedOrientations.iteritems():
if not hasMatch:
print(pointIndexGT, pointGT, orientation, 'point not found')
pass
continue
numMatches += len([orientation for orientation, value in matchedOrientations.iteritems() if value == True])
continue
correctSums[objectType] += numMatches
countsGT[objectType] += sum([point[2] + 1 for point in validPointsGT])
countsPred[objectType] += sum([point[2] + 1 for point in validPointsPred])
continue
if objectType == 'door':
linesGT = objects[1]
linesPred = pred_dict[objectType][1]
lineIndexMap = []
for lineIndexGT, lineGT in enumerate(linesGT):
matchedLineMask = {}
for lineIndexPred, linePred in enumerate(linesPred):
#if (linePred[0] in pointIndexMap[lineGT[0]] and linePred[1] in pointIndexMap[lineGT[1]]) or (linePred[1] in pointIndexMap[lineGT[0]] and linePred[0] in pointIndexMap[lineGT[1]]):
if (pointDistance(pointsPred[linePred[0]], pointsGT[lineGT[0]]) < distanceThreshold and pointDistance(pointsPred[linePred[1]], pointsGT[lineGT[1]]) < distanceThreshold) or (pointDistance(pointsPred[linePred[0]], pointsGT[lineGT[1]]) < distanceThreshold and pointDistance(pointsPred[linePred[1]], pointsGT[lineGT[0]]) < distanceThreshold):
matchedLineMask[lineIndexPred] = True
#print('match', lineGT, linePred)
pass
continue
if len(matchedLineMask) == 0:
print(lineIndexGT, lineGT, [pointsGT[pointIndex][:2] for pointIndex in lineGT], 'door not found')
pass
lineIndexMap.append(matchedLineMask)
continue
correctSums[objectType] += len([indexMap for indexMap in lineIndexMap if len(indexMap) > 0])
countsGT[objectType] += len(linesGT)
countsPred[objectType] += len(linesPred)
continue
if objectType == 'icon':
rectanglesGT = objects[1]
rectanglesPred = pred_dict[objectType][1]
labelsGT = objects[2]
labelsPred = pred_dict[objectType][2]
rectangleIndexMap = []
for indexGT, rectangleGT in enumerate(rectanglesGT):
matchedRectangleMask = {}
for indexPred, rectanglePred in enumerate(rectanglesPred):
if labelsGT[indexGT] == labelsPred[indexPred] and calcIOU([pointsPred[pointIndex] for pointIndex in rectanglePred], [pointsGT[pointIndex] for pointIndex in rectangleGT]) >= 0.3:
matchedRectangleMask[indexPred] = True
pass
continue
if len(matchedRectangleMask) == 0:
print(indexGT, rectangleGT, [pointsGT[pointIndex][:2] for pointIndex in rectangleGT], 'icon not found')
pass
rectangleIndexMap.append(matchedRectangleMask)
continue
correctSums[objectType] += len([indexMap for indexMap in rectangleIndexMap if len(indexMap) > 0])
countsGT[objectType] += len(rectanglesGT)
countsPred[objectType] += len(rectanglesPred)
pass
continue
roomsInfo = []
wallLineWidth = 3
dicts = [gt_dict, pred_dict]
for dictIndex in xrange(2):
wall_dict = dicts[dictIndex]['wall']
wallMask = drawWallMask([(wall_dict[0][line[0]], wall_dict[0][line[1]]) for line in wall_dict[1]], width, height, thickness=wallLineWidth)
roomRegions = measure.label(1 - wallMask, background=0)
cv2.imwrite('test/' + str(dictIndex) + '_segmentation_regions.png', drawSegmentationImage(roomRegions))
backgroundIndex = roomRegions.min()
wallPoints = wall_dict[0]
roomSegmentation = np.zeros(roomRegions.shape, dtype=np.int32)
roomLabels = {}
adjacentRoomPairs = []
for wallIndex, wallLabels in enumerate(wall_dict[2]):
wallLine = wall_dict[1][wallIndex]
lineDim = calcLineDim(wallPoints, wallLine)
center = np.round((np.array(wallPoints[wallLine[0]][:2]) + np.array(wallPoints[wallLine[1]][:2])) / 2).astype(np.int32)
adjacentRoomPair = []
for c in xrange(2):
direction = c * 2 - 1
if lineDim == 1:
direction *= -1
pass
point = center
for offset in xrange(10):
point[1 - lineDim] += direction
if point[1 - lineDim] < 0 or point[1 - lineDim] >= sizes[1 - lineDim]:
break
roomIndex = roomRegions[point[1], point[0]]
if roomIndex != backgroundIndex:
#print(wallIndex, center.tolist(), point.tolist(), wallLabels[c])
# if wallLabels[c] not in rooms:
# rooms[wallLabels[c]] = []
# pass
mask = roomRegions == roomIndex
roomSegmentation[mask] = wallLabels[c]
#rooms[wallLabels[c]].append(cv2.dilate(mask.astype(np.uint8), np.ones((3, 3)), iterations=wallLineWidth))
#roomRegions[mask] = backgroundIndex
if roomIndex not in roomLabels:
roomLabels[roomIndex] = {}
pass
roomLabels[roomIndex][wallLabels[c]] = True
adjacentRoomPair.append(roomIndex)
break
pass
continue
continue
if len(adjacentRoomPair) == 2:
adjacentRoomPairs.append(adjacentRoomPair)
pass
continue
neighborRoomPairs = []
door_dict = dicts[dictIndex]['door']
for doorLine in door_dict[1]:
lineDim = calcLineDim(door_dict[0], doorLine)
center = np.round((np.array(door_dict[0][doorLine[0]][:2]) + np.array(door_dict[0][doorLine[1]][:2])) / 2).astype(np.int32)
neighborRoomPair = []
for c in xrange(2):
direction = c * 2 - 1
point = center
for offset in xrange(10):
point[1 - lineDim] += direction
if point[lineDim] < 0 or point[lineDim] >= sizes[lineDim]:
break
roomIndex = roomRegions[point[1], point[0]]
if roomIndex != backgroundIndex:
neighborRoomPair.append(roomIndex)
break
pass
continue
continue
if len(neighborRoomPair) == 2:
neighborRoomPairs.append(neighborRoomPair)
pass
continue
rooms = []
indexMap = {}
for roomIndex, labels in roomLabels.iteritems():
indexMap[roomIndex] = len(rooms)
mask = roomRegions == roomIndex
mask = cv2.dilate(mask.astype(np.uint8), np.ones((3, 3)), iterations=wallLineWidth)
if 7 in labels and 2 not in labels:
labels[2] = True
pass
if 5 in labels and 3 not in labels:
labels[3] = True
pass
if 9 in labels and 1 not in labels:
labels[1] = True
pass
rooms.append((mask, labels))
continue
neighborRoomPairs = [(indexMap[neighborRoomPair[0]], indexMap[neighborRoomPair[1]]) for neighborRoomPair in neighborRoomPairs]
neighborMatrix = np.zeros((len(rooms), len(rooms)))
for neighborRoomPair in neighborRoomPairs:
neighborMatrix[neighborRoomPair[0]][neighborRoomPair[1]] = 1
neighborMatrix[neighborRoomPair[1]][neighborRoomPair[0]] = 1
continue
adjacentRoomPairs = [(indexMap[adjacentRoomPair[0]], indexMap[adjacentRoomPair[1]]) for adjacentRoomPair in adjacentRoomPairs]
adjacentMatrix = np.zeros((len(rooms), len(rooms)))
for adjacentRoomPair in adjacentRoomPairs:
adjacentMatrix[adjacentRoomPair[0]][adjacentRoomPair[1]] = 1
adjacentMatrix[adjacentRoomPair[1]][adjacentRoomPair[0]] = 1
continue
#exit(1)
roomsInfo.append([rooms, neighborMatrix, adjacentMatrix])
continue
#gt_dict['room'] = zip(*roomsInfo[0][0])
#pred_dict['room'] = zip(*roomsInfo[1][0])
#countsPred['room'] = sum([len(roomsPred) for roomLabel, roomsPred in labelRooms[1].iteritems()])
countsPred['room'] = len(roomsInfo[1][0])
countsGT['room'] = len(roomsInfo[0][0])
correctSums['room'] = 0.0
for roomGT in roomsInfo[0][0]:
hasMatch = False
for roomPred in roomsInfo[1][0]:
hasCommonLabel = False
for labelGT in roomGT[1]:
if labelGT in roomPred[1]:
hasCommonLabel = True
break
continue
# if 8 in roomGT[1]:
# print(roomPred[1], calcIOUMask(roomPred[0], roomGT[0]))
# pass
if hasCommonLabel and calcIOUMask(roomPred[0], roomGT[0]) >= 0.5:
correctSums['room'] += 1
hasMatch = True
break
continue
if not hasMatch:
print(roomGT[1].keys(), roomGT[0].max(0).nonzero()[0].mean(), roomGT[0].max(1).nonzero()[0].mean(), 'room not found')
pass
continue
#print(labelRooms[1])
statistics = {k: [v, countsGT[k], countsPred[k]] for k, v in correctSums.iteritems()}
roomIndexMap = np.zeros(len(roomsInfo[1][0]))
orderedRoomPred = {}
for roomIndexPred, roomPred in enumerate(roomsInfo[1][0]):
maxIOURoom = (0, -1)
for roomIndexGT, roomGT in enumerate(roomsInfo[0][0]):
IOU = calcIOUMask(roomPred[0], roomGT[0])
if IOU > maxIOURoom[0]:
maxIOURoom = (IOU, roomIndexGT)
pass
continue
if maxIOURoom[1] < 0:
print(roomPred[1].keys(), roomPred[0].max(0).nonzero()[0].mean(), roomPred[0].max(1).nonzero()[0].mean(), 'room has no match')
exit(1)
pass
roomIndexGT = maxIOURoom[1]
roomIndexMap[roomIndexPred] = roomIndexGT
if roomIndexGT not in orderedRoomPred:
orderedRoomPred[roomIndexGT] = roomPred
else:
mask = orderedRoomPred[roomIndexGT][0] + roomPred[0]
roomLabels = {}
for label in orderedRoomPred[roomIndexGT][1]:
roomLabels[label] = True
continue
for label in roomPred[1]:
roomLabels[label] = True
continue
orderedRoomPred[roomIndexGT] = (mask, roomLabels)
pass
continue
roomIndexMap = (np.expand_dims(roomIndexMap, -1) == np.expand_dims(np.arange(len(roomsInfo[0][0]), dtype=np.int32), 0)).astype(np.int32)
# print('GT', [(roomIndexGT, roomGT[1].keys(), roomGT[0].max(0).nonzero()[0].mean(), roomGT[0].max(1).nonzero()[0].mean()) for roomIndexGT, roomGT in enumerate(roomsInfo[0][0])])
# print('Pred', [(roomIndexPred, roomPred[1].keys(), roomPred[0].max(0).nonzero()[0].mean(), roomPred[0].max(1).nonzero()[0].mean()) for roomIndexPred, roomPred in enumerate(roomsInfo[1][0])])
# print(roomsInfo[0][1], roomsInfo[0][2])
# print(roomsInfo[1][1], roomsInfo[1][2])
# print(roomIndexMap)
roomsInfo[1][1] = np.matmul(roomIndexMap.transpose(), np.matmul(roomsInfo[1][1], roomIndexMap))
roomsInfo[1][2] = np.matmul(roomIndexMap.transpose(), np.matmul(roomsInfo[1][2], roomIndexMap))
#print(roomsInfo[1][1], roomsInfo[1][2])
#print(roomsInfo[0][1], roomsInfo[0][2])
# exit(1)
topologyStatistics = {k: [0.0, 0.0, 0.0] for k in ['adjacent', 'neighbor', 'neighbor_foreground', 'adjacent_all' , 'neighbor_all', 'neighbor_all_foreground', 'all', 'all_foreground']}
for k in ['adjacent_all' , 'neighbor_all', 'all']:
topologyStatistics[k][1] = topologyStatistics[k][2] = len(roomsInfo[0][0])
continue
for k in ['neighbor_all_foreground', 'all_foreground']:
topologyStatistics[k][1] = topologyStatistics[k][2] = len(roomsInfo[0][0]) - 1
continue
for roomIndex, roomGT in enumerate(roomsInfo[0][0]):
if roomIndex not in orderedRoomPred:
continue
roomPred = orderedRoomPred[roomIndex]
hasCommonLabel = False
for labelGT in roomGT[1]:
if labelGT in roomPred[1]:
hasCommonLabel = True
break
continue
if hasCommonLabel and calcIOUMask(roomPred[0], roomGT[0]) >= 0.5:
neighborMatchMask = roomsInfo[0][1][roomIndex] == roomsInfo[1][1][roomIndex]
topologyStatistics['neighbor'][0] += (neighborMatchMask * roomsInfo[0][1][roomIndex]).sum()
topologyStatistics['neighbor'][1] += roomsInfo[0][1][roomIndex].sum()
topologyStatistics['neighbor'][2] += roomsInfo[1][1][roomIndex].sum()
topologyStatistics['neighbor_all'][0] += int(np.all(neighborMatchMask))
adjacentMatchMask = roomsInfo[0][2][roomIndex] == roomsInfo[1][2][roomIndex]
topologyStatistics['adjacent'][0] += (adjacentMatchMask * roomsInfo[0][2][roomIndex]).sum()
topologyStatistics['adjacent'][1] += roomsInfo[0][2][roomIndex].sum()
topologyStatistics['adjacent'][2] += roomsInfo[1][2][roomIndex].sum()
topologyStatistics['adjacent_all'][0] += int(np.all(adjacentMatchMask))
topologyStatistics['all'][0] += int(np.all(neighborMatchMask) and np.all(adjacentMatchMask))
if roomIndex > 0:
topologyStatistics['neighbor_foreground'][0] += (neighborMatchMask[1:] * roomsInfo[0][1][roomIndex][1:]).sum()
topologyStatistics['neighbor_foreground'][1] += roomsInfo[0][1][roomIndex][1:].sum()
topologyStatistics['neighbor_foreground'][2] += roomsInfo[1][1][roomIndex][1:].sum()
topologyStatistics['neighbor_all_foreground'][0] += int(np.all(neighborMatchMask[1:]))
topologyStatistics['all_foreground'][0] += int(np.all(neighborMatchMask[1:]) and np.all(adjacentMatchMask[1:]))
pass
else:
print('incorrect label')
print(roomGT[1].keys(), roomGT[0].max(0).nonzero()[0].mean(), roomGT[0].max(1).nonzero()[0].mean())
print(roomPred[1].keys(), roomPred[0].max(0).nonzero()[0].mean(), roomPred[0].max(1).nonzero()[0].mean())
pass
continue
#print(roomsInfo[0][1], roomsInfo[1][1], roomsInfo[0][2], roomsInfo[1][2])
#print('topology', len(roomsInfo[0][0]), numMatchedRooms)
#print(statistics['room'])
#topologyStatistics = {k: topologyStatistics[k] for k in ['neighbor_foreground', 'neighbor', 'neighbor_all', 'neighbor_all_foreground']}
for k in ['neighbor_foreground', 'neighbor_all_foreground']:
statistics[k[:-11]] = topologyStatistics[k]
continue
return statistics
def extractCorners(heatmaps, threshold, gap, cornerType = 'wall', augment=False, h_points=False, gt=False):
if gt:
orientationPoints = heatmaps
else:
orientationPoints = extractCornersFromHeatmaps(heatmaps, threshold)
pass
#print(orientationPoints[7])
#print(orientationPoints[12])
#exit(1)
if cornerType == 'wall':
cornerOrientations = []
for orientations in POINT_ORIENTATIONS:
cornerOrientations += orientations
continue
elif cornerType == 'door':
cornerOrientations = POINT_ORIENTATIONS[0]
else:
cornerOrientations = POINT_ORIENTATIONS[1]
pass
#print(orientationPoints)
if h_points:
res = myaugmenthack(orientationPoints, cornerOrientations, cornerType, gap)
totalAugmentedPts = 0
for k,v in res.items():
orientationPoints[k].extend(v)
totalAugmentedPts += len(v)
print("total augmented points", totalAugmentedPts)
if augment:
orientationMap = {}
for pointType, orientationOrientations in enumerate(POINT_ORIENTATIONS):
for orientation, orientations in enumerate(orientationOrientations):
orientationMap[orientations] = orientation
continue
continue
for orientationIndex, corners in enumerate(orientationPoints):
if len(corners) > 3:
continue #skip aug
pointType = orientationIndex / 4
if pointType in [2]:
orientation = orientationIndex % 4
orientations = POINT_ORIENTATIONS[pointType][orientation]
for i in xrange(len(orientations)):
newOrientations = list(orientations)
newOrientations.remove(orientations[i])
newOrientations = tuple(newOrientations)
if not newOrientations in orientationMap:
continue
newOrientation = orientationMap[newOrientations]
for corner in corners:
orientationPoints[(pointType - 1) * 4 + newOrientation].append(corner + (True, ))
continue
continue
elif pointType in [1]:
orientation = orientationIndex % 4
orientations = POINT_ORIENTATIONS[pointType][orientation]
for orientation in xrange(4):
if orientation in orientations:
continue
newOrientations = list(orientations)
newOrientations.append(orientation)
newOrientations = tuple(newOrientations)
if not newOrientations in orientationMap:
continue
newOrientation = orientationMap[newOrientations]
for corner in corners:
orientationPoints[(pointType + 1) * 4 + newOrientation].append(corner + (True, ))
continue
continue
pass
continue
pass
#print(orientationPoints)
pointOffset = 0
pointOffsets = []
points = []
pointOrientationLinesMap = []
for orientationIndex, corners in enumerate(orientationPoints):
pointOffsets.append(pointOffset)
orientations = cornerOrientations[orientationIndex]
for point in corners:
orientationLines = {}
for orientation in orientations:
orientationLines[orientation] = []
continue
pointOrientationLinesMap.append(orientationLines)
continue
pointOffset += len(corners)
if cornerType == 'wall':
points += [[corner[0][0], corner[0][1], orientationIndex / 4, orientationIndex % 4] for corner in corners]
elif cornerType == 'door':
points += [[corner[0][0], corner[0][1], 0, orientationIndex] for corner in corners]
else:
points += [[corner[0][0], corner[0][1], 1, orientationIndex] for corner in corners]
pass
continue
augmentedPointMask = {}
lines = []
pointNeighbors = [[] for point in points]
for orientationIndex, corners in enumerate(orientationPoints):
orientations = cornerOrientations[orientationIndex]
for orientation in orientations:
if orientation not in [1, 2]:
continue
oppositeOrientation = (orientation + 2) % 4
lineDim = -1
if orientation == 0 or orientation == 2:
lineDim = 1
else:
lineDim = 0
pass
for cornerIndex, corner in enumerate(corners):
pointIndex = pointOffsets[orientationIndex] + cornerIndex
#print(corner)
if len(corner) > 3:
augmentedPointMask[pointIndex] = True
pass
ranges = copy.deepcopy(ORIENTATION_RANGES[orientation])
ranges[lineDim] = min(ranges[lineDim], corner[0][lineDim])
ranges[lineDim + 2] = max(ranges[lineDim + 2], corner[0][lineDim])
ranges[1 - lineDim] = min(ranges[1 - lineDim], corner[1][1 - lineDim] - gap)
ranges[1 - lineDim + 2] = max(ranges[1 - lineDim + 2], corner[2][1 - lineDim] + gap)
for oppositeOrientationIndex, oppositeCorners in enumerate(orientationPoints):
if oppositeOrientation not in cornerOrientations[oppositeOrientationIndex]:
continue
for oppositeCornerIndex, oppositeCorner in enumerate(oppositeCorners):
if orientationIndex == oppositeOrientationIndex and oppositeCornerIndex == cornerIndex:
continue
oppositePointIndex = pointOffsets[oppositeOrientationIndex] + oppositeCornerIndex
if oppositeCorner[0][lineDim] < ranges[lineDim] or oppositeCorner[0][lineDim] > ranges[lineDim + 2] or ranges[1 - lineDim] > oppositeCorner[2][1 - lineDim] or ranges[1 - lineDim + 2] < oppositeCorner[1][1 - lineDim]:
continue
if abs(oppositeCorner[0][lineDim] - corner[0][lineDim]) < LENGTH_THRESHOLDS[cornerType]:
continue
lineIndex = len(lines)
pointOrientationLinesMap[pointIndex][orientation].append(lineIndex)
pointOrientationLinesMap[oppositePointIndex][oppositeOrientation].append(lineIndex)
pointNeighbors[pointIndex].append(oppositePointIndex)
pointNeighbors[oppositePointIndex].append(pointIndex)
lines.append((pointIndex, oppositePointIndex))
continue
continue
continue
continue
continue
# pointType = orientationIndex / 4
# orientation = orientationIndex % 4
# orientations = POINT_ORIENTATIONS[pointType][orientation]
# for i in xrange(len(orientations)):
# newOrientations = list(orientations)
# newOrientations.remove(orientations[i])
# newOrientations = tuple(newOrientations)
# if not newOrientations in orientationMap:
# continue
# newOrientation = orientationMap[newOrientations]
# for corner in corners:
# orientationPoints[(pointType - 1) * 4 + newOrientation].append(corner + (True, ))
# continue
# continue
# continue
#print('augs', len(augmentedPointMask))
return points, lines, pointOrientationLinesMap, pointNeighbors, augmentedPointMask
def myaugmenthack(orientationPoints, cornerOrientations, cornerType, gap):
lines = []
pointOffset = 0
pointOffsets = []
points = []
pointOrientationLinesMap = []
for orientationIndex, corners in enumerate(orientationPoints):
pointOffsets.append(pointOffset)
orientations = cornerOrientations[orientationIndex]
for point in corners:
orientationLines = {}
for orientation in orientations:
orientationLines[orientation] = []
continue
pointOrientationLinesMap.append(orientationLines)
continue
pointOffset += len(corners)
if cornerType == 'wall':
points += [[corner[0][0], corner[0][1], orientationIndex / 4, orientationIndex % 4] for corner in corners]
elif cornerType == 'door':
points += [[corner[0][0], corner[0][1], 0, orientationIndex] for corner in corners]
else:
points += [[corner[0][0], corner[0][1], 1, orientationIndex] for corner in corners]
pass
continue
augmentedPointMask = {}
lines = []
pointNeighbors = [[] for point in points]
for orientationIndex, corners in enumerate(orientationPoints):
orientations = cornerOrientations[orientationIndex]
for orientation in orientations:
if orientation not in [1, 2]:
continue
oppositeOrientation = (orientation + 2) % 4
lineDim = -1
if orientation == 0 or orientation == 2:
lineDim = 1
else:
lineDim = 0
pass
for cornerIndex, corner in enumerate(corners):
pointIndex = pointOffsets[orientationIndex] + cornerIndex
ranges = copy.deepcopy(ORIENTATION_RANGES[orientation])
ranges[lineDim] = min(ranges[lineDim], corner[0][lineDim])
ranges[lineDim + 2] = max(ranges[lineDim + 2], corner[0][lineDim])
ranges[1 - lineDim] = min(ranges[1 - lineDim], corner[1][1 - lineDim] - gap)
ranges[1 - lineDim + 2] = max(ranges[1 - lineDim + 2], corner[2][1 - lineDim] + gap)
for oppositeOrientationIndex, oppositeCorners in enumerate(orientationPoints):
if oppositeOrientation not in cornerOrientations[oppositeOrientationIndex]:
continue
for oppositeCornerIndex, oppositeCorner in enumerate(oppositeCorners):
if orientationIndex == oppositeOrientationIndex and oppositeCornerIndex == cornerIndex:
continue
oppositePointIndex = pointOffsets[oppositeOrientationIndex] + oppositeCornerIndex
if oppositeCorner[0][lineDim] < ranges[lineDim] or oppositeCorner[0][lineDim] > ranges[lineDim + 2] or ranges[1 - lineDim] > oppositeCorner[2][1 - lineDim] or ranges[1 - lineDim + 2] < oppositeCorner[1][1 - lineDim]:
continue
if abs(oppositeCorner[0][lineDim] - corner[0][lineDim]) < LENGTH_THRESHOLDS[cornerType]:
continue
lineIndex = len(lines)
pointOrientationLinesMap[pointIndex][orientation].append(lineIndex)
pointOrientationLinesMap[oppositePointIndex][oppositeOrientation].append(lineIndex)
pointNeighbors[pointIndex].append(oppositePointIndex)
pointNeighbors[oppositePointIndex].append(pointIndex)
lines.append((pointIndex, oppositePointIndex))
continue
continue
continue
continue
continue
augmented_points = {}
# for orientationIndex, corners in enumerate(orientationPoints):
# augmented_points[orientationIndex] = []
orientationMap = {}
for pointType, orientationOrientations in enumerate(POINT_ORIENTATIONS):
for orientation, orientations in enumerate(orientationOrientations):
orientationMap[orientations] = pointType*4 + orientation
continue
continue
# for k,vs in enumerate(pointNeighbors):
# for v in vs:
# print(points[k], points[v])
for orientationIndex1, corners1 in enumerate(orientationPoints):
for cornerIndex1, corner1 in enumerate(corners1):
pointIndex1 = pointOffsets[orientationIndex1] + cornerIndex1
point1 = points[pointIndex1]
for orientationIndex2, corners2 in enumerate(orientationPoints):
for cornerIndex2, corner2 in enumerate(corners2):
if orientationIndex2 == orientationIndex1 and cornerIndex2 == cornerIndex1:
continue
pointIndex2 = pointOffsets[orientationIndex2] + cornerIndex2
point2 = points[pointIndex2]
for orientationIndex3, corners3 in enumerate(orientationPoints):
for cornerIndex3, corner3 in enumerate(corners3):
if orientationIndex3 == orientationIndex1 and cornerIndex3 == cornerIndex1:
continue
if orientationIndex3 == orientationIndex2 and cornerIndex3 == cornerIndex2:
continue
pointIndex3 = pointOffsets[orientationIndex3] + cornerIndex3
point3 = points[pointIndex3]
if pointIndex2 in pointNeighbors[pointIndex1] and pointIndex3 in pointNeighbors[pointIndex2]:
if abs(point1[0] - point3[0]) < gap or abs(point1[1] - point3[1]) < gap:
continue
fourthPoints = set(pointNeighbors[pointIndex1]) & set(pointNeighbors[pointIndex3])
valid_fourth = []
for point4 in fourthPoints:
if abs(points[point4][0] - point2[0]) > gap and abs(points[point4][1] - point2[1]) > gap:
valid_fourth.append(point4)
pass
pass
# usable_orientations = set(range(len(POINT_ORIENTATIONS[point1[2]])))
# used_orientation = set([point1[3], point2[3], point3[3]])
# fourth_orientation = usable_orientations - used_orientation
pt2_has = set(POINT_ORIENTATIONS[point2[2]][point2[3]])
oppositeOrientation2 = set([(orient+2)%4for orient in pt2_has])
pt1_has = set(POINT_ORIENTATIONS[point1[2]][point1[3]])
oppositeOrientation1 = set([(orient+2)%4for orient in pt1_has])
# pt1_needed = oppositeOrientation1 - pt2_has
pt3_has = set(POINT_ORIENTATIONS[point3[2]][point3[3]])
oppositeOrientation3 = set([(orient+2)%4for orient in pt3_has])
# pt3_needed = oppositeOrientation3 - pt2_has
newPoint_orientation = orientationMap[tuple(oppositeOrientation2)]
print('orient', newPoint_orientation, oppositeOrientation2)
if len(valid_fourth) == 0:
print('test orientation', oppositeOrientation2, oppositeOrientation1, oppositeOrientation3)
newPoint1 = [point1[0], point3[1], newPoint_orientation/4, newPoint_orientation%4]
newPoint2 = [point3[0], point1[1], newPoint_orientation/4, newPoint_orientation%4]
verify11 = myVerifyCompatibility(oppositeOrientation1, oppositeOrientation2, point1, newPoint1, gap)
verify31 = myVerifyCompatibility(oppositeOrientation3, oppositeOrientation2, point3, newPoint1, gap)
verify12 = myVerifyCompatibility(oppositeOrientation1, oppositeOrientation2, point1, newPoint2, gap)
verify32 = myVerifyCompatibility(oppositeOrientation3, oppositeOrientation2, point3, newPoint2, gap)
if abs(newPoint1[0] - point2[0]) > gap and abs(newPoint1[1] - point2[1]) > gap and verify11 and verify31:
if newPoint_orientation not in augmented_points:
augmented_points[newPoint_orientation] = []
print('case1', newPoint1, point1, point2, point3, abs(newPoint1[0] - point2[0]), abs(newPoint1[1]-point2[1]))
augmented_points[newPoint_orientation].append(((newPoint1[0], newPoint1[1]) ,(newPoint1[0]-gap, newPoint1[1]-gap), (newPoint1[0]+gap,newPoint1[1]+gap), True))
pass
elif verify12 and verify32:
if newPoint_orientation not in augmented_points:
augmented_points[newPoint_orientation] = []
pass
print('case2', newPoint2, point1, point2, point3, abs(newPoint2[0] - point2[0]), abs(newPoint2[1]-point2[1]))
augmented_points[newPoint_orientation].append(((newPoint2[0], newPoint2[1]) ,(newPoint2[0]-gap,newPoint2[1]-gap), (newPoint2[0]+gap,newPoint2[1]+gap), True))
pass
pass
pass
continue
continue
continue
continue
continue
continue
pass
return augmented_points
def myVerifyCompatibility(orients1, orients2, pt1, pt2, gap):
verification_set = orients1 & orients2
passed_verification = False
for v in verification_set:
if v == 0:
if pt2[1] - pt1[1] > 0 and abs(pt1[0] - pt2[0]) < gap:
passed_verification = True
if v == 1:
if pt2[0] - pt1[0] < 0 and abs(pt1[1] - pt2[1]) < gap:
passed_verification = True
pass
if v == 2:
if pt2[1] - pt1[1] < 0 and abs(pt1[0] - pt2[0]) < gap:
passed_verification = True
pass
if v == 3:
if pt2[0] - pt1[0] > 0 and abs(pt1[1] - pt2[1]) < gap:
passed_verification = True
pass
return passed_verification
def augmentPoints(points, decreasingTypes = [2], increasingTypes = [1]):
orientationMap = {}
for pointType, orientationOrientations in enumerate(POINT_ORIENTATIONS):
for orientation, orientations in enumerate(orientationOrientations):
orientationMap[orientations] = orientation
continue
continue
newPoints = []
for pointIndex, point in enumerate(points):
if point[2] not in decreasingTypes:
continue
orientations = POINT_ORIENTATIONS[point[2]][point[3]]
for i in xrange(len(orientations)):
newOrientations = list(orientations)
newOrientations.remove(orientations[i])
newOrientations = tuple(newOrientations)
if not newOrientations in orientationMap:
continue
newOrientation = orientationMap[newOrientations]
newPoints.append([point[0], point[1], point[2] - 1, newOrientation])
continue
continue
for pointIndex, point in enumerate(points):
if point[2] not in increasingTypes:
continue
orientations = POINT_ORIENTATIONS[point[2]][point[3]]
for orientation in xrange(4):
if orientation in orientations:
continue
oppositeOrientation = (orientation + 2) % 4
ranges = copy.deepcopy(ORIENTATION_RANGES[orientation])
lineDim = -1
if orientation == 0 or orientation == 2:
lineDim = 1
else:
lineDim = 0
pass
deltas = [0, 0]
if lineDim == 1:
deltas[0] = gap
else:
deltas[1] = gap
pass
for c in xrange(2):
ranges[c] = min(ranges[c], point[c] - deltas[c])
ranges[c + 2] = max(ranges[c + 2], point[c] + deltas[c])
continue
hasNeighbor = False
for neighborPointIndex, neighborPoint in enumerate(points):
if neighborPointIndex == pointIndex:
continue
neighborOrientations = POINT_ORIENTATIONS[neighborPoint[2]][neighborPoint[3]]
if oppositeOrientation not in neighborOrientations:
continue
inRange = True
for c in xrange(2):
if neighborPoint[c] < ranges[c] or neighborPoint[c] > ranges[c + 2]:
inRange = False
break
continue
if not inRange or abs(neighborPoint[lineDim] - point[lineDim]) < max(abs(neighborPoint[1 - lineDim] - point[1 - lineDim]), 1):
continue
hasNeighbor = True
break
if not hasNeighbor:
continue
newOrientations = list(orientations)
newOrientations.append(orientation)
newOrientations = tuple(newOrientations)
if not newOrientations in orientationMap:
continue
newOrientation = orientationMap[newOrientations]
newPoints.append([point[0], point[1], point[2] + 1, newOrientation])
continue
continue
return points + newPoints
def filterWalls(wallPoints, wallLines):
orientationMap = {}
for pointType, orientationOrientations in enumerate(POINT_ORIENTATIONS):
for orientation, orientations in enumerate(orientationOrientations):
orientationMap[orientations] = orientation
continue
continue
#print(POINT_ORIENTATIONS)
while True:
pointOrientationNeighborsMap = {}
for line in wallLines:
lineDim = calcLineDim(wallPoints, line)
for c, pointIndex in enumerate(line):
if lineDim == 0:
if c == 0:
orientation = 1
else:
orientation = 3
else:
if c == 0:
orientation = 2
else:
orientation = 0
pass
pass
if pointIndex not in pointOrientationNeighborsMap:
pointOrientationNeighborsMap[pointIndex] = {}
pass
if orientation not in pointOrientationNeighborsMap[pointIndex]:
pointOrientationNeighborsMap[pointIndex][orientation] = []
pass
pointOrientationNeighborsMap[pointIndex][orientation].append(line[1 - c])
continue
continue
invalidPointMask = {}
for pointIndex, point in enumerate(wallPoints):
if pointIndex not in pointOrientationNeighborsMap:
invalidPointMask[pointIndex] = True
continue
orientationNeighborMap = pointOrientationNeighborsMap[pointIndex]
orientations = POINT_ORIENTATIONS[point[2]][point[3]]
if len(orientationNeighborMap) < len(orientations):
if len(orientationNeighborMap) >= 2 and tuple(orientationNeighborMap.keys()) in orientationMap:
newOrientation = orientationMap[tuple(orientationNeighborMap.keys())]
wallPoints[pointIndex][2] = len(orientationNeighborMap) - 1
wallPoints[pointIndex][3] = newOrientation
#print(orientationNeighborMap)
#print('new', len(orientationNeighborMap), newOrientation)
continue
invalidPointMask[pointIndex] = True