opencv写一个图像拼接的代码
时间: 2024-02-07 07:03:16 浏览: 68
基于opencv的图像拼接代码(vc++)
5星 · 资源好评率100%
好的,以下是使用OpenCV实现图像拼接的示例代码:
```python
import cv2
import numpy as np
# 读取需要拼接的图像
img1 = cv2.imread('image1.jpg')
img2 = cv2.imread('image2.jpg')
# 将图像转换为灰度图
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# 使用SIFT算法检测特征点
sift = cv2.xfeatures2d.SIFT_create()
kp1, des1 = sift.detectAndCompute(gray1, None)
kp2, des2 = sift.detectAndCompute(gray2, None)
# 使用FLANN算法进行特征点匹配
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(checks=50)
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1, des2, k=2)
# 保留最佳匹配
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)
# 获取图像尺寸
h, w = gray1.shape
# 进行透视变换,使两幅图像拼接在一起
result = cv2.warpPerspective(img1, M, (w + img2.shape[1], h))
result[0:img2.shape[0], w:w + img2.shape[1]] = img2
# 显示结果
cv2.imshow('result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这个代码使用了SIFT算法检测特征点,FLANN算法进行特征点匹配,通过计算变换矩阵和透视变换实现了图像拼接。
阅读全文