Here is a step by step guideline to follow to complete your assignment:
- Import necessary libraries:
import cv2
import numpy as np
import os
import sys
import matplotlib.pyplot as plt
import time
from glob import glob
- Define the function for feature extraction using SIFT, SURF, or ORB:
def feature_extraction(method, image):
if method == "SIFT":
feature_extractor = cv2.SIFT_create()
elif method == "SURF":
feature_extractor = cv2.xfeatures2d.SURF_create()
elif method == "ORB":
feature_extractor = cv2.ORB_create()
else:
raise ValueError("Invalid feature extraction method.")
keypoints, descriptors = feature_extractor.detectAndCompute(image, None)
return keypoints, descriptors
- Define the function for feature matching using k-nearest neighbor:
def feature_matching(des1, des2, method, ratio=0.75):
if method == "SIFT" or method == "SURF":
matcher = cv2.BFMatcher(cv2.NORM_L2, crossCheck=False)
elif method == "ORB":
matcher = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=False)
else:
raise ValueError("Invalid feature extraction method.")
matches = matcher.knnMatch(des1, des2, k=2)
good_matches = [m[0] for m in matches if len(m) == 2 and m[0].distance < m[1].distance * ratio]
return good_matches
- Define your own RANSAC function for finding homography:
def find_homography_ransac(src_pts, dst_pts, threshold=5):
# Your own RANSAC implementation here
# Return best_homography
pass
- Define the function for merging images using homography:
def merge_images(img1, img2, H):
# Your own image merging implementation here
# Return panorama
pass
- Load the dataset:
dataset_path = "path_to_your_dataset"
image_paths = sorted(glob(os.path.join(dataset_path, "*.png")))
images = [cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) for image_path in image_paths]
- Run your code for each method and compare the performance:
methods = ["SIFT", "SURF", "ORB"]
for method in methods:
start_time = time.time()
# Feature extraction, matching, finding homography, and image merging steps here
runtime = time.time() - start_time
print(f"{method} runtime: {runtime}s")
# Display your results (plot keypoints, matching lines, panorama, etc.)
- Write your analysis about the results, comparing the runtime and the quality of constructed panoramas for each method (SIFT, SURF, and ORB).
This should be a good baseline to start your assignment. You can further improve your RANSAC and image merging implementations, and analyze the results. Good luck!
Sure! Here is a sample implementation for the find_homography_ransac and merge_images functions.
find_homography_ransac
def find_homography_ransac(src_pts, dst_pts, threshold=5, num_iterations=1000):
src_pts = np.array(src_pts)
dst_pts = np.array(dst_pts)
max_inliers = 0
best_homography = None
for _ in range(num_iterations):
# Randomly select 4 correspondence pairs
idxs = np.random.choice(src_pts.shape[0], 4, replace=False)
# Compute the homography
H, _ = cv2.findHomography(src_pts[idxs], dst_pts[idxs], method=0)
# Compute error for each point
src_pts_homogeneous = np.hstack((src_pts, np.ones((src_pts.shape[0], 1))))
mapped_pts = (src_pts_homogeneous @ H.T)
mapped_pts /= mapped_pts[:, -1][:, np.newaxis]
error = np.sqrt(np.sum((mapped_pts[:, :2] - dst_pts)**2, axis=1))
# Count inliers
inliers = error < threshold
num_inliers = np.sum(inliers)
# Update the best homography
if num_inliers > max_inliers:
max_inliers = num_inliers
best_homography = H
return best_homography
merge_images
def merge_images(img1, img2, H):
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
# Find coordinates of the corner points of both images after homography
coords_img1 = np.float32([[0,0], [0,h1], [w1,h1], [w1,0]]).reshape(-1, 1, 2)
coords_img2 = np.float32([[0,0], [0,h2], [w2,h2], [w2,0]]).reshape(-1, 1, 2)
coords_img2_trans = cv2.perspectiveTransform(coords_img2, H)
# Calculate size of the resulting panorama
result_coords = np.concatenate((coords_img1, coords_img2_trans), axis=0)
[xmin, ymin] = np.int32(result_coords.min(axis=0).ravel() - 0.5)
[xmax, ymax] = np.int32(result_coords.max(axis=0).ravel() + 0.5)
size = (xmax-xmin, ymax-ymin)
# Calculate the affine transformation to shift the image so that the result image completely contains both images
shift = np.array([[1, 0, -xmin], [0, 1, -ymin], [0,0,1]])
# Warp the second image with the new homography and copy the first image on the result image
panorama = cv2.warpPerspective(img2, shift @ H, size)
panorama[-ymin:h1-ymin, -xmin:w1-xmin] = img1
return panorama
These implementations should provide you with a reference for completing the assignment. You might want to adjust parameters, add some edge-case handling or further optimize the code according to your specific requirements. Remember, it's important to understand how the code works to be able to learn and explain your solution. Good luck!