【问题标题】:OpenCV 2.4.1 - computing SURF descriptors in PythonOpenCV 2.4.1 - 在 Python 中计算 SURF 描述符
【发布时间】:2012-06-14 14:33:24
【问题描述】:

我正在尝试更新我的代码以使用cv2.SURF(),而不是cv2.FeatureDetector_create("SURF")cv2.DescriptorExtractor_create("SURF")。但是,在检测到关键点后,我无法获取描述符。拨打SURF.detect的正确方法是什么?

我尝试按照 OpenCV 文档进行操作,但我有点困惑。这就是它在文档中所说的。

Python: cv2.SURF.detect(img, mask) → keypoints¶
Python: cv2.SURF.detect(img, mask[, descriptors[, useProvidedKeypoints]]) → keypoints, descriptors

第二次调用SURF.detect时如何传递关键点?

【问题讨论】:

    标签: python opencv computer-vision


    【解决方案1】:

    上述算法的一个改进是:

    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 = 85
    detector = cv2.SURF(hessian_threshold)
    (hkeypoints, hdescriptors) = detector.detect(hgrey, None, useProvidedKeypoints = False)
    (nkeypoints, ndescriptors) = detector.detect(ngrey, None, useProvidedKeypoints = False)
    
    # 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()
    

    您可以取消注释打印语句以更好地了解所使用的数据结构。

    【讨论】:

    • 您的代码看起来很有趣,但它对我不起作用。 python 解释器说第 27 行有一个错误:knn.train(samples,responses)。错误 (-209) 响应数组必须包含与函数 cvPreprocessOrderedResponses 中的样本总数一样的 man 元素。关于如何解决它的任何想法?谢谢!
    • 现在可以试试吗?我对使用更多类型的特征提取器进行了改进。
    • 它没有给出任何错误,但我也没有看到任何输出。对不起,我是opencv的新手……你能解释一下预期的输出是什么吗? (文件、控制台、窗口)。非常感谢!
    • 嘿,没问题。您可以用此代码替换 Abid Rahman K 显示的原始代码。现在我从那里添加了最后 4 行,所以只需再次复制整个 sn-p。
    【解决方案2】:

    我不确定我是否正确理解了您的问题。但是如果你正在寻找匹配 SURF 关键点的样本,下面是一个非常简单和基本的样本,它类似于模板匹配:

    import cv2
    import numpy as np
    
    # Load the images
    img =cv2.imread('messi4.jpg')
    
    # Convert them to grayscale
    imgg =cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    
    # SURF extraction
    surf = cv2.SURF()
    kp, descritors = surf.detect(imgg,None,useProvidedKeypoints = False)
    
    # Setting up samples and responses for kNN
    samples = np.array(descritors)
    responses = np.arange(len(kp),dtype = np.float32)
    
    # kNN training
    knn = cv2.KNearest()
    knn.train(samples,responses)
    
    # Now loading a template image and searching for similar keypoints
    template = cv2.imread('template.jpg')
    templateg= cv2.cvtColor(template,cv2.COLOR_BGR2GRAY)
    keys,desc = surf.detect(templateg,None,useProvidedKeypoints = False)
    
    for h,des in enumerate(desc):
        des = np.array(des,np.float32).reshape((1,128))
        retval, results, neigh_resp, dists = knn.find_nearest(des,1)
        res,dist =  int(results[0][0]),dists[0][0]
    
        if dist<0.1: # draw matched keypoints in red color
            color = (0,0,255)
        else:  # draw unmatched in blue color
            print dist
            color = (255,0,0)
    
        #Draw matched key points on original image
        x,y = kp[res].pt
        center = (int(x),int(y))
        cv2.circle(img,center,2,color,-1)
    
        #Draw matched key points on template image
        x,y = keys[h].pt
        center = (int(x),int(y))
        cv2.circle(template,center,2,color,-1)
    
    cv2.imshow('img',img)
    cv2.imshow('tm',template)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    以下是我得到的结果(使用绘画将粘贴的模板图像复制到原始图像上):

    如您所见,存在一些小错误。但对于初创公司来说,希望它是好的。

    【讨论】:

    • 感谢您的详细回复!我实际上已经完成了 SURF 匹配的完整实现,但是它是使用旧版本的 OpenCV 完成的。我正在寻找的是:surf.detect(imgg,None,useProvidedKeypoints = False)。非常感谢!帮助很大。
    • 惊人的答案。帮了我很多!
    • 将您的代码与我的图像一起使用我得到:OpenCV 错误:在 cvPreprocessOrderedResponses 中输入参数的大小不匹配(响应数组必须包含与样本总数一样多的元素)
    • 我在使用 OpenCV 2.3.1 时遇到了与上述相同的错误:对 knn.train(samples,responses) 的调用引发 OpenCV 错误:“输入参数的大小不匹配(响应数组必须包含与样本总数)”。
    猜你喜欢
    • 2016-03-16
    • 2011-06-22
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 2013-09-05
    • 2014-05-07
    • 2013-04-16
    • 1970-01-01
    相关资源
    最近更新 更多