An improvement of the above algorithm is:
import cv2
import numpy
opencv_haystack =cv2.imread('haystack.jpg')
opencv_needle =cv2.imread('needle.jpg')
ngrey = cv2.cvtColor(opencv_needle, cv2.COLOR_BGR2GRAY)
hgrey = cv2.cvtColor(opencv_haystack, cv2.COLOR_BGR2GRAY)
hessian_threshold = 85
detector = cv2.SURF(hessian_threshold)
(hkeypoints, hdescriptors) = detector.detect(hgrey, None, useProvidedKeypoints = False)
(nkeypoints, ndescriptors) = detector.detect(ngrey, None, useProvidedKeypoints = False)
rowsize = len(hdescriptors) / len(hkeypoints)
if rowsize > 1:
hrows = numpy.array(hdescriptors, dtype = numpy.float32).reshape((-1, rowsize))
nrows = numpy.array(ndescriptors, dtype = numpy.float32).reshape((-1, rowsize))
else:
hrows = numpy.array(hdescriptors, dtype = numpy.float32)
nrows = numpy.array(ndescriptors, dtype = numpy.float32)
rowsize = len(hrows[0])
samples = hrows
responses = numpy.arange(len(hkeypoints), dtype = numpy.float32)
knn = cv2.KNearest()
knn.train(samples,responses)
for i, descriptor in enumerate(nrows):
descriptor = numpy.array(descriptor, dtype = numpy.float32).reshape((1, rowsize))
retval, results, neigh_resp, dists = knn.find_nearest(descriptor, 1)
res, dist = int(results[0][0]), dists[0][0]
if dist < 0.1:
color = (0, 0, 255)
else:
color = (255, 0, 0)
x,y = hkeypoints[res].pt
center = (int(x),int(y))
cv2.circle(opencv_haystack,center,2,color,-1)
x,y = nkeypoints[i].pt
center = (int(x),int(y))
cv2.circle(opencv_needle,center,2,color,-1)
cv2.imshow('haystack',opencv_haystack)
cv2.imshow('needle',opencv_needle)
cv2.waitKey(0)
cv2.destroyAllWindows()
You can uncomment the print statements to get a better idea about the data structures used.
surf.detect(imgg,None,useProvidedKeypoints = False)
。非常感谢您!真是帮了大忙。 - Kkovknn.train(samples, responses)
会引发OpenCV错误:“输入参数的大小不匹配(响应数组必须包含与样本总数相同数量的元素)”。 - Moshe