I have a problem with my code, in my warp perspective function when I warp the image,…
- User
I have a problem with my code, in my warp perspective function when I warp the image, the image gets aligned to left side from the interest point, what I mean is from the middle of the image however there is content on the left, so content is missing, it gets cut because it is on the negative part of the image. Can you make sure there is no content missing ? Also this might have something to do with how homography is calculated, since warp_perspective only warps perspective according to already calculated homography. Here is my full code: “import numpy as np import cv2 import os import glob import matplotlib.pyplot as plt import time from kayla_tools import
def compute_homography_matrix(src_pts, dst_pts): def normalize_points(pts): pts_homogeneous = np.hstack((pts, np.ones((pts.shape[0], 1)))) centroid = np.mean(pts, axis=0) scale = np.sqrt(2) / np.mean(np.linalg.norm(pts - centroid, axis=1)) T = np.array([[scale, 0, -scale * centroid[0]], [0, scale, -scale * centroid[1]], [0, 0, 1]]) normalized_pts = (T @ pts_homogeneous.T).T return normalized_pts[:, :2], T
src_pts_normalized, T1 = normalize_points(src_pts) dst_pts_normalized, T2 = normalize_points(dst_pts)
A = [] for p1, p2 in zip(src_pts_normalized, dst_pts_normalized): x1, y1 = p1 x2, y2 = p2 A.append([0, 0, 0, -x1, -y1, -1, y2 * x1, y2 * y1, y2]) A.append([x1, y1, 1, 0, 0, 0, -x2 * x1, -x2 * y1, -x2])
A = np.array(A) try: _, , VT = np.linalg.svd(A) except np.linalg.LinAlgError: return None
h = VT[-1]
H_normalized = h.reshape(3, 3) H = np.linalg.inv(T2) @ H_normalized @ T1
if np.abs(H[-1, -1]) > 1e-6: H = H / H[-1, -1] else: return None
return H
def filter_matches(matches, ratio_thres=0.7): filtered_matches = [] for match in matches: good_match = [] for m, n in match: if m.distance < ratio_thres * n.distance: good_match.append(m) filtered_matches.append(good_match)
return filtered_matches
def find_homography(keypoints, filtered_matches): homographies = [] skipped_indices = [] # Keep track of skipped images and their indices
for i, matches in enumerate(filtered_matches): src_pts = np.float32([keypoints[0][m.queryIdx].pt for m in matches]).reshape(-1, 1, 2) dst_pts = np.float32([keypoints[i + 1][m.trainIdx].pt for m in matches]).reshape(-1, 1, 2)
H = ransac_homography(src_pts, dst_pts)
if H is not None: H = H.astype(np.float32) homographies.append(H) else: print(f"Warning: Homography computation failed for image pair (0, {i + 1}). Skipping.") skipped_indices.append(i + 1) # Add indices of skipped images to the list continue
return homographies, skipped_indices
def ransac_homography(src_pts, dst_pts, iterations=2000, threshold=3): best_inlier_count = 0 best_homography = None
if len(src_pts) != len(dst_pts) or len(src_pts) < 4: raise ValueError(“The number of source and destination points must be equal and at least 4.”)
- Assistant