Introduction
Homography helps us match one picture to another by finding how one image can be shifted, rotated, or stretched to fit the other. This is useful to line up images taken from different angles.
Jump into concepts and practice - no test required
import cv2 import numpy as np # Find homography matrix homography_matrix, status = cv2.findHomography(src_points, dst_points, method=cv2.RANSAC) # Warp source image to align with destination image aligned_image = cv2.warpPerspective(source_image, homography_matrix, (width, height))
src_points = np.array([[10, 20], [50, 80], [90, 40], [120, 100]]) dst_points = np.array([[15, 25], [55, 85], [95, 45], [125, 105]]) homography_matrix, status = cv2.findHomography(src_points, dst_points, cv2.RANSAC)
src_points = np.array([]) dst_points = np.array([]) homography_matrix, status = cv2.findHomography(src_points, dst_points, cv2.RANSAC)
src_points = np.array([[10, 20]]) dst_points = np.array([[15, 25]]) homography_matrix, status = cv2.findHomography(src_points, dst_points, cv2.RANSAC)
import cv2 import numpy as np # Create two simple images with a square shifted source_image = np.zeros((200, 200), dtype=np.uint8) cv2.rectangle(source_image, (50, 50), (150, 150), 255, -1) # white square # Destination image has the square shifted and rotated angle = 10 # degrees M = cv2.getRotationMatrix2D((100, 100), angle, 1) destination_image = cv2.warpAffine(source_image, M, (200, 200)) # Define matching points manually (corners of the square) src_points = np.array([[50, 50], [150, 50], [150, 150], [50, 150]], dtype=np.float32) dst_points = cv2.transform(np.array([src_points]), M)[0] # Find homography matrix homography_matrix, status = cv2.findHomography(src_points, dst_points, cv2.RANSAC) # Warp source image to align with destination aligned_image = cv2.warpPerspective(source_image, homography_matrix, (200, 200)) # Check difference between aligned image and destination difference = cv2.absdiff(aligned_image, destination_image) # Print homography matrix and sum of difference pixels print("Homography matrix:") print(homography_matrix) print(f"Sum of absolute difference pixels: {np.sum(difference)}")
aligned_img after applying homography?
import cv2
import numpy as np
img1 = cv2.imread('img1.jpg')
img2 = cv2.imread('img2.jpg')
pts1 = np.array([[10,10],[100,10],[100,100],[10,100]])
pts2 = np.array([[12,14],[102,12],[98,110],[14,108]])
H, _ = cv2.findHomography(pts1, pts2)
aligned_img = cv2.warpPerspective(img1, H, (img2.shape[1], img2.shape[0]))H, status = cv2.findHomography(pts1, pts2) aligned = cv2.warpPerspective(img1, pts1, (img2.shape[1], img2.shape[0]))