Untitled
unknown
plain_text
a year ago
1.7 kB
8
Indexable
def sift(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 SIFT detector
sift = cv2.SIFT_create()
# Detect and compute keypoints and descriptors
keypoints1, descriptors1 = sift.detectAndCompute(img1, None)
keypoints2, descriptors2 = sift.detectAndCompute(img2, None)
# Initialize a brute-force matcher
bf = cv2.BFMatcher()
# Match descriptors
matches = bf.knnMatch(descriptors1, descriptors2, k=2)
# Apply ratio test
good_matches = []
for m, n in matches:
if m.distance < threshold * n.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_matchesEditor is loading...
Leave a Comment