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()
结果:
相关推荐
dialect_1 天前
KMP算法
开发语言·c++·算法
总要学点什么1 天前
第89篇:三维特效-螺旋圆效果——让螺旋臂卷起一圈圈外扩的涟漪
开发语言·javascript·ecmascript·webgl·cesium·空间分析·1024程序员节
前端精髓1 天前
结构化输出with_structured_output(抽卡)
python·langchain
尹人入圣1 天前
目前热门的IP驱动产业新场景新工具
网络·python·网络协议·tcp/ip
开开心心_Every1 天前
快速隐藏程序工具自定义快捷键一键切换
java·开发语言·前端·spring·智能手机·word·intellij-idea
chenbingjie_c1 天前
C++ 多态完全指南:从虚函数重写到虚函数表原理
开发语言·c++
Nuanyt1 天前
Agent 学习笔记(下篇三):上线工程、进阶选择与操作界面(Stage 7 / 7.5 / 8 + 延伸路线)
笔记·python·学习·memory·aiagent·harness
吴卫斌1 天前
定投ETF实战指南(四):行业/主题ETF——定投的“进攻端“
开发语言·python·股票·量化
2601_967987371 天前
Python——入门级(定义功能def函数)
python·函数·可变参数·默认参数·关键字参数
超级架构师1 天前
PRAXO-CORE 2.5.0:用 conformance 和显式边界构建 Go Agent 框架
开发语言·人工智能·后端·golang·ai编程·智能体框架·praxo-core