opencv多幅图像拼接python代码
时间: 2023-02-26 19:26:11 浏览: 132
opencv-python实现多张图像拼接源码
你可以尝试使用OpenCV的cv2.findHomography和cv2.warpPerspective函数来实现多幅图像拼接,下面是一个示例代码: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 = cv2.xfeatures2d.SIFT_create()
kp1, des1 = sift.detectAndCompute(gray1, None)
kp2, des2 = sift.detectAndCompute(gray2, None)
# 创建BFMatcher对象
bf = cv2.BFMatcher()
matches = bf.knnMatch(des1, des2, k=2)
# 根据特征点坐标,计算出全局匹配(Homography Matrix)
good = []
for m, n in matches:
if m.distance < 0.75 * n.distance:
good.append([m])
src_pts = np.float32([kp1[m[0].queryIdx].pt for m in good]).reshape(-1, 1, 2)
dst_pts = np.float32([kp2[m[0].trainIdx].pt for m in good]).reshape(-1, 1, 2)
H, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
# 使用仿射矩阵变换图片
dst = cv2.warpPerspective(img1, H, (img1.shape[1] + img2.shape[1], img1.shape[0]))
# 将两个图片拼接起来
dst[0:img2.shape[0], 0:img2.shape[1]] = img2
# 显示拼接的图片
cv2.imshow("dst", dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
阅读全文