OpenCV中的warpPerspective与单应性矩阵无法配合使用。

3

我正在尝试使用OpenCV 3,特别是SIFT特征、findHomography和warpPerspective方法,以便在较大的图像2中找到图像1,然后对图像2进行透视变换,使其(几乎)等于图像1。

这是代码:

import numpy as np
import cv2 
from matplotlib import pyplot as plt 

MIN_MATCH_COUNT = 10

img1 = cv2.imread('box.png',0)          # queryImage
img2 = cv2.imread('box_in_scene.png',0) # trainImage

# Initiate SIFT detector
detector = cv2.xfeatures2d.SIFT_create()

# find the keypoints and descriptors with SIFT
kp1, des1 = detector.detectAndCompute(img1, None)
print("Image 1: # kps: {}, descriptors: {}".format(len(kp1), des1.shape))
kp2, des2 = detector.detectAndCompute(img2, None)
print("Image 2: # kps: {}, descriptors: {}".format(len(kp2), des2.shape))

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)

# store all the good matches as per Lowe's ratio test.
good = []
for m,n in matches:
    if m.distance < 0.7 * n.distance:
        good.append(m)

if len(good) > MIN_MATCH_COUNT:
    src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)
    dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)

    M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
else:
    print("Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT))

im_out = cv2.warpPerspective(img2, M, (img1.shape[1] * 2, img1.shape[0] * 2))
plt.imshow(im_out)
#plt.imshow(img2)
plt.show()

生成的图像略有变形,但不足以与img1相匹配。

以下是匹配结果和变形(?)结果。

匹配结果

变形(?)结果

1个回答

3

我解决了问题,我之前错了方向进行单应性矩阵计算。应该是这样的:

    M, mask = cv2.findHomography(dst_pts, src_pts, cv2.RANSAC, 5.0)

改为:

    M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)

Right warped result


只有在使用以下代码进行“warpPerspective”时,上述工作才有效:im_out = cv2.warpPerspective(img2, M, (img1.shape[1], img1.shape[0])) - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接