- 下面是两张需要拼接的图片
- 完整代码:
import cv2
import numpy as np
import sys
def cv_show(name, img):
cv2.imshow(name, img)
cv2.waitKey(0)
def detectAndDescribe(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
descriptor = cv2.SIFT_create()
(kps, des) = descriptor.detectAndCompute(gray, None)
kps_float = np.float32([kp.pt for kp in kps])
return (kps, kps_float, des)
''' 读取拼接图片 '''
imageA = cv2.imread('A.jpg')
cv_show('imageA', imageA)
imageB = cv2.imread('B.jpg')
cv_show('imageB', imageB)
''' 计算图片特征点及描述符 '''
(kpsA, kps_floatA, desA) = detectAndDescribe(imageA)
(kpsB, kps_floatB, desB) = detectAndDescribe(imageB)
''' 建立暴力匹配器BFMatcher,在匹配大型训练集时使用 FlannBasedMatcher 速度更快 '''
matcher = cv2.BFMatcher()
rawMatches = matcher.knnMatch(desB, desA, 2)
good = []
matches = []
for m in rawMatches:
if len(m) == 2 and m[0].distance < 0.65 * m[1].distance:
good.append(m)
matches.append((m[0].trainIdx, m[0].queryIdx))
print(len(good))
print(matches)
vis = cv2.drawMatchesKnn(imageB, kpsB, imageA, kpsA, good, None, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
cv_show("Keypoint Matches", vis)
""" 透视变换 """
if len(matches) > 4: # 当筛选后的匹配对大于4时,计算视角变换矩阵
# 获取匹配对的点坐标
ptsA = np.float32([kps_floatA[i] for (i, _) in matches])
ptsB = np.float32([kps_floatB[i] for (_, i) in matches])
(H, mask) = cv2.findHomography(ptsB, ptsA, cv2.RANSAC, 10)
else:
print('图片未找到4个以上的匹配点')
sys.exit()
result = cv2.warpPerspective(imageB, H, (imageB.shape[1] + imageA.shape[1], imageB.shape[0]))
cv_show('resulB', result)
# 将图片A传入resultB图片最左端
result[0:imageA.shape[0], 0:imageA.shape[1]] = imageA
cv_show('result', result)
- 结果如下: