a b/utils/triangulation.py
1
# Given target 2D coordinates and camera matrices from two camera views,
2
# triangulate the target 3D coordinates
3
4
import numpy as np
5
import cv2 as cv
6
7
8
def to_homog(points):
9
    """
10
    Function: convert points from Euclidean coordinates to homogeneous coordinates
11
    points: 3xn numpy array containing Euclidean coordinates
12
    Return: 4xn numpy array containing homogeneous coordinates
13
    """
14
    m, n = points.shape
15
    points_homog = np.concatenate([points, np.ones([1, n])], axis=0)
16
    return points_homog
17
18
19
def from_homog(points_homog):
20
    """
21
    Function: convert points from homogeneous coordinates to Eulidean coordinates
22
    points_homog: 4xn numpy array containing homogeneous coordinates
23
    Return: 3xn numpy array containing Euclidean coordinates
24
    """
25
    m, n = points_homog.shape
26
    points = points_homog[:m-1] / points_homog[m-1]
27
    return points
28
29
30
def reconstruct(pts1, pts2, int1, int2, ext1, ext2):
31
    """
32
   Function: reconstruct 3D points with given correspondence
33
   int1, int2: intrinsic matrices of camera 1 and camera 2
34
   ext1, ext2: extrinsic matrices of camera 1 and camera 2
35
   Return: 3xn numpy arrays containing the Euclidean coordinates of reconstructed 3D points
36
   """
37
38
    I_0 = np.hstack((np.eye(3), np.zeros((3, 1))))
39
    proj1 = int1 @ I_0 @ ext1
40
    proj2 = int2 @ I_0 @ ext2
41
42
    homo_coor = cv.triangulatePoints(proj1, proj2, pts1, pts2)
43
44
    recon = from_homog(homo_coor)
45
    return recon
46
47