python将两张图片对齐

目录

需要对齐的照片如下:

源码:

结果:


需要对齐的照片如下:
源码:
python 复制代码
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()
结果:
相关推荐
charlie1145141915 分钟前
通用GUI编程技术——Win32 原生编程实战(十六)——Visual Studio 资源编辑器使用指南
开发语言·c++·ide·学习·gui·visual studio·win32
wheelmouse77881 小时前
网络排查基础与实战指南:Ping 与 Telnet
开发语言·网络·php
敲代码的嘎仔1 小时前
Java后端开发——真实面试汇总(持续更新)
java·开发语言·程序人生·面试·职场和发展·八股
迈巴赫车主1 小时前
蓝桥杯20560逃离高塔
java·开发语言·数据结构·算法·职场和发展·蓝桥杯
dulu~dulu2 小时前
算法---寻找和为K的子数组
笔记·python·算法·leetcode
编程之升级打怪2 小时前
用Python语言实现简单的Redis缓冲数据库驱动库
redis·python
春日见2 小时前
E2E自驾规控30讲:导论
开发语言·驱动开发·git·matlab·计算机外设
wangchunting2 小时前
Jvm-垃圾收集器
java·开发语言·jvm
沐知全栈开发2 小时前
PHP Math: 精通PHP中的数学函数与应用
开发语言
吴声子夜歌2 小时前
JavaScript——call()、apply()和bind()
开发语言·前端·javascript