This program creates a simple square image, rotates it to make a destination image, finds the homography, aligns the source to destination, and checks how close they are.
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)}")