forked from vt-vl-lab/3d-photo-inpainting
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mesh.py
2296 lines (2182 loc) · 134 KB
/
mesh.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
import os
import numpy as np
try:
import cynetworkx as netx
except ImportError:
import networkx as netx
import matplotlib.pyplot as plt
from functools import partial
from vispy import scene, io
from vispy.scene import visuals
from vispy.visuals.filters import Alpha
import cv2
from moviepy.editor import ImageSequenceClip
from skimage.transform import resize
import time
import copy
import torch
import os
from utils import path_planning, open_small_mask, clean_far_edge, refine_depth_around_edge
from utils import refine_color_around_edge, filter_irrelevant_edge_new, require_depth_edge, clean_far_edge_new
from utils import create_placeholder, refresh_node, find_largest_rect
from mesh_tools import get_depth_from_maps, get_map_from_ccs, get_edge_from_nodes, get_depth_from_nodes, get_rgb_from_nodes, crop_maps_by_size, convert2tensor, recursive_add_edge, update_info, filter_edge, relabel_node, depth_inpainting
from mesh_tools import refresh_bord_depth, enlarge_border, fill_dummy_bord, extrapolate, fill_missing_node, incomplete_node, get_valid_size, dilate_valid_size, size_operation
import transforms3d
import random
from functools import reduce
def create_mesh(depth, image, int_mtx, config):
H, W, C = image.shape
ext_H, ext_W = H + 2 * config['extrapolation_thickness'], W + 2 * config['extrapolation_thickness']
LDI = netx.Graph(H=ext_H, W=ext_W, noext_H=H, noext_W=W, cam_param=int_mtx)
xy2depth = {}
int_mtx_pix = int_mtx * np.array([[W], [H], [1.]])
LDI.graph['cam_param_pix'], LDI.graph['cam_param_pix_inv'] = int_mtx_pix, np.linalg.inv(int_mtx_pix)
disp = 1. / (-depth)
LDI.graph['hoffset'], LDI.graph['woffset'] = config['extrapolation_thickness'], config['extrapolation_thickness']
LDI.graph['bord_up'], LDI.graph['bord_down'] = LDI.graph['hoffset'] + 0, LDI.graph['hoffset'] + H
LDI.graph['bord_left'], LDI.graph['bord_right'] = LDI.graph['woffset'] + 0, LDI.graph['woffset'] + W
for idx in range(H):
for idy in range(W):
x, y = idx + LDI.graph['hoffset'], idy + LDI.graph['woffset']
LDI.add_node((x, y, -depth[idx, idy]),
color=image[idx, idy],
disp=disp[idx, idy],
synthesis=False,
cc_id=set())
xy2depth[(x, y)] = [-depth[idx, idy]]
for x, y, d in LDI.nodes:
two_nes = [ne for ne in [(x+1, y), (x, y+1)] if ne[0] < LDI.graph['bord_down'] and ne[1] < LDI.graph['bord_right']]
[LDI.add_edge((ne[0], ne[1], xy2depth[ne][0]), (x, y, d)) for ne in two_nes]
LDI = calculate_fov(LDI)
image = np.pad(image,
pad_width=((config['extrapolation_thickness'], config['extrapolation_thickness']),
(config['extrapolation_thickness'], config['extrapolation_thickness']),
(0, 0)),
mode='constant')
depth = np.pad(depth,
pad_width=((config['extrapolation_thickness'], config['extrapolation_thickness']),
(config['extrapolation_thickness'], config['extrapolation_thickness'])),
mode='constant')
return LDI, xy2depth, image, depth
def tear_edges(mesh, threshold = 0.00025, xy2depth=None):
remove_edge_list = []
remove_horizon, remove_vertical = np.zeros((2, mesh.graph['H'], mesh.graph['W']))
mesh_nodes = mesh.nodes
for edge in mesh.edges:
if abs(mesh_nodes[edge[0]]['disp'] - mesh_nodes[edge[1]]['disp']) > threshold:
remove_edge_list.append((edge[0], edge[1]))
near, far = edge if abs(edge[0][2]) < abs(edge[1][2]) else edge[::-1]
mesh_nodes[far]['near'] = [] if mesh_nodes[far].get('near') is None else mesh_nodes[far]['near'].append(near)
mesh_nodes[near]['far'] = [] if mesh_nodes[near].get('far') is None else mesh_nodes[near]['far'].append(far)
if near[0] == far[0]:
remove_horizon[near[0], np.minimum(near[1], far[1])] = 1
elif near[1] == far[1]:
remove_vertical[np.minimum(near[0], far[0]), near[1]] = 1
mesh.remove_edges_from(remove_edge_list)
remove_edge_list = []
dang_horizon = np.where(np.roll(remove_horizon, 1, 0) + np.roll(remove_horizon, -1, 0) - remove_horizon == 2)
dang_vertical = np.where(np.roll(remove_vertical, 1, 1) + np.roll(remove_vertical, -1, 1) - remove_vertical == 2)
horizon_condition = lambda x, y: mesh.graph['bord_up'] + 1 <= x < mesh.graph['bord_down'] - 1
vertical_condition = lambda x, y: mesh.graph['bord_left'] + 1 <= y < mesh.graph['bord_right'] - 1
prjto3d = lambda x, y: (x, y, xy2depth[(x, y)][0])
node_existence = lambda x, y: mesh.has_node(prjto3d(x, y))
for x, y in zip(dang_horizon[0], dang_horizon[1]):
if horizon_condition(x, y) and node_existence(x, y) and node_existence(x, y+1):
remove_edge_list.append((prjto3d(x, y), prjto3d(x, y+1)))
for x, y in zip(dang_vertical[0], dang_vertical[1]):
if vertical_condition(x, y) and node_existence(x, y) and node_existence(x+1, y):
remove_edge_list.append((prjto3d(x, y), prjto3d(x+1, y)))
mesh.remove_edges_from(remove_edge_list)
return mesh
def calculate_fov(mesh):
k = mesh.graph['cam_param']
mesh.graph['hFov'] = 2 * np.arctan(1. / (2*k[0, 0]))
mesh.graph['vFov'] = 2 * np.arctan(1. / (2*k[1, 1]))
mesh.graph['aspect'] = mesh.graph['noext_H'] / mesh.graph['noext_W']
return mesh
def calculate_fov_FB(mesh):
mesh.graph['aspect'] = mesh.graph['H'] / mesh.graph['W']
if mesh.graph['H'] > mesh.graph['W']:
mesh.graph['hFov'] = 0.508015513
half_short = np.tan(mesh.graph['hFov']/2.0)
half_long = half_short * mesh.graph['aspect']
mesh.graph['vFov'] = 2.0 * np.arctan(half_long)
else:
mesh.graph['vFov'] = 0.508015513
half_short = np.tan(mesh.graph['vFov']/2.0)
half_long = half_short / mesh.graph['aspect']
mesh.graph['hFov'] = 2.0 * np.arctan(half_long)
return mesh
def reproject_3d_int_detail(sx, sy, z, k_00, k_02, k_11, k_12, w_offset, h_offset):
abs_z = abs(z)
return [abs_z * ((sy+0.5-w_offset) * k_00 + k_02), abs_z * ((sx+0.5-h_offset) * k_11 + k_12), abs_z]
def reproject_3d_int_detail_FB(sx, sy, z, w_offset, h_offset, mesh):
if mesh.graph.get('tan_hFov') is None:
mesh.graph['tan_hFov'] = np.tan(mesh.graph['hFov'] / 2.)
if mesh.graph.get('tan_vFov') is None:
mesh.graph['tan_vFov'] = np.tan(mesh.graph['vFov'] / 2.)
ray = np.array([(-1. + 2. * ((sy+0.5-w_offset)/(mesh.graph['W'] - 1))) * mesh.graph['tan_hFov'],
(1. - 2. * (sx+0.5-h_offset)/(mesh.graph['H'] - 1)) * mesh.graph['tan_vFov'],
-1])
point_3d = ray * np.abs(z)
return point_3d
def reproject_3d_int(sx, sy, z, mesh):
k = mesh.graph['cam_param_pix_inv'].copy()
if k[0, 2] > 0:
k = np.linalg.inv(k)
ray = np.dot(k, np.array([sy-mesh.graph['woffset'], sx-mesh.graph['hoffset'], 1]).reshape(3, 1))
point_3d = ray * np.abs(z)
point_3d = point_3d.flatten()
return point_3d
def generate_init_node(mesh, config, min_node_in_cc):
mesh_nodes = mesh.nodes
info_on_pix = {}
ccs = sorted(netx.connected_components(mesh), key = len, reverse=True)
remove_nodes = []
for cc in ccs:
remove_flag = True if len(cc) < min_node_in_cc else False
if remove_flag is False:
for (nx, ny, nd) in cc:
info_on_pix[(nx, ny)] = [{'depth':nd,
'color':mesh_nodes[(nx, ny, nd)]['color'],
'synthesis':False,
'disp':mesh_nodes[(nx, ny, nd)]['disp']}]
else:
[remove_nodes.append((nx, ny, nd)) for (nx, ny, nd) in cc]
for node in remove_nodes:
far_nodes = [] if mesh_nodes[node].get('far') is None else mesh_nodes[node]['far']
for far_node in far_nodes:
if mesh.has_node(far_node) and mesh_nodes[far_node].get('near') is not None and node in mesh_nodes[far_node]['near']:
mesh_nodes[far_node]['near'].remove(node)
near_nodes = [] if mesh_nodes[node].get('near') is None else mesh_nodes[node]['near']
for near_node in near_nodes:
if mesh.has_node(near_node) and mesh_nodes[near_node].get('far') is not None and node in mesh_nodes[near_node]['far']:
mesh_nodes[near_node]['far'].remove(node)
[mesh.remove_node(node) for node in remove_nodes]
return mesh, info_on_pix
def get_neighbors(mesh, node):
return [*mesh.neighbors(node)]
def generate_face(mesh, info_on_pix, config):
H, W = mesh.graph['H'], mesh.graph['W']
str_faces = []
num_node = len(mesh.nodes)
ply_flag = config.get('save_ply')
def out_fmt(input, cur_id_b, cur_id_self, cur_id_a, ply_flag):
if ply_flag is True:
input.append(' '.join(['3', cur_id_b, cur_id_self, cur_id_a]) + '\n')
else:
input.append([cur_id_b, cur_id_self, cur_id_a])
mesh_nodes = mesh.nodes
for node in mesh_nodes:
cur_id_self = mesh_nodes[node]['cur_id']
ne_nodes = get_neighbors(mesh, node)
four_dir_nes = {'up': [], 'left': [],
'down': [], 'right': []}
for ne_node in ne_nodes:
store_tuple = [ne_node, mesh_nodes[ne_node]['cur_id']]
if ne_node[0] == node[0]:
if ne_node[1] == ne_node[1] - 1:
four_dir_nes['left'].append(store_tuple)
else:
four_dir_nes['right'].append(store_tuple)
else:
if ne_node[0] == ne_node[0] - 1:
four_dir_nes['up'].append(store_tuple)
else:
four_dir_nes['down'].append(store_tuple)
for node_a, cur_id_a in four_dir_nes['up']:
for node_b, cur_id_b in four_dir_nes['right']:
out_fmt(str_faces, cur_id_b, cur_id_self, cur_id_a, ply_flag)
for node_a, cur_id_a in four_dir_nes['right']:
for node_b, cur_id_b in four_dir_nes['down']:
out_fmt(str_faces, cur_id_b, cur_id_self, cur_id_a, ply_flag)
for node_a, cur_id_a in four_dir_nes['down']:
for node_b, cur_id_b in four_dir_nes['left']:
out_fmt(str_faces, cur_id_b, cur_id_self, cur_id_a, ply_flag)
for node_a, cur_id_a in four_dir_nes['left']:
for node_b, cur_id_b in four_dir_nes['up']:
out_fmt(str_faces, cur_id_b, cur_id_self, cur_id_a, ply_flag)
return str_faces
def reassign_floating_island(mesh, info_on_pix, image, depth):
H, W = mesh.graph['H'], mesh.graph['W'],
mesh_nodes = mesh.nodes
bord_up, bord_down = mesh.graph['bord_up'], mesh.graph['bord_down']
bord_left, bord_right = mesh.graph['bord_left'], mesh.graph['bord_right']
W = mesh.graph['W']
lost_map = np.zeros((H, W))
'''
(5) is_inside(x, y, xmin, xmax, ymin, ymax) : Check if a pixel(x, y) is inside the border.
(6) get_cross_nes(x, y) : Get the four cross neighbors of pixel(x, y).
'''
key_exist = lambda d, k: k in d
is_inside = lambda x, y, xmin, xmax, ymin, ymax: xmin <= x < xmax and ymin <= y < ymax
get_cross_nes = lambda x, y: [(x + 1, y), (x - 1, y), (x, y - 1), (x, y + 1)]
'''
(A) Highlight the pixels on isolated floating island.
(B) Number those isolated floating islands with connected component analysis.
(C) For each isolated island:
(1) Find its longest surrounded depth edge.
(2) Propogate depth from that depth edge to the pixels on the isolated island.
(3) Build the connection between the depth edge and that isolated island.
'''
for x in range(H):
for y in range(W):
if is_inside(x, y, bord_up, bord_down, bord_left, bord_right) and not(key_exist(info_on_pix, (x, y))):
lost_map[x, y] = 1
_, label_lost_map = cv2.connectedComponents(lost_map.astype(np.uint8), connectivity=4)
mask = np.zeros((H, W))
mask[bord_up:bord_down, bord_left:bord_right] = 1
label_lost_map = (label_lost_map * mask).astype(np.int)
for i in range(1, label_lost_map.max()+1):
lost_xs, lost_ys = np.where(label_lost_map == i)
surr_edge_ids = {}
for lost_x, lost_y in zip(lost_xs, lost_ys):
if (lost_x, lost_y) == (295, 389) or (lost_x, lost_y) == (296, 389):
import pdb; pdb.set_trace()
for ne in get_cross_nes(lost_x, lost_y):
if key_exist(info_on_pix, ne):
for info in info_on_pix[ne]:
ne_node = (ne[0], ne[1], info['depth'])
if key_exist(mesh_nodes[ne_node], 'edge_id'):
edge_id = mesh_nodes[ne_node]['edge_id']
surr_edge_ids[edge_id] = surr_edge_ids[edge_id] + [ne_node] if \
key_exist(surr_edge_ids, edge_id) else [ne_node]
if len(surr_edge_ids) == 0:
continue
edge_id, edge_nodes = sorted([*surr_edge_ids.items()], key=lambda x: len(x[1]), reverse=True)[0]
edge_depth_map = np.zeros((H, W))
for node in edge_nodes:
edge_depth_map[node[0], node[1]] = node[2]
lost_xs, lost_ys = np.where(label_lost_map == i)
while lost_xs.shape[0] > 0:
lost_xs, lost_ys = np.where(label_lost_map == i)
for lost_x, lost_y in zip(lost_xs, lost_ys):
propagated_depth = []
real_nes = []
for ne in get_cross_nes(lost_x, lost_y):
if not(is_inside(ne[0], ne[1], bord_up, bord_down, bord_left, bord_right)) or \
edge_depth_map[ne[0], ne[1]] == 0:
continue
propagated_depth.append(edge_depth_map[ne[0], ne[1]])
real_nes.append(ne)
if len(real_nes) == 0:
continue
reassign_depth = np.mean(propagated_depth)
label_lost_map[lost_x, lost_y] = 0
edge_depth_map[lost_x, lost_y] = reassign_depth
depth[lost_x, lost_y] = -reassign_depth
mesh.add_node((lost_x, lost_y, reassign_depth), color=image[lost_x, lost_y],
synthesis=False,
disp=1./reassign_depth,
cc_id=set())
info_on_pix[(lost_x, lost_y)] = [{'depth':reassign_depth,
'color':image[lost_x, lost_y],
'synthesis':False,
'disp':1./reassign_depth}]
new_connections = [((lost_x, lost_y, reassign_depth),
(ne[0], ne[1], edge_depth_map[ne[0], ne[1]])) for ne in real_nes]
mesh.add_edges_from(new_connections)
return mesh, info_on_pix, depth
def remove_node_feat(mesh, *feats):
mesh_nodes = mesh.nodes
for node in mesh_nodes:
for feat in feats:
mesh_nodes[node][feat] = None
return mesh
def update_status(mesh, info_on_pix, depth=None):
'''
(2) clear_node_feat(G, *fts) : Clear all the node feature on graph G.
(6) get_cross_nes(x, y) : Get the four cross neighbors of pixel(x, y).
'''
key_exist = lambda d, k: d.get(k) is not None
is_inside = lambda x, y, xmin, xmax, ymin, ymax: xmin <= x < xmax and ymin <= y < ymax
get_cross_nes = lambda x, y: [(x + 1, y), (x - 1, y), (x, y - 1), (x, y + 1)]
append_element = lambda d, k, x: d[k] + [x] if key_exist(d, k) else [x]
def clear_node_feat(G, fts):
le_nodes = G.nodes
for k in le_nodes:
v = le_nodes[k]
for ft in fts:
if ft in v:
v[ft] = None
clear_node_feat(mesh, ['edge_id', 'far', 'near'])
bord_up, bord_down = mesh.graph['bord_up'], mesh.graph['bord_down']
bord_left, bord_right = mesh.graph['bord_left'], mesh.graph['bord_right']
le_nodes = mesh.nodes
for node_key in le_nodes:
if mesh.neighbors(node_key).__length_hint__() == 4:
continue
four_nes = [xx for xx in get_cross_nes(node_key[0], node_key[1]) if
is_inside(xx[0], xx[1], bord_up, bord_down, bord_left, bord_right) and
xx in info_on_pix]
[four_nes.remove((ne_node[0], ne_node[1])) for ne_node in mesh.neighbors(node_key)]
for ne in four_nes:
for info in info_on_pix[ne]:
assert mesh.has_node((ne[0], ne[1], info['depth'])), "No node_key"
ind_node = le_nodes[node_key]
if abs(node_key[2]) > abs(info['depth']):
ind_node['near'] = append_element(ind_node, 'near', (ne[0], ne[1], info['depth']))
else:
ind_node['far'] = append_element(ind_node, 'far', (ne[0], ne[1], info['depth']))
if depth is not None:
for key, value in info_on_pix.items():
if depth[key[0], key[1]] != abs(value[0]['depth']):
value[0]['disp'] = 1. / value[0]['depth']
depth[key[0], key[1]] = abs(value[0]['depth'])
return mesh, depth, info_on_pix
else:
return mesh
def group_edges(LDI, config, image, remove_conflict_ordinal, spdb=False):
'''
(1) add_new_node(G, node) : add "node" to graph "G"
(2) add_new_edge(G, node_a, node_b) : add edge "node_a--node_b" to graph "G"
(3) exceed_thre(x, y, thre) : Check if difference between "x" and "y" exceed threshold "thre"
(4) key_exist(d, k) : Check if key "k' exists in dictionary "d"
(5) comm_opp_bg(G, x, y) : Check if node "x" and "y" in graph "G" treat the same opposite node as background
(6) comm_opp_fg(G, x, y) : Check if node "x" and "y" in graph "G" treat the same opposite node as foreground
'''
add_new_node = lambda G, node: None if G.has_node(node) else G.add_node(node)
add_new_edge = lambda G, node_a, node_b: None if G.has_edge(node_a, node_b) else G.add_edge(node_a, node_b)
exceed_thre = lambda x, y, thre: (abs(x) - abs(y)) > thre
key_exist = lambda d, k: d.get(k) is not None
comm_opp_bg = lambda G, x, y: key_exist(G.nodes[x], 'far') and key_exist(G.nodes[y], 'far') and \
not(set(G.nodes[x]['far']).isdisjoint(set(G.nodes[y]['far'])))
comm_opp_fg = lambda G, x, y: key_exist(G.nodes[x], 'near') and key_exist(G.nodes[y], 'near') and \
not(set(G.nodes[x]['near']).isdisjoint(set(G.nodes[y]['near'])))
discont_graph = netx.Graph()
'''
(A) Skip the pixel at image boundary, we don't want to deal with them.
(B) Identify discontinuity by the number of its neighbor(degree).
If the degree < 4(up/right/buttom/left). We will go through following steps:
(1) Add the discontinuity pixel "node" to graph "discont_graph".
(2) Find "node"'s cross neighbor(up/right/buttom/left) "ne_node".
- If the cross neighbor "ne_node" is a discontinuity pixel(degree("ne_node") < 4),
(a) add it to graph "discont_graph" and build the connection between "ne_node" and "node".
(b) label its cross neighbor as invalid pixels "inval_diag_candi" to avoid building
connection between original discontinuity pixel "node" and "inval_diag_candi".
- Otherwise, find "ne_node"'s cross neighbors, called diagonal candidate "diag_candi".
- The "diag_candi" is diagonal to the original discontinuity pixel "node".
- If "diag_candi" exists, go to step(3).
(3) A diagonal candidate "diag_candi" will be :
- added to the "discont_graph" if its degree < 4.
- connected to the original discontinuity pixel "node" if it satisfied either
one of following criterion:
(a) the difference of disparity between "diag_candi" and "node" is smaller than default threshold.
(b) the "diag_candi" and "node" face the same opposite pixel. (See. function "tear_edges")
(c) Both of "diag_candi" and "node" must_connect to each other. (See. function "combine_end_node")
(C) Aggregate each connected part in "discont_graph" into "discont_ccs" (A.K.A. depth edge).
'''
for node in LDI.nodes:
if not(LDI.graph['bord_up'] + 1 <= node[0] <= LDI.graph['bord_down'] - 2 and \
LDI.graph['bord_left'] + 1 <= node[1] <= LDI.graph['bord_right'] - 2):
continue
neighbors = [*LDI.neighbors(node)]
if len(neighbors) < 4:
add_new_node(discont_graph, node)
diag_candi_anc, inval_diag_candi, discont_nes = set(), set(), set()
for ne_node in neighbors:
if len([*LDI.neighbors(ne_node)]) < 4:
add_new_node(discont_graph, ne_node)
add_new_edge(discont_graph, ne_node, node)
discont_nes.add(ne_node)
else:
diag_candi_anc.add(ne_node)
inval_diag_candi = set([inval_diagonal for ne_node in discont_nes for inval_diagonal in LDI.neighbors(ne_node) if \
abs(inval_diagonal[0] - node[0]) < 2 and abs(inval_diagonal[1] - node[1]) < 2])
for ne_node in diag_candi_anc:
if ne_node[0] == node[0]:
diagonal_xys = [[ne_node[0] + 1, ne_node[1]], [ne_node[0] - 1, ne_node[1]]]
elif ne_node[1] == node[1]:
diagonal_xys = [[ne_node[0], ne_node[1] + 1], [ne_node[0], ne_node[1] - 1]]
for diag_candi in LDI.neighbors(ne_node):
if [diag_candi[0], diag_candi[1]] in diagonal_xys and LDI.degree(diag_candi) < 4:
if diag_candi not in inval_diag_candi:
if not exceed_thre(1./node[2], 1./diag_candi[2], config['depth_threshold']) or \
(comm_opp_bg(LDI, diag_candi, node) and comm_opp_fg(LDI, diag_candi, node)):
add_new_node(discont_graph, diag_candi)
add_new_edge(discont_graph, diag_candi, node)
if key_exist(LDI.nodes[diag_candi], 'must_connect') and node in LDI.nodes[diag_candi]['must_connect'] and \
key_exist(LDI.nodes[node], 'must_connect') and diag_candi in LDI.nodes[node]['must_connect']:
add_new_node(discont_graph, diag_candi)
add_new_edge(discont_graph, diag_candi, node)
if spdb == True:
import pdb; pdb.set_trace()
discont_ccs = [*netx.connected_components(discont_graph)]
'''
In some corner case, a depth edge "discont_cc" will contain both
foreground(FG) and background(BG) pixels. This violate the assumption that
a depth edge can only composite by one type of pixel(FG or BG).
We need to further divide this depth edge into several sub-part so that the
assumption is satisfied.
(A) A depth edge is invalid if both of its "far_flag"(BG) and
"near_flag"(FG) are True.
(B) If the depth edge is invalid, we need to do:
(1) Find the role("oridinal") of each pixel on the depth edge.
"-1" --> Its opposite pixels has smaller depth(near) than it.
It is a backgorund pixel.
"+1" --> Its opposite pixels has larger depth(far) than it.
It is a foregorund pixel.
"0" --> Some of opposite pixels has larger depth(far) than it,
and some has smaller pixel than it.
It is an ambiguous pixel.
(2) For each pixel "discont_node", check if its neigbhors' roles are consistent.
- If not, break the connection between the neighbor "ne_node" that has a role
different from "discont_node".
- If yes, remove all the role that are inconsistent to its neighbors "ne_node".
(3) Connected component analysis to re-identified those divided depth edge.
(C) Aggregate each connected part in "discont_graph" into "discont_ccs" (A.K.A. depth edge).
'''
if remove_conflict_ordinal:
new_discont_ccs = []
num_new_cc = 0
for edge_id, discont_cc in enumerate(discont_ccs):
near_flag = False
far_flag = False
for discont_node in discont_cc:
near_flag = True if key_exist(LDI.nodes[discont_node], 'far') else near_flag
far_flag = True if key_exist(LDI.nodes[discont_node], 'near') else far_flag
if far_flag and near_flag:
break
if far_flag and near_flag:
for discont_node in discont_cc:
discont_graph.nodes[discont_node]['ordinal'] = \
np.array([key_exist(LDI.nodes[discont_node], 'far'),
key_exist(LDI.nodes[discont_node], 'near')]) * \
np.array([-1, 1])
discont_graph.nodes[discont_node]['ordinal'] = \
np.sum(discont_graph.nodes[discont_node]['ordinal'])
remove_nodes, remove_edges = [], []
for discont_node in discont_cc:
ordinal_relation = np.sum([discont_graph.nodes[xx]['ordinal'] \
for xx in discont_graph.neighbors(discont_node)])
near_side = discont_graph.nodes[discont_node]['ordinal'] <= 0
if abs(ordinal_relation) < len([*discont_graph.neighbors(discont_node)]):
remove_nodes.append(discont_node)
for ne_node in discont_graph.neighbors(discont_node):
remove_flag = (near_side and not(key_exist(LDI.nodes[ne_node], 'far'))) or \
(not near_side and not(key_exist(LDI.nodes[ne_node], 'near')))
remove_edges += [(discont_node, ne_node)] if remove_flag else []
else:
if near_side and key_exist(LDI.nodes[discont_node], 'near'):
LDI.nodes[discont_node].pop('near')
elif not(near_side) and key_exist(LDI.nodes[discont_node], 'far'):
LDI.nodes[discont_node].pop('far')
discont_graph.remove_edges_from(remove_edges)
sub_mesh = discont_graph.subgraph(list(discont_cc)).copy()
sub_discont_ccs = [*netx.connected_components(sub_mesh)]
is_redun_near = lambda xx: len(xx) == 1 and xx[0] in remove_nodes and key_exist(LDI.nodes[xx[0]], 'far')
for sub_discont_cc in sub_discont_ccs:
if is_redun_near(list(sub_discont_cc)):
LDI.nodes[list(sub_discont_cc)[0]].pop('far')
new_discont_ccs.append(sub_discont_cc)
else:
new_discont_ccs.append(discont_cc)
discont_ccs = new_discont_ccs
new_discont_ccs = None
if spdb == True:
import pdb; pdb.set_trace()
for edge_id, edge_cc in enumerate(discont_ccs):
for node in edge_cc:
LDI.nodes[node]['edge_id'] = edge_id
return discont_ccs, LDI, discont_graph
def combine_end_node(mesh, edge_mesh, edge_ccs, depth):
import collections
mesh_nodes = mesh.nodes
connect_dict = dict()
for valid_edge_id, valid_edge_cc in enumerate(edge_ccs):
connect_info = []
for valid_edge_node in valid_edge_cc:
single_connect = set()
for ne_node in mesh.neighbors(valid_edge_node):
if mesh_nodes[ne_node].get('far') is not None:
for fn in mesh_nodes[ne_node].get('far'):
if mesh.has_node(fn) and mesh_nodes[fn].get('edge_id') is not None:
single_connect.add(mesh_nodes[fn]['edge_id'])
if mesh_nodes[ne_node].get('near') is not None:
for fn in mesh_nodes[ne_node].get('near'):
if mesh.has_node(fn) and mesh_nodes[fn].get('edge_id') is not None:
single_connect.add(mesh_nodes[fn]['edge_id'])
connect_info.extend([*single_connect])
connect_dict[valid_edge_id] = collections.Counter(connect_info)
end_maps = np.zeros((mesh.graph['H'], mesh.graph['W']))
edge_maps = np.zeros((mesh.graph['H'], mesh.graph['W'])) - 1
for valid_edge_id, valid_edge_cc in enumerate(edge_ccs):
for valid_edge_node in valid_edge_cc:
edge_maps[valid_edge_node[0], valid_edge_node[1]] = valid_edge_id
if len([*edge_mesh.neighbors(valid_edge_node)]) == 1:
num_ne = 1
if num_ne == 1:
end_maps[valid_edge_node[0], valid_edge_node[1]] = valid_edge_node[2]
nxs, nys = np.where(end_maps != 0)
invalid_nodes = set()
for nx, ny in zip(nxs, nys):
if mesh.has_node((nx, ny, end_maps[nx, ny])) is False:
invalid_nodes.add((nx, ny))
continue
four_nes = [xx for xx in [(nx - 1, ny), (nx + 1, ny), (nx, ny - 1), (nx, ny + 1)] \
if 0 <= xx[0] < mesh.graph['H'] and 0 <= xx[1] < mesh.graph['W'] and \
end_maps[xx[0], xx[1]] != 0]
mesh_nes = [*mesh.neighbors((nx, ny, end_maps[nx, ny]))]
remove_num = 0
for fne in four_nes:
if (fne[0], fne[1], end_maps[fne[0], fne[1]]) in mesh_nes:
remove_num += 1
if remove_num == len(four_nes):
invalid_nodes.add((nx, ny))
for invalid_node in invalid_nodes:
end_maps[invalid_node[0], invalid_node[1]] = 0
nxs, nys = np.where(end_maps != 0)
invalid_nodes = set()
for nx, ny in zip(nxs, nys):
if mesh_nodes[(nx, ny, end_maps[nx, ny])].get('edge_id') is None:
continue
else:
self_id = mesh_nodes[(nx, ny, end_maps[nx, ny])].get('edge_id')
self_connect = connect_dict[self_id] if connect_dict.get(self_id) is not None else dict()
four_nes = [xx for xx in [(nx - 1, ny), (nx + 1, ny), (nx, ny - 1), (nx, ny + 1)] \
if 0 <= xx[0] < mesh.graph['H'] and 0 <= xx[1] < mesh.graph['W'] and \
end_maps[xx[0], xx[1]] != 0]
for fne in four_nes:
if mesh_nodes[(fne[0], fne[1], end_maps[fne[0], fne[1]])].get('edge_id') is None:
continue
else:
ne_id = mesh_nodes[(fne[0], fne[1], end_maps[fne[0], fne[1]])]['edge_id']
if self_connect.get(ne_id) is None or self_connect.get(ne_id) == 1:
continue
else:
invalid_nodes.add((nx, ny))
for invalid_node in invalid_nodes:
end_maps[invalid_node[0], invalid_node[1]] = 0
nxs, nys = np.where(end_maps != 0)
invalid_nodes = set()
for nx, ny in zip(nxs, nys):
four_nes = [xx for xx in [(nx - 1, ny), (nx + 1, ny), (nx, ny - 1), (nx, ny + 1)] \
if 0 <= xx[0] < mesh.graph['H'] and 0 <= xx[1] < mesh.graph['W'] and \
end_maps[xx[0], xx[1]] != 0]
for fne in four_nes:
if mesh.has_node((fne[0], fne[1], end_maps[fne[0], fne[1]])):
node_a, node_b = (fne[0], fne[1], end_maps[fne[0], fne[1]]), (nx, ny, end_maps[nx, ny])
mesh.add_edge(node_a, node_b)
mesh_nodes[node_b]['must_connect'] = set() if mesh_nodes[node_b].get('must_connect') is None else mesh_nodes[node_b]['must_connect']
mesh_nodes[node_b]['must_connect'].add(node_a)
mesh_nodes[node_b]['must_connect'] |= set([xx for xx in [*edge_mesh.neighbors(node_a)] if \
(xx[0] - node_b[0]) < 2 and (xx[1] - node_b[1]) < 2])
mesh_nodes[node_a]['must_connect'] = set() if mesh_nodes[node_a].get('must_connect') is None else mesh_nodes[node_a]['must_connect']
mesh_nodes[node_a]['must_connect'].add(node_b)
mesh_nodes[node_a]['must_connect'] |= set([xx for xx in [*edge_mesh.neighbors(node_b)] if \
(xx[0] - node_a[0]) < 2 and (xx[1] - node_a[1]) < 2])
invalid_nodes.add((nx, ny))
for invalid_node in invalid_nodes:
end_maps[invalid_node[0], invalid_node[1]] = 0
return mesh
def remove_redundant_edge(mesh, edge_mesh, edge_ccs, info_on_pix, config, redundant_number=1000, invalid=False, spdb=False):
point_to_amount = {}
point_to_id = {}
end_maps = np.zeros((mesh.graph['H'], mesh.graph['W'])) - 1
for valid_edge_id, valid_edge_cc in enumerate(edge_ccs):
for valid_edge_node in valid_edge_cc:
point_to_amount[valid_edge_node] = len(valid_edge_cc)
point_to_id[valid_edge_node] = valid_edge_id
if edge_mesh.has_node(valid_edge_node) is True:
if len([*edge_mesh.neighbors(valid_edge_node)]) == 1:
end_maps[valid_edge_node[0], valid_edge_node[1]] = valid_edge_id
nxs, nys = np.where(end_maps > -1)
point_to_adjoint = {}
for nx, ny in zip(nxs, nys):
adjoint_edges = set([end_maps[x, y] for x, y in [(nx + 1, ny), (nx - 1, ny), (nx, ny + 1), (nx, ny - 1)] if end_maps[x, y] != -1])
point_to_adjoint[end_maps[nx, ny]] = (point_to_adjoint[end_maps[nx, ny]] | adjoint_edges) if point_to_adjoint.get(end_maps[nx, ny]) is not None else adjoint_edges
valid_edge_ccs = filter_edge(mesh, edge_ccs, config, invalid=invalid)
edge_canvas = np.zeros((mesh.graph['H'], mesh.graph['W'])) - 1
for valid_edge_id, valid_edge_cc in enumerate(valid_edge_ccs):
for valid_edge_node in valid_edge_cc:
edge_canvas[valid_edge_node[0], valid_edge_node[1]] = valid_edge_id
if spdb is True:
plt.imshow(edge_canvas); plt.show()
import pdb; pdb.set_trace()
for valid_edge_id, valid_edge_cc in enumerate(valid_edge_ccs):
end_number = 0
four_end_number = 0
eight_end_number = 0
db_eight_end_number = 0
if len(valid_edge_cc) > redundant_number:
continue
for valid_edge_node in valid_edge_cc:
if len([*edge_mesh.neighbors(valid_edge_node)]) == 3:
break
elif len([*edge_mesh.neighbors(valid_edge_node)]) == 1:
hx, hy, hz = valid_edge_node
if invalid is False:
eight_nes = [(x, y) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1),
(hx + 1, hy + 1), (hx - 1, hy - 1), (hx - 1, hy + 1), (hx + 1, hy - 1)] \
if info_on_pix.get((x, y)) is not None and edge_canvas[x, y] != -1 and edge_canvas[x, y] != valid_edge_id]
if len(eight_nes) == 0:
end_number += 1
if invalid is True:
four_nes = []; eight_nes = []; db_eight_nes = []
four_nes = [(x, y) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1)] \
if info_on_pix.get((x, y)) is not None and edge_canvas[x, y] != -1 and edge_canvas[x, y] != valid_edge_id]
eight_nes = [(x, y) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1), \
(hx + 1, hy + 1), (hx - 1, hy - 1), (hx - 1, hy + 1), (hx + 1, hy - 1)] \
if info_on_pix.get((x, y)) is not None and edge_canvas[x, y] != -1 and edge_canvas[x, y] != valid_edge_id]
db_eight_nes = [(x, y) for x in range(hx - 2, hx + 3) for y in range(hy - 2, hy + 3) \
if info_on_pix.get((x, y)) is not None and edge_canvas[x, y] != -1 and edge_canvas[x, y] != valid_edge_id and (x, y) != (hx, hy)]
if len(four_nes) == 0 or len(eight_nes) == 0:
end_number += 1
if len(four_nes) == 0:
four_end_number += 1
if len(eight_nes) == 0:
eight_end_number += 1
if len(db_eight_nes) == 0:
db_eight_end_number += 1
elif len([*edge_mesh.neighbors(valid_edge_node)]) == 0:
hx, hy, hz = valid_edge_node
four_nes = [(x, y, info_on_pix[(x, y)][0]['depth']) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1)] \
if info_on_pix.get((x, y)) is not None and \
mesh.has_edge(valid_edge_node, (x, y, info_on_pix[(x, y)][0]['depth'])) is False]
for ne in four_nes:
try:
if invalid is True or (point_to_amount.get(ne) is None or point_to_amount[ne] < redundant_number) or \
point_to_id[ne] in point_to_adjoint.get(point_to_id[valid_edge_node], set()):
mesh.add_edge(valid_edge_node, ne)
except:
import pdb; pdb.set_trace()
if (invalid is not True and end_number >= 1) or (invalid is True and end_number >= 2 and eight_end_number >= 1 and db_eight_end_number >= 1):
for valid_edge_node in valid_edge_cc:
hx, hy, _ = valid_edge_node
four_nes = [(x, y, info_on_pix[(x, y)][0]['depth']) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1)] \
if info_on_pix.get((x, y)) is not None and \
mesh.has_edge(valid_edge_node, (x, y, info_on_pix[(x, y)][0]['depth'])) is False and \
(edge_canvas[x, y] == -1 or edge_canvas[x, y] == valid_edge_id)]
for ne in four_nes:
if invalid is True or (point_to_amount.get(ne) is None or point_to_amount[ne] < redundant_number) or \
point_to_id[ne] in point_to_adjoint.get(point_to_id[valid_edge_node], set()):
mesh.add_edge(valid_edge_node, ne)
return mesh
def judge_dangle(mark, mesh, node):
if not (1 <= node[0] < mesh.graph['H']-1) or not(1 <= node[1] < mesh.graph['W']-1):
return mark
mesh_neighbors = [*mesh.neighbors(node)]
mesh_neighbors = [xx for xx in mesh_neighbors if 0 < xx[0] < mesh.graph['H'] - 1 and 0 < xx[1] < mesh.graph['W'] - 1]
if len(mesh_neighbors) >= 3:
return mark
elif len(mesh_neighbors) <= 1:
mark[node[0], node[1]] = (len(mesh_neighbors) + 1)
else:
dan_ne_node_a = mesh_neighbors[0]
dan_ne_node_b = mesh_neighbors[1]
if abs(dan_ne_node_a[0] - dan_ne_node_b[0]) > 1 or \
abs(dan_ne_node_a[1] - dan_ne_node_b[1]) > 1:
mark[node[0], node[1]] = 3
return mark
def remove_dangling(mesh, edge_ccs, edge_mesh, info_on_pix, image, depth, config):
tmp_edge_ccs = copy.deepcopy(edge_ccs)
for edge_cc_id, valid_edge_cc in enumerate(tmp_edge_ccs):
if len(valid_edge_cc) > 1 or len(valid_edge_cc) == 0:
continue
single_edge_node = [*valid_edge_cc][0]
hx, hy, hz = single_edge_node
eight_nes = set([(x, y, info_on_pix[(x, y)][0]['depth']) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1),
(hx + 1, hy + 1), (hx - 1, hy - 1), (hx - 1, hy + 1), (hx + 1, hy - 1)] \
if info_on_pix.get((x, y)) is not None])
four_nes = [(x, y, info_on_pix[(x, y)][0]['depth']) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1)] \
if info_on_pix.get((x, y)) is not None]
sub_mesh = mesh.subgraph(eight_nes).copy()
ccs = netx.connected_components(sub_mesh)
four_ccs = []
for cc_id, _cc in enumerate(ccs):
four_ccs.append(set())
for cc_node in _cc:
if abs(cc_node[0] - hx) + abs(cc_node[1] - hy) < 2:
four_ccs[cc_id].add(cc_node)
largest_cc = sorted(four_ccs, key=lambda x: (len(x), -np.sum([abs(xx[2] - hz) for xx in x])))[-1]
if len(largest_cc) < 2:
for ne in four_nes:
mesh.add_edge(single_edge_node, ne)
else:
mesh.remove_edges_from([(single_edge_node, ne) for ne in mesh.neighbors(single_edge_node)])
new_depth = np.mean([xx[2] for xx in largest_cc])
info_on_pix[(hx, hy)][0]['depth'] = new_depth
info_on_pix[(hx, hy)][0]['disp'] = 1./new_depth
new_node = (hx, hy, new_depth)
mesh = refresh_node(single_edge_node, mesh.node[single_edge_node], new_node, dict(), mesh)
edge_ccs[edge_cc_id] = set([new_node])
for ne in largest_cc:
mesh.add_edge(new_node, ne)
mark = np.zeros((mesh.graph['H'], mesh.graph['W']))
for edge_idx, edge_cc in enumerate(edge_ccs):
for edge_node in edge_cc:
if not (mesh.graph['bord_up'] <= edge_node[0] < mesh.graph['bord_down']-1) or \
not (mesh.graph['bord_left'] <= edge_node[1] < mesh.graph['bord_right']-1):
continue
mesh_neighbors = [*mesh.neighbors(edge_node)]
mesh_neighbors = [xx for xx in mesh_neighbors \
if mesh.graph['bord_up'] < xx[0] < mesh.graph['bord_down'] - 1 and \
mesh.graph['bord_left'] < xx[1] < mesh.graph['bord_right'] - 1]
if len([*mesh.neighbors(edge_node)]) >= 3:
continue
elif len([*mesh.neighbors(edge_node)]) <= 1:
mark[edge_node[0], edge_node[1]] += (len([*mesh.neighbors(edge_node)]) + 1)
else:
dan_ne_node_a = [*mesh.neighbors(edge_node)][0]
dan_ne_node_b = [*mesh.neighbors(edge_node)][1]
if abs(dan_ne_node_a[0] - dan_ne_node_b[0]) > 1 or \
abs(dan_ne_node_a[1] - dan_ne_node_b[1]) > 1:
mark[edge_node[0], edge_node[1]] += 3
mxs, mys = np.where(mark == 1)
conn_0_nodes = [(x[0], x[1], info_on_pix[(x[0], x[1])][0]['depth']) for x in zip(mxs, mys) \
if mesh.has_node((x[0], x[1], info_on_pix[(x[0], x[1])][0]['depth']))]
mxs, mys = np.where(mark == 2)
conn_1_nodes = [(x[0], x[1], info_on_pix[(x[0], x[1])][0]['depth']) for x in zip(mxs, mys) \
if mesh.has_node((x[0], x[1], info_on_pix[(x[0], x[1])][0]['depth']))]
for node in conn_0_nodes:
hx, hy = node[0], node[1]
four_nes = [(x, y, info_on_pix[(x, y)][0]['depth']) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1)] \
if info_on_pix.get((x, y)) is not None]
re_depth = {'value' : 0, 'count': 0}
for ne in four_nes:
mesh.add_edge(node, ne)
re_depth['value'] += cc_node[2]
re_depth['count'] += 1.
re_depth = re_depth['value'] / re_depth['count']
mapping_dict = {node: (node[0], node[1], re_depth)}
info_on_pix, mesh, edge_mesh = update_info(mapping_dict, info_on_pix, mesh, edge_mesh)
depth[node[0], node[1]] = abs(re_depth)
mark[node[0], node[1]] = 0
for node in conn_1_nodes:
hx, hy = node[0], node[1]
eight_nes = set([(x, y, info_on_pix[(x, y)][0]['depth']) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1),
(hx + 1, hy + 1), (hx - 1, hy - 1), (hx - 1, hy + 1), (hx + 1, hy - 1)] \
if info_on_pix.get((x, y)) is not None])
self_nes = set([ne2 for ne1 in mesh.neighbors(node) for ne2 in mesh.neighbors(ne1) if ne2 in eight_nes])
eight_nes = [*(eight_nes - self_nes)]
sub_mesh = mesh.subgraph(eight_nes).copy()
ccs = netx.connected_components(sub_mesh)
largest_cc = sorted(ccs, key=lambda x: (len(x), -np.sum([abs(xx[0] - node[0]) + abs(xx[1] - node[1]) for xx in x])))[-1]
mesh.remove_edges_from([(xx, node) for xx in mesh.neighbors(node)])
re_depth = {'value' : 0, 'count': 0}
for cc_node in largest_cc:
if cc_node[0] == node[0] and cc_node[1] == node[1]:
continue
re_depth['value'] += cc_node[2]
re_depth['count'] += 1.
if abs(cc_node[0] - node[0]) + abs(cc_node[1] - node[1]) < 2:
mesh.add_edge(cc_node, node)
try:
re_depth = re_depth['value'] / re_depth['count']
except:
re_depth = node[2]
renode = (node[0], node[1], re_depth)
mapping_dict = {node: renode}
info_on_pix, mesh, edge_mesh = update_info(mapping_dict, info_on_pix, mesh, edge_mesh)
depth[node[0], node[1]] = abs(re_depth)
mark[node[0], node[1]] = 0
edge_mesh, mesh, mark, info_on_pix = recursive_add_edge(edge_mesh, mesh, info_on_pix, renode, mark)
mxs, mys = np.where(mark == 3)
conn_2_nodes = [(x[0], x[1], info_on_pix[(x[0], x[1])][0]['depth']) for x in zip(mxs, mys) \
if mesh.has_node((x[0], x[1], info_on_pix[(x[0], x[1])][0]['depth'])) and \
mesh.degree((x[0], x[1], info_on_pix[(x[0], x[1])][0]['depth'])) == 2]
sub_mesh = mesh.subgraph(conn_2_nodes).copy()
ccs = netx.connected_components(sub_mesh)
for cc in ccs:
candidate_nodes = [xx for xx in cc if sub_mesh.degree(xx) == 1]
for node in candidate_nodes:
if mesh.has_node(node) is False:
continue
ne_node = [xx for xx in mesh.neighbors(node) if xx not in cc][0]
hx, hy = node[0], node[1]
eight_nes = set([(x, y, info_on_pix[(x, y)][0]['depth']) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1),
(hx + 1, hy + 1), (hx - 1, hy - 1), (hx - 1, hy + 1), (hx + 1, hy - 1)] \
if info_on_pix.get((x, y)) is not None and (x, y, info_on_pix[(x, y)][0]['depth']) not in cc])
ne_sub_mesh = mesh.subgraph(eight_nes).copy()
ne_ccs = netx.connected_components(ne_sub_mesh)
try:
ne_cc = [ne_cc for ne_cc in ne_ccs if ne_node in ne_cc][0]
except:
import pdb; pdb.set_trace()
largest_cc = [xx for xx in ne_cc if abs(xx[0] - node[0]) + abs(xx[1] - node[1]) == 1]
mesh.remove_edges_from([(xx, node) for xx in mesh.neighbors(node)])
re_depth = {'value' : 0, 'count': 0}
for cc_node in largest_cc:
re_depth['value'] += cc_node[2]
re_depth['count'] += 1.
mesh.add_edge(cc_node, node)
try:
re_depth = re_depth['value'] / re_depth['count']
except:
re_depth = node[2]
renode = (node[0], node[1], re_depth)
mapping_dict = {node: renode}
info_on_pix, mesh, edge_mesh = update_info(mapping_dict, info_on_pix, mesh, edge_mesh)
depth[node[0], node[1]] = abs(re_depth)
mark[node[0], node[1]] = 0
edge_mesh, mesh, mark, info_on_pix = recursive_add_edge(edge_mesh, mesh, info_on_pix, renode, mark)
break
if len(cc) == 1:
node = [node for node in cc][0]
hx, hy = node[0], node[1]
nine_nes = set([(x, y, info_on_pix[(x, y)][0]['depth']) for x, y in [(hx, hy), (hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1),
(hx + 1, hy + 1), (hx - 1, hy - 1), (hx - 1, hy + 1), (hx + 1, hy - 1)] \
if info_on_pix.get((x, y)) is not None and mesh.has_node((x, y, info_on_pix[(x, y)][0]['depth']))])
ne_sub_mesh = mesh.subgraph(nine_nes).copy()
ne_ccs = netx.connected_components(ne_sub_mesh)
for ne_cc in ne_ccs:
if node in ne_cc:
re_depth = {'value' : 0, 'count': 0}
for ne in ne_cc:
if abs(ne[0] - node[0]) + abs(ne[1] - node[1]) == 1:
mesh.add_edge(node, ne)
re_depth['value'] += ne[2]
re_depth['count'] += 1.
re_depth = re_depth['value'] / re_depth['count']
mapping_dict = {node: (node[0], node[1], re_depth)}
info_on_pix, mesh, edge_mesh = update_info(mapping_dict, info_on_pix, mesh, edge_mesh)
depth[node[0], node[1]] = abs(re_depth)
mark[node[0], node[1]] = 0
return mesh, info_on_pix, edge_mesh, depth, mark
def context_and_holes(mesh, edge_ccs, config, specific_edge_id, specific_edge_loc, depth_feat_model,
connect_points_ccs=None, inpaint_iter=0, filter_edge=False, vis_edge_id=None):
edge_maps = np.zeros((mesh.graph['H'], mesh.graph['W'])) - 1
mask_info = {}
for edge_id, edge_cc in enumerate(edge_ccs):
for edge_node in edge_cc:
edge_maps[edge_node[0], edge_node[1]] = edge_id
context_ccs = [set() for x in range(len(edge_ccs))]
extend_context_ccs = [set() for x in range(len(edge_ccs))]
extend_erode_context_ccs = [set() for x in range(len(edge_ccs))]
extend_edge_ccs = [set() for x in range(len(edge_ccs))]
accomp_extend_context_ccs = [set() for x in range(len(edge_ccs))]
erode_context_ccs = [set() for x in range(len(edge_ccs))]
broken_mask_ccs = [set() for x in range(len(edge_ccs))]
invalid_extend_edge_ccs = [set() for x in range(len(edge_ccs))]
intouched_ccs = [set() for x in range(len(edge_ccs))]
redundant_ccs = [set() for x in range(len(edge_ccs))]
if inpaint_iter == 0:
background_thickness = config['background_thickness']
context_thickness = config['context_thickness']
else:
background_thickness = config['background_thickness_2']
context_thickness = config['context_thickness_2']
mesh_nodes = mesh.nodes
for edge_id, edge_cc in enumerate(edge_ccs):
if context_thickness == 0 or (len(specific_edge_id) > 0 and edge_id not in specific_edge_id):
continue
edge_group = {}
for edge_node in edge_cc:
far_nodes = mesh_nodes[edge_node].get('far')
if far_nodes is None:
continue
for far_node in far_nodes:
if far_node in edge_cc:
continue
context_ccs[edge_id].add(far_node)
if mesh_nodes[far_node].get('edge_id') is not None:
if edge_group.get(mesh_nodes[far_node]['edge_id']) is None:
edge_group[mesh_nodes[far_node]['edge_id']] = set()
edge_group[mesh_nodes[far_node]['edge_id']].add(far_node)
if len(edge_cc) > 2:
for edge_key in [*edge_group.keys()]:
if len(edge_group[edge_key]) == 1:
context_ccs[edge_id].remove([*edge_group[edge_key]][0])
for edge_id, edge_cc in enumerate(edge_ccs):
if inpaint_iter != 0:
continue
tmp_intouched_nodes = set()
for edge_node in edge_cc:
raw_intouched_nodes = set(mesh_nodes[edge_node].get('near')) if mesh_nodes[edge_node].get('near') is not None else set()
tmp_intouched_nodes |= set([xx for xx in raw_intouched_nodes if mesh_nodes[xx].get('edge_id') is not None and \
len(context_ccs[mesh_nodes[xx].get('edge_id')]) > 0])
intouched_ccs[edge_id] |= tmp_intouched_nodes
tmp_intouched_nodes = None
mask_ccs = copy.deepcopy(edge_ccs)
forbidden_len = 3
forbidden_map = np.ones((mesh.graph['H'] - forbidden_len, mesh.graph['W'] - forbidden_len))
forbidden_map = np.pad(forbidden_map, ((forbidden_len, forbidden_len), (forbidden_len, forbidden_len)), mode='constant').astype(np.bool)
cur_tmp_mask_map = np.zeros_like(forbidden_map).astype(np.bool)
passive_background = 10 if 10 is not None else background_thickness
passive_context = 1 if 1 is not None else context_thickness
for edge_id, edge_cc in enumerate(edge_ccs):
cur_mask_cc = None; cur_mask_cc = []
cur_context_cc = None; cur_context_cc = []
cur_accomp_near_cc = None; cur_accomp_near_cc = []
cur_invalid_extend_edge_cc = None; cur_invalid_extend_edge_cc = []
cur_comp_far_cc = None; cur_comp_far_cc = []
tmp_erode = []
if len(context_ccs[edge_id]) == 0 or (len(specific_edge_id) > 0 and edge_id not in specific_edge_id):
continue
for i in range(max(background_thickness, context_thickness)):
cur_tmp_mask_map.fill(False)
if i == 0:
tmp_mask_nodes = copy.deepcopy(mask_ccs[edge_id])
tmp_intersect_nodes = []
tmp_intersect_context_nodes = []
mask_map = np.zeros((mesh.graph['H'], mesh.graph['W']), dtype=np.bool)
context_depth = np.zeros((mesh.graph['H'], mesh.graph['W']))
comp_cnt_depth = np.zeros((mesh.graph['H'], mesh.graph['W']))
connect_map = np.zeros((mesh.graph['H'], mesh.graph['W']))
for node in tmp_mask_nodes:
mask_map[node[0], node[1]] = True
depth_count = 0
if mesh_nodes[node].get('far') is not None:
for comp_cnt_node in mesh_nodes[node]['far']:
comp_cnt_depth[node[0], node[1]] += abs(comp_cnt_node[2])
depth_count += 1
if depth_count > 0:
comp_cnt_depth[node[0], node[1]] = comp_cnt_depth[node[0], node[1]] / depth_count
connect_node = []
if mesh_nodes[node].get('connect_point_id') is not None:
connect_node.append(mesh_nodes[node]['connect_point_id'])
connect_point_id = np.bincount(connect_node).argmax() if len(connect_node) > 0 else -1
if connect_point_id > -1 and connect_points_ccs is not None: