Untitled
import cv2 import numpy as np def orb(image1_path, image2_path, threshold=0.25, ransac_threshold=3.0): # Load the images if isinstance(image1_path, str): img1 = cv2.imread(image1_path, cv2.IMREAD_GRAYSCALE) if isinstance(image2_path, str): img2 = cv2.imread(image2_path, cv2.IMREAD_GRAYSCALE) if isinstance(image1_path, np.ndarray): img1 = cv2.cvtColor(image1_path.astype('uint8'), cv2.COLOR_RGB2GRAY) if isinstance(image2_path, np.ndarray): img2 = cv2.cvtColor(image2_path.astype('uint8'), cv2.COLOR_RGB2GRAY) # Initialize ORB detector orb = cv2.ORB_create() # Detect and compute keypoints and descriptors keypoints1, descriptors1 = orb.detectAndCompute(img1, None) keypoints2, descriptors2 = orb.detectAndCompute(img2, None) # Initialize a brute-force matcher bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) # Match descriptors matches = bf.match(descriptors1, descriptors2) # Sort them in the order of their distance matches = sorted(matches, key=lambda x: x.distance) # Apply ratio test good_matches = [] for m in matches: if m.distance < threshold * matches[-1].distance: good_matches.append(m) # Convert keypoints to points src_pts = [keypoints1[m.queryIdx].pt for m in good_matches] dst_pts = [keypoints2[m.trainIdx].pt for m in good_matches] # Perform RANSAC for robustness if len(src_pts) >= 4: src_pts = np.float32(src_pts).reshape(-1, 1, 2) dst_pts = np.float32(dst_pts).reshape(-1, 1, 2) M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, ransac_threshold) mask_matches = mask.ravel().tolist() num_matches = sum(mask_matches) else: num_matches = 0 return num_matches
Leave a Comment