Skip to content

Instantly share code, notes, and snippets.

@sdshmkh
Last active November 21, 2024 17:52
Show Gist options
  • Save sdshmkh/46827ad74cb9ec662975c40488de3c7c to your computer and use it in GitHub Desktop.
Save sdshmkh/46827ad74cb9ec662975c40488de3c7c to your computer and use it in GitHub Desktop.
Find Homography
def find_homography(X, X_dash):
'''
Given a set of N correspondences of the form [x,y] and [x',y'], fit homography.
'''
equations = []
num_points = X.shape[0]
for i in range(num_points):
x, y = X[i, 0], X[i, 1] # Original points
x_dash, y_dash = X_dash[i, 0], X_dash[i, 1] # Transformed points
# First row for the equation
equations.append([x, y, 1, 0, 0, 0, -x_dash * x, -x_dash * y, -x_dash])
# Second row for the equation
equations.append([0, 0, 0, x, y, 1, -y_dash * x, -y_dash * y, -y_dash])
A = np.vstack(equations)
U,S,V_t = np.linalg.svd(A)
H = V_t[-1,:].reshape(3,3)
# Normalize to make H[2, 2] = 1
H = H/H[2,2]
return H
def homogenous_transform(X, H):
'''
Apply the Homography matrix on given set of points and calculate the projected points
'''
num_points = X.shape[0]
homogeneous_points = np.hstack([X, np.ones((num_points, 1))]) # Convert to homogeneous
warped_points = np.dot(homogeneous_points, H.T) # Apply homography
return warped_points[:, :2] / warped_points[:, 2] # Normalize back to cartesian
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment