python将两张图片对齐

时间:2024-05-10 08:14:37

目录

需要对齐的照片如下:

源码:

结果:


需要对齐的照片如下:

源码:
import cv2
import numpy as np
from matplotlib import pyplot as plt

# 读取两张图片
imgA = cv2.imread('./out/out/3.png')
imgB = cv2.imread('./out/out/4.jpg')

# 创建SIFT对象
sift = cv2.SIFT_create()

# 在两张图片中检测特征点和计算描述子
kp1, des1 = sift.detectAndCompute(imgA, None)
kp2, des2 = sift.detectAndCompute(imgB, None)

# 创建FLANN匹配器
FLANN_INDEX_KDTREE = 1
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(checks=50)
flann = cv2.FlannBasedMatcher(index_params, search_params)

# 使用k近邻算法进行特征匹配
matches = flann.knnMatch(des1, des2, k=2)

# 根据Lowe's ratio test选择最佳匹配
good_matches = []
for m, n in matches:
    if m.distance < 0.7 * n.distance:
        good_matches.append(m)

# 获取匹配的特征点的坐标
src_pts = np.float32([kp1[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2)
dst_pts = np.float32([kp2[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2)

# 计算透视变换矩阵
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)

# 应用透视变换将imgA对齐到imgB
aligned_img = cv2.warpPerspective(imgA, M, (imgB.shape[1], imgB.shape[0]))
cv2.imwrite('aligned_img.jpg', aligned_img)

plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1), plt.imshow(cv2.cvtColor(aligned_img, cv2.COLOR_BGR2RGB)), plt.title('Image A with Detected Changes')
plt.subplot(1, 2, 2), plt.imshow(cv2.cvtColor(imgB, cv2.COLOR_BGR2RGB)), plt.title('Original Image B')
plt.show()
结果: