如何基于若干匹配点对将存在角度差异的两张图像重叠对齐显示
实现方案
你需要先基于匹配点对计算两张图像之间的几何变换矩阵,对其中一张图像做对应变换后再调整透明度叠加即可,具体实现如下:
首先安装所需依赖:
pip install opencv-python numpy pillow
完整实现代码:
import cv2 import numpy as np from PIL import Image # 读入两张图像 img1 = Image.open('Rutland.jpg') img2 = Image.open('Rutland2.jpg') point_matches = [((1988, 1029), (2003, 1045)), ((4091, 3901), (4085, 3896))] # 提取匹配点转为numpy数组 src_pts = np.array([p[0] for p in point_matches], dtype=np.float32) dst_pts = np.array([p[1] for p in point_matches], dtype=np.float32) # 计算相似变换矩阵(支持旋转、平移、缩放,适配2对匹配点场景) transform_matrix, _ = cv2.estimateAffinePartial2D(src_pts, dst_pts) # 将img2转为opencv格式做变换 img2_cv = cv2.cvtColor(np.array(img2), cv2.COLOR_RGB2BGR) # 变换图像,尺寸和img1保持一致 h, w = img1.size[1], img1.size[0] warped_img2_cv = cv2.warpAffine(img2_cv, transform_matrix, (w, h)) # 转回PIL格式 warped_img2 = Image.fromarray(cv2.cvtColor(warped_img2_cv, cv2.COLOR_BGR2RGB)) # 调整img2透明度后叠加 warped_img2.putalpha(int(255 * 0.5)) # 0.5为透明度,可自行调整 result = Image.alpha_composite(img1.convert('RGBA'), warped_img2.convert('RGBA')) # 保存或显示结果 result.save('aligned_overlay.png') result.show()
补充说明
- 如果你有3对及以上匹配点,可以将变换计算替换为
cv2.getAffineTransform(src_pts[:3], dst_pts[:3]),可以支持斜切等更复杂的仿射变换;如果匹配点超过4对,可使用cv2.findHomography计算单应性矩阵,适配存在视角变化的场景 - 若不需要保留原图全部区域,也可根据实际需求调整
cv2.warpAffine的输出尺寸参数 - 透明度参数可根据视觉效果自行调整,数值越小叠加后的第二张图越透明
内容的提问来源于stack exchange,提问作者Collin Giguere
相关产品推荐
相关产品推荐

