I have some python code to compare two images:
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)
But detector_DescriptorMatcher.knnMatch()
only works when k=1
. If k
has a different value than 1
, the following error is returned:
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
The error is caused by configuring BFMatcher
with crossCheck = True
. For k > 1
, set crossCheck = False
(constructor default).
From the docs:
If
crossCheck==true
, then theknnMatch()
method withk=1
will only return pairs(i,j)
such that fori-th
query descriptor thej-th
descriptor in the matcher’s collection is the nearest and vice versa, i.e. theBFMatcher
will only return consistent pairs. Such technique usually produces best results with minimal number of outliers when there are enough matches. This is alternative to the ratio test, used by D. Lowe in SIFT paper.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With