Created
March 19, 2023 11:43
-
-
Save DeathsPirate/3262d602281b64c055a84f88d3b45235 to your computer and use it in GitHub Desktop.
Image matching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import numpy as np | |
def calculate_differences(img1, img2): | |
# Initialization | |
detector = cv2.ORB_create() | |
descriptor = cv2.ORB_create() | |
matcher = cv2.DescriptorMatcher_create(cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_HAMMING) | |
# First image objects | |
img1_keypoints, img1_descriptors = detector.detectAndCompute(img1, None) | |
# Second image objects | |
img2_keypoints, img2_descriptors = detector.detectAndCompute(img2, None) | |
# Match KeyPoints | |
mat_of_d_match = matcher.match(img1_descriptors, img2_descriptors) | |
# Filtering the matches | |
d_match_list = mat_of_d_match | |
min_dist = 100 | |
max_dist = 0 | |
for i in range(len(img1_descriptors)): | |
dist = d_match_list[i].distance | |
min_dist = min(min_dist, dist) | |
max_dist = max(max_dist, dist) | |
good_matches = [m for m in d_match_list if m.distance < 3 * min_dist] | |
# Converting to MatOfPoint2f format | |
img1_points_list = [img1_keypoints[m.queryIdx].pt for m in good_matches] | |
img2_points_list = [img2_keypoints[m.trainIdx].pt for m in good_matches] | |
img1_point2f_mat = np.float32(img1_points_list) | |
img2_point2f_mat = np.float32(img2_points_list) | |
# Computing the affine transform matrix | |
result, _ = cv2.estimateAffine2D(img1_point2f_mat, img2_point2f_mat) | |
print_mat(result) # Printing the optimal affine transformation 2x3 array | |
# The following variables correspond to the estimateRigidTransform result as shown here: https://stackoverflow.com/a/29511091/5165833 | |
a = result[0, 0] | |
b = result[0, 1] | |
d = result[1, 1] | |
c = result[1, 0] | |
tx = result[0, 2] | |
ty = result[1, 2] | |
# Solving for scale, translation, and rotation as shown in the link above | |
scale_x = np.sign(a) * np.sqrt(a * a + b * b) # Axis x scale difference | |
scale_y = np.sign(d) * np.sqrt(c * c + d * d) # Axis y scale difference | |
translation = ty # The translation difference | |
rotation_angle = np.arctan2(c, d) # Rotation difference | |
# Printing results | |
print(f"Scale_x diff: {scale_x}") | |
print(f"Scale_y diff: {scale_y}") | |
print(f"Translation diff: {translation}") | |
print(f"Rotation diff: {rotation_angle}") | |
def print_mat(m): | |
for x in range(m.shape[0]): | |
for y in range(m.shape[1]): | |
print(f"{m[x, y]:.6f}", end=" ") | |
print() | |
# Example usage: | |
img1 = cv2.imread("path/to/image1.jpg", cv2.IMREAD_GRAYSCALE) | |
img2 = cv2.imread("path/to/image2.jpg", cv2.IMREAD_GRAYSCALE) | |
calculate_differences(img1, img2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment