使用opencv 2.4.6.1和Python的SURF描述符

SURF descriptors with opencv 2.4.6.1 and Python

我正在使用Python和opencv进行SURF功能检测。 我在stackoverflow OpenCV 2.4.1上找到了这些示例-在Python中计算SURF描述符,但是不幸的是,它们无法与最新版本的opencv(即2.4.6.1)一起使用。 cv2.SURF.detect()命令必须已更改,因为它现在仅允许使用两个参数:

1
cv2.SURF.detect(image[, mask]) → keypoints?

这样我就可以获取关键点,但是如何获取描述符呢? 找不到解决方案。 希望你能在这里帮助我。 谢谢


根据Abid Rahman K在评论中发布的教程,我修改了此示例代码OpenCV 2.4.1-在Python中计算SURF描述符,因此它可以与opencv 2.4.6.1一起使用

获取SURF关键点和描述符的功能已更改为:

1
cv2.SURF.detectAndCompute(image, mask[, descriptors[, useProvidedKeypoints]]) → keypoints, descriptors

因此,这是链接的修改示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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)

# build feature detector and descriptor extractor
hessian_threshold = 5000
detector = cv2.SURF(hessian_threshold)
hkeypoints,hdescriptors = detector.detectAndCompute(hgrey,None)
nkeypoints,ndescriptors = detector.detectAndCompute(ngrey,None)

# extract vectors of size 64 from raw descriptors numpy arrays
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))
    #print hrows.shape, nrows.shape
else:
    hrows = numpy.array(hdescriptors, dtype = numpy.float32)
    nrows = numpy.array(ndescriptors, dtype = numpy.float32)
    rowsize = len(hrows[0])

# kNN training - learn mapping from hrow to hkeypoints index
samples = hrows
responses = numpy.arange(len(hkeypoints), dtype = numpy.float32)
#print len(samples), len(responses)
knn = cv2.KNearest()
knn.train(samples,responses)

# retrieve index and value through enumeration
for i, descriptor in enumerate(nrows):
    descriptor = numpy.array(descriptor, dtype = numpy.float32).reshape((1, rowsize))
    #print i, descriptor.shape, samples[0].shape
    retval, results, neigh_resp, dists = knn.find_nearest(descriptor, 1)
    res, dist =  int(results[0][0]), dists[0][0]
    #print res, dist

    if dist < 0.1:
        # draw matched keypoints in red color
        color = (0, 0, 255)
    else:
        # draw unmatched in blue color
        color = (255, 0, 0)
    # draw matched key points on haystack image
    x,y = hkeypoints[res].pt
    center = (int(x),int(y))
    cv2.circle(opencv_haystack,center,2,color,-1)
    # draw matched key points on needle image
    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()