-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathdepth_map_tools.py
More file actions
1658 lines (1279 loc) · 58.8 KB
/
depth_map_tools.py
File metadata and controls
1658 lines (1279 loc) · 58.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
import open3d as o3d
import copy
import cv2
from contextlib import contextmanager
import time
import ctypes
from ctypes import wintypes
from OpenGL.GL import *
from OpenGL.GL.shaders import compileProgram, compileShader
import glfw
@contextmanager
def timer(name = 'not named'):
start = time.perf_counter()
yield
end = time.perf_counter()
print(f"{name}: {end - start:.6f} seconds")
def calculate_normals(depth, K):
H, W = depth.shape
fx = float(K[0, 0])
fy = float(K[1, 1])
cx = float(K[0, 2])
cy = float(K[1, 2])
# ------------------------------------------------------------------
# 0) Per-pixel normals (unchanged)
# ------------------------------------------------------------------
Zc = depth # (H, W)
u = np.arange(W, dtype=np.float32)
v = np.arange(H, dtype=np.float32)
u_grid, v_grid = np.meshgrid(u, v)
Xc = (u_grid - cx) / fx * Zc
Yc = (cy - v_grid) / fy * Zc
Zc_cam = Zc
P = np.stack([Xc, Yc, Zc_cam], axis=-1)
P_x1 = np.empty_like(P)
P_x1[:, :-1, :] = P[:, 1:, :]
P_x1[:, -1, :] = P[:, -1, :]
P_y1 = np.empty_like(P)
P_y1[:-1, :, :] = P[1:, :, :]
P_y1[-1, :, :] = P[-1, :, :]
v1 = P_x1 - P
v2 = P_y1 - P
normal = np.cross(v1, v2)
norm = np.linalg.norm(normal, axis=-1, keepdims=True) + 1e-8
normal = normal / norm
# --- DirectX conversion ---
normal[..., 1] *= -1 # flip Y
normal[..., 2] *= -1 # flip Z
return normal
def open_cv_w2c_to_gl_view(transform_to_ref):
open_cv_w2c = np.linalg.inv(transform_to_ref) # this is your original w2c again
# 2) Axis conversion CV -> OpenGL
A = np.diag([1, -1, -1, 1]).astype(np.float32)
# world_gl -> camera_gl (still row-major numbers)
V_gl_row = A @ open_cv_w2c @ A
# 3) Convert to column-major for OpenGL
base_pos = V_gl_row
# 4. OpenGL view matrix is inverse of camera pose
return np.linalg.inv(base_pos)
# ============================================================
# Build frustum planes (6 planes) from K + c2w
# Each plane: (normal n, scalar d) so that n·X + d >= 0 means "inside"
# ============================================================
def frustum_planes(K, c2w, near=0.1, far=100.0):
fx, fy = K[0,0], K[1,1]
cx, cy = K[0,2], K[1,2]
W = int(round(2 * cx))
H = int(round(2 * cy))
# Directions of rays for 4 corners in camera space
invK = np.linalg.inv(K)
corners_px = [(0,0), (W-1,0), (W-1,H-1), (0,H-1)]
rays = []
for u,v in corners_px:
d = invK @ np.array([u,v,1.0],dtype=np.float32)
rays.append(d / np.linalg.norm(d))
rays = np.array(rays)
# Camera center & rotation
R = c2w[:3,:3]
t = c2w[:3,3]
C = t # camera center in world
# Convert rays to world coords
rays_world = (R @ rays.T).T
# --- Build 6 planes in world space ---
planes = []
# Near plane
n_near = rays_world.mean(axis=0) # approximate forward
n_near = n_near / np.linalg.norm(n_near)
Pn = C + n_near * near
planes.append(( n_near, -np.dot(n_near, Pn) ))
# Far plane
Pf = C + n_near * far
planes.append(( -n_near, np.dot(n_near, Pf) ))
# Side planes (each edge defines a plane through C)
# For each edge (i -> i+1)
for i in range(4):
a = rays_world[i]
b = rays_world[(i+1)%4]
n = np.cross(a, b)
if np.linalg.norm(n) < 1e-9: continue
n = n / np.linalg.norm(n)
d = -np.dot(n, C)
planes.append((n, d))
return planes # list of (n, d)
# ============================================================
# SAT / Half-space intersection test for two frusta
# ============================================================
def frusta_intersect(K, c2w1, c2w2, near=0.1, far=10000.0):
P1 = frustum_planes(K, c2w1, near, far)
P2 = frustum_planes(K, c2w2, near, far)
# For convex polyhedra A and B:
# Check if all vertices of A lie outside any plane of B OR vice versa.
# Instead of computing vertices, sample along rays (exact for pyramids).
# Get 8 corner rays
cx, cy = K[0,2], K[1,2]
W = int(round(2*cx))
H = int(round(2*cy))
invK = np.linalg.inv(K)
def corner_rays():
pts=[]
for u,v in [(0,0),(W-1,0),(W-1,H-1),(0,H-1)]:
d = invK @ np.array([u,v,1.0])
pts.append(d/np.linalg.norm(d))
return np.array(pts)
cr = corner_rays()
# CAM CENTERS
C1 = c2w1[:3,3]
C2 = c2w2[:3,3]
R1 = c2w1[:3,:3]
R2 = c2w2[:3,:3]
# Build the 8 vertices for each frustum exactly
def frustum_vertices(c2w):
C = c2w[:3,3]
R = c2w[:3,:3]
out=[]
for z in (near, far):
for d in cr:
p_cam = d * z
out.append(R @ p_cam + C)
return np.array(out)
V1 = frustum_vertices(c2w1)
V2 = frustum_vertices(c2w2)
# Test each frustum against the other's planes
def outside_all(vertices, planes):
# If all vertices lie OUTSIDE a single plane → separated
for (n, d) in planes:
if np.all(np.dot(vertices, n) + d < 0):
return True
return False
# If either frustum is fully outside any plane → no intersection
if outside_all(V1, frustum_planes(K, c2w2, near, far)):
return False
if outside_all(V2, frustum_planes(K, c2w1, near, far)):
return False
return True
def apply_side_view_to_paralax_mask(parallax_mask, normals, right):
right_dot = normals[..., 0]
mask_normal_thrsehold_deg = 90.0
cos_threshold = np.cos(np.deg2rad(mask_normal_thrsehold_deg))
if right:
mask_normal = (right_dot > cos_threshold)
else:
mask_normal = (right_dot < cos_threshold)
side_view_mask = parallax_mask & mask_normal
return side_view_mask
def rotation_y(angle_rad):
#print(np.cos)
c = np.cos(angle_rad)
s = np.sin(angle_rad)
return np.array([
[ c, 0, s, 0],
[ 0, 1, 0, 0],
[-s, 0, c, 0],
[ 0, 0, 0, 1]
], dtype=np.float32)
def translation_matrix(x, y, z):
T = np.eye(4, dtype=np.float32)
T[:3, 3] = [x, y, z]
return T
def get_cam_view(side_offset, convergence_angle_rad=0.0, reverse=False):
eye = np.array([0, 0, 0], dtype=np.float32)
target = eye + np.array([0, 0, -1], dtype=np.float32)
up = np.array([0, 1, 0], dtype=np.float32)
base_view = gl_look_at(eye, target, up)
if not reverse:
# ----- Forward transform -----
T = translation_matrix(side_offset, 0, 0) # world translation
R = rotation_y(convergence_angle_rad) # inward rotation
return R @ T @ base_view
else:
# ----- Proper reverse transform -----
R_inv = rotation_y(-convergence_angle_rad) # undo rotation
T_inv = translation_matrix(-side_offset, 0, 0) # undo translation
# Reverse the order: T_inv then R_inv
return T_inv @ R_inv @ base_view
def convergence_angle(distance, pupillary_distance):
"""
Calculate the convergence angles for both eyes to point to an object.
Parameters:
distance (float): The distance to the object.
pupillary_distance (float): The distance between the centers of the two pupils.
Returns:
- angle_per_eye: The angle each eye must rotate inward from the midline.
"""
if distance == 0:
raise ValueError("Distance must be non-zero to compute a valid angle.")
# Calculate the angle for one eye in radians using arctan((pupillary_distance/2) / distance)
return np.atan((pupillary_distance / 2) / distance)
def mesh_from_depth_and_rgb(
depth,
rgb_image,
K
):
depth = np.asarray(depth).astype(np.float32)
rgb_image = np.asarray(rgb_image).astype(np.float32)/255
H, W = depth.shape
fx = float(K[0, 0])
fy = float(K[1, 1])
cx = float(K[0, 2])
cy = float(K[1, 2])
Zc = depth # (H, W)
normal = calculate_normals(Zc, K)
#right_dot = normal[..., 0]
#
#mask_normal_thrsehold_deg = 90.0
#cos_threshold = np.cos(np.deg2rad(mask_normal_thrsehold_deg))
#if mask_for_right:
# mask_normal = (right_dot > cos_threshold)
#else:
# mask_normal = (right_dot < cos_threshold)
# ----------------------------------------------------
# Expand pixel-center normals to per-corner normals
# Each pixel has 4 vertices → duplicate the normal
# resulting shape: (H, W, 4, 3)
# ----------------------------------------------------
c = Zc
up = np.pad(Zc, ((1, 0), (0, 0)), mode='edge')[:-1, :]
down = np.pad(Zc, ((0, 1), (0, 0)), mode='edge')[1:, :]
left = np.pad(Zc, ((0, 0), (1, 0)), mode='edge')[:, :-1]
right = np.pad(Zc, ((0, 0), (0, 1)), mode='edge')[:, 1:]
up_left = np.pad(Zc, ((1, 0), (1, 0)), mode='edge')[:-1, :-1]
up_right = np.pad(Zc, ((1, 0), (0, 1)), mode='edge')[:-1, 1:]
down_left = np.pad(Zc, ((0, 1), (1, 0)), mode='edge')[1:, :-1]
down_right = np.pad(Zc, ((0, 1), (0, 1)), mode='edge')[1:, 1:]
# ------------------------------------------------------------------
# 3) Unclamped corners (no threshold), used when apply_clampin_to_mesh=False
# ------------------------------------------------------------------
z0_u = mesh_maker_helper_make_corner_unclamped(c, up, left, up_left)
z1_u = mesh_maker_helper_make_corner_unclamped(c, up, right, up_right)
z2_u = mesh_maker_helper_make_corner_unclamped(c, down, left, down_left)
z3_u = mesh_maker_helper_make_corner_unclamped(c, down, right, down_right)
#z_corners_unclamped = np.stack([z0_u, z1_u, z2_u, z3_u], axis=-1) # (H,W,4)
# ------------------------------------------------------------------
# NEW: enforce consistency of corner depths across neighboring pixels
# so that shared logical corners have exactly the same Z value.
# ------------------------------------------------------------------
corner_sum = np.zeros((H + 1, W + 1), dtype=np.float32)
corner_count = np.zeros((H + 1, W + 1), dtype=np.float32)
# Each pixel (y, x) contributes its 4 corners:
# corner 0 (TL) -> (y, x)
# corner 1 (TR) -> (y, x+1)
# corner 2 (BL) -> (y+1, x)
# corner 3 (BR) -> (y+1, x+1)
# Top-left corners
corner_sum[0:H, 0:W ] += z0_u
corner_count[0:H, 0:W ] += 1.0
# Top-right corners
corner_sum[0:H, 1:W+1 ] += z1_u
corner_count[0:H, 1:W+1 ] += 1.0
# Bottom-left corners
corner_sum[1:H+1, 0:W ] += z2_u
corner_count[1:H+1, 0:W ] += 1.0
# Bottom-right corners
corner_sum[1:H+1, 1:W+1 ] += z3_u
corner_count[1:H+1, 1:W+1] += 1.0
# Avoid divide-by-zero just in case
corner_count = np.maximum(corner_count, 1.0)
Z_corners_shared = corner_sum / corner_count # shape: (H+1, W+1)
# Rebuild per-pixel 4-corner depths from this *shared* grid
Z0 = Z_corners_shared[0:H, 0:W ] # TL
Z1 = Z_corners_shared[0:H, 1:W+1 ] # TR
Z2 = Z_corners_shared[1:H+1, 0:W ] # BL
Z3 = Z_corners_shared[1:H+1, 1:W+1 ] # BR
Z_corners_consistent = np.stack([Z0, Z1, Z2, Z3], axis=-1) # (H, W, 4)
# FINAL MASK: clamping AND normal-direction
#if mask_for_right is None:
# mask_img = parallax_mask
#else:
# mask_img = parallax_mask & mask_normal
# ------------------------------------------------------------------
# 6) Corner coordinates in pixel space
# ------------------------------------------------------------------
u_corners = np.arange(W +1, dtype=np.float32)
v_corners = np.arange(H +1, dtype=np.float32)
u_corner_grid, v_corner_grid = np.meshgrid(u_corners, v_corners)
u0 = u_corner_grid[0:H, 0:W]
u1 = u_corner_grid[0:H, 1:W+1]
u2 = u_corner_grid[1:H+1, 0:W]
u3 = u_corner_grid[1:H+1, 1:W+1]
v0 = v_corner_grid[0:H, 0:W]
v1 = v_corner_grid[0:H, 1:W+1]
v2 = v_corner_grid[1:H+1, 0:W]
v3 = v_corner_grid[1:H+1, 1:W+1]
u_pix = np.stack([u0, u1, u2, u3], axis=-1)
v_pix = np.stack([v0, v1, v2, v3], axis=-1)
# ------------------------------------------------------------------
# 7) Choose which corner depths to use for geometry
# ------------------------------------------------------------------
make_flat = False
if make_flat:
# Zc shape is (H, W)
# We want (H, W, 4) where all four corners use the same depth
Z = np.repeat(Zc[:, :, None], 4, axis=2) # flat quads
else:
# old behavior
Z = Z_corners_consistent
Z = Z.astype(np.float32)
X = (u_pix - cx) / fx * Z
Y = (cy - v_pix) / fy * Z
Z = -Z
X_flat = X.reshape(-1)
Y_flat = Y.reshape(-1)
Z_flat = Z.reshape(-1)
positions = np.stack([X_flat, Y_flat, Z_flat], axis=-1)
# ------------------------------------------------------------------
# 8) Colors (optionally black out masked pixels)
# ------------------------------------------------------------------
#rgb = rgb_image.astype(np.float32) / 255.0
# ------------------------------------------------------------------
# DEBUG TEXTURE: use normals as RGB
# ------------------------------------------------------------------
#
# Map normals from [-1,1] to [0,1] then to [0,255]
#normal_rgb = (normal * 0.5 + 0.5).clip(0.0, 1.0)
#rgb = normal_rgb
rgb_4 = np.repeat(rgb_image.reshape(H * W, 3), 4, axis=0)
pixel_ids = np.repeat(np.arange(H*W, dtype=np.uint32)+1, 4)
pixel_ids = pixel_ids.reshape(-1, 1).astype(np.float32)
# Flatten normals the same way as positions
normal_expanded = np.repeat(normal[:, :, None, :], 4, axis=2)
normals_flat = normal_expanded.reshape(-1, 3).astype(np.float32)
vertices = np.concatenate([
positions, # (N,3)
normals_flat, # (N,3)
rgb_4, # (N,3)
pixel_ids # (N,1)
], axis=-1)
# ------------------------------------------------------------------
# 9) Indices
# ------------------------------------------------------------------
num_pixels = H * W
base_indices = (np.arange(num_pixels, dtype=np.uint32) * 4)[:, None]
local = base_indices + np.array([0, 1, 2, 3], dtype=np.uint32)[None, :]
v0_i = local[:, 0]
v1_i = local[:, 1]
v2_i = local[:, 2]
v3_i = local[:, 3]
tris = np.stack([
np.stack([v0_i, v2_i, v1_i], axis=-1),
np.stack([v2_i, v3_i, v1_i], axis=-1),
], axis=1)
indices = tris.reshape(-1).astype(np.uint32)
return (vertices, indices), normal
def mesh_maker_helper_make_corner_unclamped(c, n1, n2, n3):
# Just average center+neighbors (what you conceptually want as baseline)
return (c + n1 + n2 + n3) * 0.25
def mesh_maker_helper_make_corner_with_mask(c, n1, n2, n3, thr):
sum_z = c.copy()
cnt = np.ones_like(c, dtype=np.float32)
rejected = np.zeros_like(c, dtype=bool)
for n in (n1, n2, n3):
diff = np.abs(n - c)
accept = diff <= thr
rejected |= ~accept
sum_z += np.where(accept, n, 0.0)
cnt += accept.astype(np.float32)
return (sum_z / cnt), rejected
def remap_ids_to_img(rgb_image, id_maps, invalid_color=(0,0,0)):
"""
Used to go back throgh the redering pipline and get the source data
id_maps = [ids1, ids2, ..., idsN]
idsN has output resolution
idsN → ids(N-1) → ... → ids1 → rgb_image
"""
# Store output shape BEFORE flattening
final_shape = id_maps[-1].shape
# Flatten maps
flat_maps = [m.reshape(-1) for m in id_maps]
# Start with the last map (idsN)
current_ids = flat_maps[-1].copy()
N_final = current_ids.size
# Prepare validity mask
valid = np.ones(N_final, dtype=bool)
# Process from ids(N-1) down to ids1
# IMPORTANT: skip flat_maps[-1] — do NOT dereference the last map
for stage in reversed(range(len(id_maps)-1)):
ids = flat_maps[stage]
Ns = ids.size
stage_valid = (current_ids >= 0) & (current_ids < Ns)
valid &= stage_valid
# remap only valid entries
next_ids = np.zeros_like(current_ids)
idx = valid & stage_valid
next_ids[idx] = ids[current_ids[idx]]
current_ids = next_ids
# Now current_ids indexes directly into the rgb_image
H0, W0, _ = rgb_image.shape
N0 = H0 * W0
final_valid = valid & (current_ids >= 0) & (current_ids < N0)
out = np.zeros((N_final, 3), dtype=rgb_image.dtype)
out[:] = invalid_color
ids0 = current_ids[final_valid]
ys = ids0 // W0
xs = ids0 % W0
out[final_valid] = rgb_image[ys, xs]
return out.reshape(final_shape[0], final_shape[1], 3)
def steep_disparity_lr(depth, K, parallax_shift=0.0351, threshold=0.09):
"""
depth : (H,W) depth map
K : 3x3 intrinsic matrix
parallax_shift : stereo baseline / shift scale
threshold : disparity magnitude threshold
Returns:
left_mask, right_mask
(each boolean (H,W) array)
"""
Zc = depth
fx = float(K[0, 0])
# Neighbors
left_Z = np.pad(Zc, ((0,0),(1,0)), mode='edge')[:, :-1]
right_Z = np.pad(Zc, ((0,0),(0,1)), mode='edge')[:, 1:]
# Compute horizontal disparity change
du_L = fx * parallax_shift * (1.0/Zc - 1.0/left_Z) # steep toward left neighbor
du_R = fx * parallax_shift * (1.0/Zc - 1.0/right_Z) # steep toward right neighbor
# Two directional steepness masks
#left_mask = np.abs(du_L) > threshold
#right_mask = np.abs(du_R) > threshold
left_mask = (du_L > threshold) | (du_R < -threshold)
right_mask = (du_R > threshold) | (du_L < -threshold)
return left_mask, right_mask
def steep_mask_disparity(depth, K, parallax_shift=0.0351, threshold=0.1):
"""
depth : (H, W) depth map
K : 3x3 camera intrinsic matrix
parallax_shift : baseline / relative camera shift scaling
threshold : disparity gradient threshold for steepness
Returns:
Boolean mask where steep / visually-foreshortened pixels are marked True.
"""
Zc = depth
# Extract focal length fx (pixel units)
fx = float(K[0, 0])
# Build neighbor depth maps
left = np.pad(Zc, ((0,0),(1,0)), mode='edge')[:, :-1]
right = np.pad(Zc, ((0,0),(0,1)), mode='edge')[:, 1:]
up = np.pad(Zc, ((1,0),(0,0)), mode='edge')[:-1, :]
down = np.pad(Zc, ((0,1),(0,0)), mode='edge')[1:, :]
# disparity gradient (inverse depth change scaled by fx & baseline)
du_l = fx * parallax_shift * (1.0/Zc - 1.0/left)
du_r = fx * parallax_shift * (1.0/Zc - 1.0/right)
du_u = fx * parallax_shift * (1.0/Zc - 1.0/up)
du_d = fx * parallax_shift * (1.0/Zc - 1.0/down)
# steep if any neighbor parallax exceeds threshold
mask = (
(np.abs(du_l) > threshold) |
(np.abs(du_r) > threshold) |
(np.abs(du_u) > threshold) |
(np.abs(du_d) > threshold)
)
return mask
def generate_normal_bg_image(width, height):
"""
Create an X-shaped normal background using your four normals.
The X intersects EXACTLY at the rectangle center, even if W != H.
Includes diagonal pixels (no gaps).
"""
W, H = width, height
img = np.zeros((H, W, 3), dtype=np.float32)
# Your original normals
n_left = np.array([0.0, 0.5, 0.5], dtype=np.float32)
n_right = np.array([1.0, 0.5, 0.5], dtype=np.float32)
n_top = np.array([0.5, 0.5, 0.0], dtype=np.float32)
n_bottom = np.array([0.5, 0.5, 1.0], dtype=np.float32)
# Grid
x = np.arange(W)
y = np.arange(H)
xx, yy = np.meshgrid(x, y)
# Center
cx = W / 2.0
cy = H / 2.0
# Diagonals (scaled)
main_diag = (yy - cy) * W + (xx - cx) * H
anti_diag = (yy - cy) * W - (xx - cx) * H
# Region masks WITH diagonals included (<= instead of <)
mask_top = (main_diag <= 0) & (anti_diag <= 0)
mask_right = (main_diag <= 0) & (anti_diag >= 0)
mask_bottom = (main_diag >= 0) & (anti_diag >= 0)
mask_left = (main_diag >= 0) & (anti_diag <= 0)
img[mask_top] = n_top
img[mask_bottom] = n_bottom
img[mask_left] = n_left
img[mask_right] = n_right
return img
import threading as _threading
_gl_state = _threading.local() # per-thread: .glwindow, .render_shader
_glfw_lock = _threading.Lock() # serialises the one-time glfw.init() call
_glfw_inited = False
def gl_render(vertices_and_indices, mvp, width, height, near, far, bg_color = [0.0,0.0,0.0]):
global _glfw_inited
if not hasattr(_gl_state, 'glwindow') or _gl_state.glwindow is None:
with _glfw_lock:
if not _glfw_inited:
if not glfw.init():
raise RuntimeError("Could not init GLFW")
_glfw_inited = True
glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
glfw.window_hint(glfw.VISIBLE, glfw.FALSE) # Hide the window
glfw.window_hint(glfw.FOCUSED, glfw.FALSE)
glfw.window_hint(glfw.AUTO_ICONIFY, glfw.FALSE)
#Create hidden window to be able to set context
_gl_state.glwindow = glfw.create_window(1, 1, "", None, None)
glfw.make_context_current(_gl_state.glwindow)
glEnable(GL_DEPTH_TEST)
# ---------- SHADERS ----------
VERT_SHADER = """
#version 330 core
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec3 aNormal;
layout(location = 2) in vec3 aColor;
layout(location = 3) in float aID;
out vec3 vColor;
out vec3 vNormal;
flat out float vID;
uniform mat4 uMVP;
void main()
{
vColor = aColor;
vNormal = aNormal;
vID = aID;
gl_Position = uMVP * vec4(aPos, 1.0);
}
"""
FRAG_SHADER = """
#version 330 core
in vec3 vColor;
in vec3 vNormal;
flat in float vID;
layout(location = 0) out vec4 FragColor;
layout(location = 1) out vec3 FragNormal;
layout(location = 2) out int FragID;
void main()
{
FragColor = vec4(vColor, 1.0);
FragNormal = vNormal;//normalize(vNormal);
FragID = int(vID);
}
"""
_gl_state.render_shader = compileProgram(
compileShader(VERT_SHADER, GL_VERTEX_SHADER),
compileShader(FRAG_SHADER, GL_FRAGMENT_SHADER)
)
# ---------- CREATE FBO ----------
fbo = glGenFramebuffers(1)
glBindFramebuffer(GL_FRAMEBUFFER, fbo)
# --- RGB ---
tex_color = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, tex_color)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8,
width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, None)
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, tex_color, 0)
# --- NORMALS ---
tex_normals = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, tex_normals)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F,
width, height, 0, GL_RGB, GL_FLOAT, None)
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1,
GL_TEXTURE_2D, tex_normals, 0)
# --- IDS ---
tex_ids = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, tex_ids)
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32I,
width, height, 0, GL_RED_INTEGER, GL_INT, None)
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2,
GL_TEXTURE_2D, tex_ids, 0)
# --- DEPTH ---
tex_depth = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, tex_depth)
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24,
width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, None)
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_TEXTURE_2D, tex_depth, 0)
# ---------- draw buffers ----------
buffers = (OpenGL.raw.GL.VERSION.GL_1_0.GLenum * 3)(
GL_COLOR_ATTACHMENT0,
GL_COLOR_ATTACHMENT1,
GL_COLOR_ATTACHMENT2
)
glDrawBuffers(3, buffers)
vertices, indices = vertices_and_indices
# ---------- VAO ----------
vao = glGenVertexArrays(1)
glBindVertexArray(vao)
vbo = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, vbo)
glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)
ebo = glGenBuffers(1)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, GL_STATIC_DRAW)
# NEW: 10 floats per vertex (3 pos, 3 normal, 3 color, 1 id)
stride = 10 * 4
# aPos (location=0)
glEnableVertexAttribArray(0)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, ctypes.c_void_p(0))
# aNormal (location=1) → offset 12 bytes
glEnableVertexAttribArray(1)
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, stride, ctypes.c_void_p(12))
# aColor (location=2) → offset 24 bytes
glEnableVertexAttribArray(2)
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, stride, ctypes.c_void_p(24))
# aID (location=3) → offset 36 bytes
glEnableVertexAttribArray(3)
glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, stride, ctypes.c_void_p(36))
# ---------- DRAW ----------
glBindFramebuffer(GL_FRAMEBUFFER, fbo)
glViewport(0, 0, width, height)
glClearColor(bg_color[0], bg_color[1], bg_color[2], 1)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glClearBufferiv(GL_COLOR, 2, np.array([0], dtype=np.int32)) # set ids to zero
glUseProgram(_gl_state.render_shader)
loc_mvp = glGetUniformLocation(_gl_state.render_shader, "uMVP")
glUniformMatrix4fv(loc_mvp, 1, GL_FALSE, mvp.T)
glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None)
# ---------- READ RGB ----------
glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo)
glReadBuffer(GL_COLOR_ATTACHMENT0)
buf = glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE)
rgb = np.frombuffer(buf, dtype=np.uint8).reshape(height, width, 3)[::-1]
# ---------- READ DEPTH (IMPORTANT FIX) ----------
glBindFramebuffer(GL_FRAMEBUFFER, fbo) # <-- REQUIRED for NVIDIA
glReadBuffer(GL_NONE)
buf = glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT)
depth_raw = np.frombuffer(buf, dtype=np.float32).reshape(height, width)[::-1]
# ---------- LINEARIZE ----------
z_ndc = depth_raw * 2.0 - 1.0
linear_depth = (2.0 * near * far) / (far + near - z_ndc * (far - near))
# ---------- READ NORMALS ----------
glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo)
glReadBuffer(GL_COLOR_ATTACHMENT1)
buf = glReadPixels(0, 0, width, height, GL_RGB, GL_FLOAT)
normals = np.frombuffer(buf, dtype=np.float32).reshape(height, width, 3)[::-1]
normals = (normals * 0.5 + 0.5).clip(0.0, 1.0)
# ---------- READ ID ----------
glReadBuffer(GL_COLOR_ATTACHMENT2)
buf = glReadPixels(0, 0, width, height, GL_RED_INTEGER, GL_INT)
ids = np.frombuffer(buf, dtype=np.int32).reshape(height, width)[::-1]
# ---------- CLEANUP ----------
glDeleteFramebuffers(1, [fbo])
glDeleteTextures(1, [tex_color])
glDeleteTextures(1, [tex_normals])
glDeleteTextures(1, [tex_ids])
glDeleteTextures(1, [tex_depth])
glDeleteBuffers(1, [vbo])
glDeleteBuffers(1, [ebo])
glDeleteVertexArrays(1, [vao])
return rgb, linear_depth, normals, ids
def open_gl_projection_from_camera_matrix(K, near, far):
fx = K[0, 0]
fy = K[1, 1]
cx = K[0, 2]
cy = K[1, 2]
# Convert intrinsics to OpenGL-style NDC projection
# Note: OpenGL NDC x,y range is [-1, 1]
#
# x_ndc = (x * 2 / width) - 1
# y_ndc = 1 - (y * 2 / height)
width = cx * 2
height = cy * 2
A11 = 2 * fx / width
A22 = 2 * fy / height
A13 = 2 * (cx / width) - 1
A23 = 1 - 2 * (cy / height)
# Depth terms same as your perspective() version
A33 = -(far + near) / (far - near)
A34 = -(2 * far * near) / (far - near)
proj = np.array([
[A11, 0, A13, 0],
[0, A22, A23, 0],
[0, 0, A33, A34],
[0, 0, -1, 0]
], dtype=np.float32)
return proj
def compute_camera_matrix(fov_horizontal_deg, fov_vertical_deg, image_width, image_height):
#We need one or the other
if fov_horizontal_deg is not None:
# Convert FoV from degrees to radians
fov_horizontal_rad = np.deg2rad(fov_horizontal_deg)
# Compute the focal lengths in pixels
fx = image_width / (2 * np.tan(fov_horizontal_rad / 2))
if fov_vertical_deg is not None:
# Convert FoV from degrees to radians
fov_vertical_rad = np.deg2rad(fov_vertical_deg)
# Compute the focal lengths in pixels
fy = image_height / (2 * np.tan(fov_vertical_rad / 2))
if fov_vertical_deg is None:
fy = fx
if fov_horizontal_deg is None:
fx = fy
# Assume the principal point is at the image center
cx = image_width / 2
cy = image_height / 2
# Construct the camera matrix
camera_matrix = np.array([[fx, 0, cx],
[ 0, fy, cy],
[ 0, 0, 1]], dtype=np.float64)
return camera_matrix
def svd(source_points, target_points, ZeroCentroid = False):
# Compute the centroid of each set of points
if ZeroCentroid: #If we only care about rotation. ie the camera is locked in place
z = np.array([0.0,0.0,0.0])
centroid_source = z
centroid_target = z
else:
centroid_source = np.mean(source_points, axis=0)
centroid_target = np.mean(target_points, axis=0)
#print(source_points, target_points)
# Center the points around the centroid
source_centered = source_points - centroid_source
target_centered = target_points - centroid_target
# Compute the covariance matrix
H = np.dot(source_centered.T, target_centered)
# Perform Singular Value Decomposition (SVD)
U, S, Vt = np.linalg.svd(H)
# Compute the rotation matrix
Rot = np.dot(Vt.T, U.T)
#Special reflection case handling
if np.linalg.det(Rot) < 0:
Vt[2, :] *= -1
Rot = np.dot(Vt.T, U.T)
# Form the transformation matrix
transformation_matrix = np.eye(4)
transformation_matrix[:3, :3] = Rot
# Compute the translation vector
transformation_matrix[:3, 3] = centroid_target - np.dot(Rot, centroid_source)#original function
return transformation_matrix
def transform_points(points, transform):
"""
Transform a set of 3D points using a 4x4 homogeneous transform.
Parameters
----------
points : numpy.ndarray, shape (N, 3)
Input 3D points.
transform : numpy.ndarray, shape (4, 4)
4x4 homogeneous transformation matrix.
Returns
-------
numpy.ndarray, shape (N, 3)
Transformed 3D points.
"""
# 1. Convert Nx3 points to Nx4 homogeneous coordinates by appending a column of 1s.
ones = np.ones((points.shape[0], 1), dtype=points.dtype)
points_hom = np.hstack([points, ones]) # Now shape is (N, 4)
# 2. Multiply by the 4x4 transformation matrix
# Note: We use transform.T for correct multiplication with row vectors
transformed_hom = points_hom @ transform.T # Still (N, 4)