OpenCV中的Flann KNN Matcher只返回一个点而不是一对

时间:2015-07-08 11:58:34

标签: python python-2.7 opencv flann

当我运行Flann KNN匹配器时,有时候KNN匹配器只返回一个点,因为依赖于两个点的匹配器之后的代码失败了:

flann = cv2.FlannBasedMatcher(index_params, search_params)

matches = flann.knnMatch(descriptors1, descriptors2, k=2)

# Retrieve good matches
good_matches = []

# ratio test as per Lowe's paper
for i, (m, n) in enumerate(matches):
    if m.distance < 0.7*n.distance:
        good_matches.append((m, n))

引发此错误:

Traceback (most recent call last):
  File "main.py", line 161, in <module>
    main(vid, video_file)
 ...
  File "main.py", line 73, in consume_for_homography_error
    matches = flann_matcher(descriptors1, descriptors2)
  File "main.py", line 48, in flann_matcher
    for i, (m, n) in enumerate(matches):
ValueError: need more than 1 value to unpack

这里似乎有什么问题?

3 个答案:

答案 0 :(得分:1)

有时,算法无法为查询图像中的单个描述符找到 2 个潜在匹配项。发生这种情况时,您可能只会在该索引的列表中获得 1 个或可能为零的 DMatch 项目。 如果列表中有一个 DMatch 条目,那么它就是该描述符的最佳条目,并且没有其他可与之比较的条目,因此我们应该简单地将其视为良好匹配。例如:

good = []
for i in range(0, len(matches)):
    if len(matches[i]) == 1:
        m = matches[i][0]
        good.append([m])
    if len(matches[i]) > 1:
        (m,n) = matches[i]
        if m.distance < 0.75*n.distance:
            good.append([m])

答案 1 :(得分:0)

knnMatch函数返回的匹配集合是 List 类型,其中每个元素又是2个DMatch对象的列表(因为k = 2)。因此,当您在匹配列表中应用枚举器时,您将在每次迭代中获得索引值和 List 对象。您的代码需要索引值和每次迭代中的元组。这就是问题所在。请查看以下代码。

flann = cv2.FlannBasedMatcher(index_params, search_params)

matches = flann.knnMatch(descriptors1, descriptors2, k=2)

# Retrieve good matches
good_matches = []

# ratio test as per Lowe's paper
for m,n in matches:
    if m.distance < 0.7*n.distance:
    good_matches.append((m, n))

答案 2 :(得分:0)

问题在于,匹配项似乎被填充为固定长度的列表列表,在这种情况下,len(matches) == 500即使找到的匹配项少于该数量。

尝试添加此内容:

matches = [match for match in matches if len(match) == 2]
(or even better)
good_matches = [match[0] for match in matches if len(match) == 2 and match[0].distance 
                                                        < .7*match[1].distance]


before the for loop to delete these (empty lists?).