python代码进行图像配准

这段代码演示了如何使用ORB特征检测器和特征匹配来进行图像配准。
图像配准是将两幅图像对齐,使得它们在同一空间中表现出相似的视觉内容。

一、效果图展示

二、代码

import cv2
import numpy as np

# 读取两张图像
# image1 是RGB  image2 是高光谱相机拍的伪RGB
# iamge1 和 iamge2 尺寸可以是不一样的
image1 = cv2.imread('datasets/image/ccc.bmp', cv2.IMREAD_COLOR)
image2 = cv2.imread('datasets/image/image.png', cv2.IMREAD_COLOR)
# 创建ORB特征检测器
orb = cv2.ORB_create()

# 在两张图像中寻找特征点
kp1, des1 = orb.detectAndCompute(image1, None)
kp2, des2 = orb.detectAndCompute(image2, None)

# 创建BF匹配器
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

# 特征匹配
matches = bf.match(des1, des2)

# 将匹配结果按照距离排序
matches = sorted(matches, key=lambda x: x.distance)

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

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

# 计算逆变换矩阵
M_inv = np.linalg.inv(M)

# 对第一张图像进行透视变换,映射到第二张图像上
result_gray = cv2.warpPerspective(image1, M, (image2.shape[1], image2.shape[0]))
print(result_gray.shape)
cv2.imshow('Cropped Area', result_gray)
cv2.waitKey(0)
cv2.destroyAllWindows()

# 将裁剪的结果保存为彩色图像
cv2.imwrite('datasets/image/cropped_area.jpg', result_gray)


你可能感兴趣的:(python,opencv,开发语言)