knnMatch不适用于K!= 1

时间:2015-11-03 10:55:27

标签: python opencv

我有一些python代码来比较两个图像:

 detector_FeatureDetector_1 = cv2.FastFeatureDetector_create()
 detector_FeatureDetector_2 = cv2.FastFeatureDetector_create()   
 detector_DescriptorExtractor_1 = cv2.BRISK_create()
 detector_DescriptorExtractor_2 = cv2.BRISK_create()
 detector_DescriptorMatcher_1 = cv2.BFMatcher(cv2.NORM_HAMMING2, crossCheck = True)
 detector_DescriptorMatcher_2 = cv2.BFMatcher(cv2.NORM_HAMMING2, crossCheck = True)
 image_1 = cv2.imread('/Users/rui/image1.png')
 image_2 = cv2.imread('/Users/rui/image2.png')
 obj_descriptor_keypoints_1 = detector_FeatureDetector.detect(image_1)
 obj_descriptor_keypoints_2 = detector_FeatureDetector.detect(image_2)
 keypoints1, obj_descriptor_descriptors_1 = detector_DescriptorExtractor.compute(image_1, obj_descriptor_keypoints_1)
 keypoints2, obj_descriptor_descriptors_2 = detector_DescriptorExtractor.compute(image_2, obj_descriptor_keypoints_2)
 matches = detector_DescriptorMatcher.knnMatch(obj_descriptor_descriptors_1, obj_descriptor_descriptors_2, k=6)

detector_DescriptorMatcher.knnMatch()仅适用于k=1。如果k的值与1不同,则会返回以下错误:

OpenCV Error: Assertion failed (K == 1 && update == 0 && mask.empty()) in batchDistance, file /opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_tarballs_ports_graphics_opencv/opencv/work/opencv-3.0.0/modules/core/src/stat.cpp, line 3682

Traceback (most recent call last):
  File "/Users/rui/main.py", line 191, in <module>

matches = detector_DescriptorMatcher.knnMatch(obj_descriptor_descriptors, obj_descriptor_descriptors_movie_frame, k=6)

cv2.error: /opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_tarballs_ports_graphics_opencv/opencv/work/opencv-3.0.0/modules/core/src/stat.cpp:3682: error: (-215) K == 1 && update == 0 && mask.empty() in function batchDistance

1 个答案:

答案 0 :(得分:7)

使用extension NSManagedObject { func safeSetValue(value : AnyObject, forKey key : String) -> Bool { // Get NSAttributeDescription for key: guard let attr = self.entity.attributesByName[key] else { return false } // Get name of the class used to represent the attribute: guard let cname = attr.attributeValueClassName else { return false } // Create class object from name: guard let cls : AnyClass = NSClassFromString(cname) else { return false } // Check if given value is an instance of a subclass: if !value.isKindOfClass(cls) { return false } // Finally: Set value for key: self.setValue(value, forKey: key) return true } } 配置BFMatcher会导致错误。对于crossCheck = True,请设置k > 1(构造函数默认值)。

来自docs

  

如果crossCheck = False,那么带有crossCheck==true的{​​{1}}方法只返回knnMatch()对,以便k=1查询描述符(i,j)描述符在匹配器的集合中是最接近的,反之亦然,即i-th将只返回一致的对。当有足够的匹配时,这种技术通常产生最佳结果,并且具有最少数量的异常值。这是D. Lowe在SIFT论文中使用的比率测试的替代方案。