Skip to content

Instantly share code, notes, and snippets.

@n1ckfg
Created June 21, 2023 20:22
Show Gist options
  • Save n1ckfg/3f44bb0b3493ccaa3cc895bb4d308771 to your computer and use it in GitHub Desktop.
Save n1ckfg/3f44bb0b3493ccaa3cc895bb4d308771 to your computer and use it in GitHub Desktop.
# https://subscription.packtpub.com/book/data/9781788474443/9/ch09lvl1sec12/restoring-a-3d-point-from-two-observations-through-triangulation
import cv2
import numpy as np
# camera projection matrices
P1 = np.eye(3, 4, dtype=np.float32)
P2 = np.eye(3, 4, dtype=np.float32)
P2[0, 3] = -1
# tracked points
N = 5
points3d = np.empty((4, N), np.float32)
points3d[:3, :] = np.random.randn(3, N)
points3d[3, :] = 1
# project the 2D points to 3D and add noise
points1 = P1 @ points3d
points1 = points1[:2, :] / points1[2, :]
points1[:2, :] += np.random.randn(2, N) * 1e-2
points2 = P2 @ points3d
points2 = points2[:2, :] / points2[2, :]
points2[:2, :] += np.random.randn(2, N) * 1e-2
# reconstruct the points from the noisy observations
points3d_reconstr = cv2.triangulatePoints(P1, P2, points1, points2)
points3d_reconstr /= points3d_reconstr[3, :]
# results
print('Original points')
print(points3d[:3].T)
print('Reconstructed points')
print(points3d_reconstr[:3].T)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment