v9.1.1
Menu

Hamming Distance Matcher

hardPROFeature DescriptorsFeaturesCV: Feature Detection and Matching

Implement feature matching using Hamming distance for binary descriptors. This task involves finding the best matches between two sets of binary feature descriptors.

The Hamming distance is a measure of the number of positions at which two binary strings differ, given by dH(a,b)=∑iai⊕bid_H(a, b) = \sum_{i} a_i \oplus b_i. It is used to compare the similarity between binary descriptors.

To perform matching:

  1. For each descriptor in set A, find the nearest neighbor in set B
  2. Apply the ratio test: accept if best_dist/second_best_dist<thresholdbest\_dist / second\_best\_dist < threshold
    • If desc2 has only one descriptor, there is no second best: always accept the match.
    • If the second-best distance is 00 (two or more exact matches), the match is ambiguous: reject it.
  3. Return matches as (idx1, idx2, distance) tuples with an integer distance, in the order of desc1.
dH(a,b)=∑iai⊕bid_H(a, b) = \sum_{i} a_i \oplus b_i

This technique is widely used in computer vision for feature matching and object recognition.

Example

Input
desc1 = [[1,0,1,0], [0,1,0,1]]
desc2 = [[1,0,1,1], [0,0,0,0], [0,1,0,1]]
ratio_threshold = 0.75
Output
[(0, 0, 1), (1, 2, 0)]
Reasoning
  • desc1 holds 2 descriptors and desc2 holds 3, each a row of D=4D = 4 bits. A match pairs a row of desc1 with its closest row of desc2, measured in differing bits.
  • Descriptor 0, a=[1,0,1,0]a = [1,0,1,0]: it differs from [1,0,1,1][1,0,1,1] only in the last bit (dH=1d_H = 1), from [0,0,0,0][0,0,0,0] in bits 0 and 2 (dH=2d_H = 2), and from [0,1,0,1][0,1,0,1] in all four (dH=4d_H = 4).
  • Best is 11 (row 0), second best is 22, so the ratio is 1/2=0.5<0.751/2 = 0.5 < 0.75 and the match (0, 0, 1) is accepted.
  • Descriptor 1, a=[0,1,0,1]a = [0,1,0,1]: the distances are 33, 22 and 00. Best is 00 (row 2), second best is 22, ratio 0/2=0<0.750/2 = 0 < 0.75, giving (1, 2, 0).
  • Each tuple is (index in desc1, index in desc2, integer bit count), listed in desc1 order.
  • Notice the ratio test rewards distinctiveness, not just closeness: had descriptor 0's runner-up also been at distance 1, the ratio 1/1=11/1 = 1 would reject it even though a 1-bit match exists.

Constraints

  • desc1: Binary descriptors from image 1 (N1, D)
  • desc2: Binary descriptors from image 2 (N2, D)
  • ratio_threshold: Ratio test threshold (default 0.75)
  • Return: List of (idx1, idx2, distance) matches

Learn this in

More from CV: Feature Detection and Matching

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.