Apply ratio test as per Lowe's paper to filter good matches
good_matches = []
for m, n in matches:
if m.distance < 0.75 * n.distance:
good_matches.append(m)
Extract location of good matches
if len(good_matches) >= 3: # At least 3 matches needed for affine transform
src_pts = np.float32([keypoints_1[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2)
dst_pts = np.float32([keypoints_2[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2)
code
# Compute affine transformation using RANSAC
M, mask = cv2.estimateAffinePartial2D(src_pts, dst_pts, method=cv2.RANSAC, ransacReprojThreshold=5.0)
# Get the inliers (mask will contain 1 for inliers and 0 for outliers)
inliers = mask.ravel().tolist()
# Print the result
print(f"Affine transformation matrix:\n{M}")
print(f"Number of inliers: {np.sum(mask)} out of {len(good_matches)} matches")
# Draw matches (optional)
matched_image = cv2.drawMatches(gray_image_1, keypoints_1, gray_image_2, keypoints_2, good_matches, None,
matchesMask=inliers, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
plt.imshow(matched_image)
plt.show()
Assistant
User
هیچ فرقی حاصل نشد
Assistant
اگر با اعمال تغییرات پیشنهادی تفاوتی حاصل نشد، مشکل ممکن است بهخاطر عواملی دیگر باشد که در عملکرد کد تأثیرگذار هستند. در ادامه به تعدادی از این عوامل و راهکارهای پیشنهادی برای کم کردن اختلاف بین تصاویر اشاره میشود:
تعداد و کیفیت ویژگیها:
اطمینان حاصل کنید که تصاویر به اندازه کافی ویژگیهای قابل توجه (مثل گوشهها، لبهها) دارند که برای الگوریتم SIFT قابل تشخیص باشند. شاید لازم باشد پارامترهای SIFT یا BFMatcher مانند نرمه Lowe's را تغییر دهید.
انتخاب درست ویژگیها:
پارامترهای BFMatcher و نیز تست نرمه (ratio test) را امتحان کنید. مثلاً میتوانید مقدار نرمه را از 0.75 به 0.7 یا 0.8 تغییر دهید و ببینید که آیا بهبود حاصل میشود یا خیر.
:
else:
print("Not enough matches are found - at least 3 are required.")
کد دوم: import cv2
import numpy as np
import matplotlib.pyplot as plt
Calculate and print the overall difference (sum of absolute differences)
total_difference = np.sum(difference_image)
print(f"Total difference between the two images: {total_difference}")
برای کاهش اختلاف بین دو تصویر نهایی که روی هم قرار میگیرند، شما میتوانید مطمئن شوید که ماتریس تبدیل آفین (Affine Transformation) که از کد اول به دست میآید، دقیقاً همان ماتریسی باشد که در کد دوم استفاده میکنید. همچنین، بهتر است مطمئن شوید که عملیات رنسانس و دیگر تنظیمات، هماهنگ باشند. در زیر تغییرات لازم در کدها آمده است:
کد اول:
ذخیره کردن ماتریس تبدیل آفین به دست آمده از کد اول تا بتوان از آن در کد دوم استفاده کرد.
python
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load the images (image 1 and image 2)
image_path_1 = '/content/bird/hw3/1.jpg'
image_path_2 = '/content/bird/hw3/2.jpg'
# Convert both images to grayscale
gray_image_1 = cv2.imread(image_path_1, cv2.IMREAD_GRAYSCALE)
gray_image_2 = cv2.imread(image_path_2, cv2.IMREAD_GRAYSCALE)
# Initialize SIFT detector
sift = cv2.SIFT_create()
# Detect keypoints and descriptors for both images
keypoints_1, descriptors_1 = sift.detectAndCompute(gray_image_1, None)
keypoints_2, descriptors_2 = sift.detectAndCompute(gray_image_2, None)
# Match keypoints using BFMatcher
bf = cv2.BFMatcher(cv2.NORM_L2)
matches = bf.knnMatch(descriptors_1, descriptors_2, k=2)
# Apply ratio test as per Lowe's paper to filter good matches
good_matches = []
for m, n in matches:
if m.distance < 0.75 * n.distance:
good_matches.append(m)
# Extract location of good matches
if len(good_matches) >= 3: # At least 3 matches needed for affine transform
src_pts = np.float32([keypoints_1[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2)
dst_pts = np.float32([keypoints_2[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2)
# Compute affine transformation using RANSAC
M, mask = cv2.estimateAffinePartial2D(src_pts, dst_pts, method=cv2.RANSAC, ransacReprojThreshold=5.0)
# Print and save the affine transformation matrix
print(f"Affine transformation matrix:\n{M}")
print(f"Number of inliers: {np.sum(mask)} out of {len(good_matches)} matches")
# Optionally save the transformation matrix to a file
np.save('/content/bird/hw3/affine_matrix.npy', M)
# Draw matches (optional)
matched_image = cv2.drawMatches(gray_image_1, keypoints_1, gray_image_2, keypoints_2, good_matches, None,
matchesMask=mask.ravel().tolist(), flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
plt.imshow(matched_image)
plt.show()
else:
print("Not enough matches are found - at least 3 are required.")
کد دوم:
بارگذاری ماتریس ذخیرهشده در کد دوم.
python
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load the images (image 1 and image 2)
image_path_1 = '/content/bird/hw3/1.jpg'
image_path_2 = '/content/bird/hw3/2.jpg'
# Read both images in grayscale
gray_image_1 = cv2.imread(image_path_1, cv2.IMREAD_GRAYSCALE)
gray_image_2 = cv2.imread(image_path_2, cv2.IMREAD_GRAYSCALE)
# Load the affine transformation matrix obtained from RANSAC
M = np.load('/content/bird/hw3/affine_matrix.npy')
# Get the size of the second image (target image)
height, width = gray_image_2.shape
# Apply the affine transformation to image 1
transformed_image_1 = cv2.warpAffine(gray_image_1, M, (width, height))
# Calculate the difference between the transformed image 1 and image 2
difference_image = cv2.absdiff(transformed_image_1, gray_image_2)
# Display the transformed image and difference image
plt.figure(figsize=(12, 6))
plt.subplot(1, 3, 1)
plt.title("Image 1 (Transformed)")
plt.imshow(transformed_image_1, cmap='gray')
plt.subplot(1, 3, 2)
plt.title("Image 2")
plt.imshow(gray_image_2, cmap='gray')
plt.subplot(1, 3, 3)
plt.title("Difference Image")
plt.imshow(difference_image, cmap='gray')
plt.show()
# Calculate and print the overall difference (sum of absolute differences)
total_difference = np.sum(difference_image)
print(f"Total difference between the two images: {total_difference}")
این تغییرات به اطمینان حاصل میکند که ماتریس تبدیل آفین دقیقاً همان باشد و در نتیجه تفاوت میان دو تصویر کاهش یابد.
تنظیم پروپژکتور RANSAC
مقدار ransacReprojThreshold را تغییر دهید. ممکن است با افزایش یا کاهش این مقدار خروجی بهتری بگیرید.
پیشپردازش تصویر:
تصاویر را قبل از پردازش نرمالسازی یا فیلتر کنید تا بازههای شدتی متفاوت کمتر تاثیر بگذارند.
میتوانید از Gaussian Blur یا روشهای دیگر برای کاهش نویز استفاده کنید.
تبدیل دقیقتر:
به جای cv2.estimateAffinePartial2D میتوانید از cv2.estimateAffine2D استفاده کنید تا تبدیل دقیقتری داشته باشید (البته به شرطی که تصاویر شما صرفاً تغییرات چرخشی و مقیاسی نداشته باشند).
تستی دیگر:
میتوانید دیگر الگوریتمهای تطبیق مانند ORB یا AKAZE را به جای SIFT امتحان کنید.
در نهایت، ممکن است تصاویر شما تغییرات زیاد در روشنایی، مقیاس یا پرسپکتیو داشته باشند که باعث میشود روشهای ساده آفین عملکرد مناسبی نداشته باشند. در این شرایط ممکن است نیاز به روشهای پیچیدهتری نظیر استفاده از Homography یا تطبیق غیرخطی باشد.