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()
结果:
相关推荐
喝茶与编码1 天前
Python异步并发控制:asyncio.gather 与 Semaphore 协同设计解析
后端·python
zone77391 天前
003:RAG 入门-LangChain 读取图片数据
后端·python·面试
用户8356290780511 天前
在 PowerPoint 中用 Python 添加和定制形状的完整教程
后端·python
用户962377954481 天前
🚀 docx2md-picgo:Word 文档图片一键上传图床工具
python·markdown
zone77392 天前
001:简单 RAG 入门
后端·python·面试
F_Quant2 天前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
允许部分打工人先富起来2 天前
在node项目中执行python脚本
前端·python·node.js
IVEN_2 天前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
haosend2 天前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽2 天前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac