match1to2与Opencv SIFT出错

时间:2018-01-02 15:24:14

标签: python opencv sift

我收到错误:

line 33, in <module>
img3 = cv2.drawMatches(img1,kp1,img2,kp2,matches,None,flags=2)
TypeError: Expected cv::DMatch for argument 'matches1to2'

当我尝试执行此代码时。它应该是SIFT中的简单图像比较并绘制匹配图。我以前有代码适用于ORB,但当我转换它为SIFT工作时,发生了这个错误。有人可以帮我解决这个问题吗?代码如下:

#import os
import sys
sys.path.append('/usr/local/lib/python2.7/site-packages')
import cv2
import time
import glob, os
import numpy as np
import matplotlib.pyplot as plt


img1 = cv2.imread("/home/undead/Documents/TestSpectro/test.png",0)
img2 = cv2.imread("/home/undead/Documents/LibrarySpectro/ThankYouAud.png",0)

sift = cv2.xfeatures2d.SIFT_create(3000)

kp1,des1 = sift.detectAndCompute(img1,None)
kp2,des2 = sift.detectAndCompute(img2,None)

bf = cv2.BFMatcher()

matches = bf.knnMatch(des1,des2,k=2)


good = []
for m,n in matches:
    if m.distance < 0.75 * n.distance:
        good.append([m])

#img3 = cv2.drawMatches(img1,kp1,img2,kp2,good,None,flags=2)
img3 = cv2.drawMatches(img1,kp1,img2,kp2,matches,None,flags=2)

plt.imshow(img3),plt.show()

更新 发现问题,有问题的行应该是:

img3 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,matches,None,flags=2)

1 个答案:

答案 0 :(得分:1)

(除了您的问题),在代码中应用了比率测试,但随后没有使用结果。您应该传递“好”而不是“匹配”作为参数。

对于您的问题,可以维护两个列表,例如

good = []
good_without_list = []

for m, n in matches:
    if m.distance < 0.75 * n.distance:
        good.append([m])
        good_without_list.append(m)

然后您可以使用

  • “ cv2.drawMatchesKnn”的“好”列表(在您的情况下)

    knn_image = cv2.drawMatchesKnn(img1, kp1, img2, kp2, good, None, flags=2)
    
  • “ cv2.drawMatches”的“ good_without_list”列表

    img3 = cv2.drawMatches(img1, kp1, img2, kp2, good_without_list, None, **draw_params)