我将尝试使用OpenCV ORB算法来匹配两张图片,具体步骤可以参考这个教程。以下是我的代码:
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)小或相等吗?