使用ORB图像功能匹配时OpenCV python错误

时间:2014-07-29 14:54:20

标签: python-2.7 opencv image-processing feature-detection orb

我试图使用OpenCV ORB匹配两个图像,如this tutorial中所述。

这是我的代码:

import numpy as np
import cv2
import six
import pyparsing
import dateutil
from matplotlib import pyplot as plt
import timeit
import os
import sys

img1_path  = 'img1.jpg'
img2_path  = 'img2.jpg'

img1 = cv2.imread(img1_path,0) # queryImage
img2 = cv2.imread(img2_path,0) # trainImage

orb = cv2.ORB()

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

FLANN_INDEX_LSH = 6

index_params= dict(algorithm = FLANN_INDEX_LSH,
                   table_number = 6, # 12
                   key_size = 12,     # 20
                   multi_probe_level = 1) #2

search_params = dict(checks = 50)
flann = cv2.FlannBasedMatcher(index_params, search_params)

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

if len(matches)>0:
    print "%d total matches found" % (len(matches))
else:
    print "No matches were found - %d" % (len(good))
    sys.exit()

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

我用两张非常相似的图片运行这个脚本。在大多数情况下,脚本运行正常并找到匹配的关键点。

但是,在某些情况下,我收到此错误(它指的是最后三行代码):

Traceback (most recent call last):
    for m,n in matches:
ValueError: need more than 1 value to unpack

当img2显着小于img1的子图像时会发生这种情况。

(如果img2是原始图像,img1是修改过的图像,则表示有人在原始图像中添加了细节)。

如果我在文件名img1,img2之间切换,那么脚本运行没有问题。

必须是查询图像(img1)更小,还是等于火车图像(img2)?

1 个答案:

答案 0 :(得分:3)

必须检查匹配列表的每个成员是否确实存在两个邻居。这与图像尺寸无关。

good = []
for m_n in matches:
  if len(m_n) != 2:
    continue
  (m,n) = m_n
  if m.distance < 0.6*n.distance:
    good.append(m)