matcher.knnMatch() error: unsupported format or combination of formats

I was trying to simplify opencv/find_obj.py at 4.x · opencv/opencv · GitHub and make it use warpPerspective() and am now getting an error.

Before I share the error here’s the code:

import sys
import cv2

FLANN_INDEX_KDTREE = 1

def filter_matches(kp1, kp2, matches, ratio = 0.75):
  mkp1, mkp2 = [], []
  for m in matches:
    if len(m) == 2 and m[0].distance < m[1].distance * ratio:
      m = m[0]
      mkp1.append( kp1[m.queryIdx] )
      mkp2.append( kp2[m.trainIdx] )
  p1 = np.float32([kp.pt for kp in mkp1])
  p2 = np.float32([kp.pt for kp in mkp2])
  kp_pairs = zip(mkp1, mkp2)
  return p1, p2, list(kp_pairs)

def alignImages(im1, im2):
  detector = cv2.AKAZE_create()
  flann_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
  matcher = cv2.FlannBasedMatcher(flann_params, {})

  kp1, desc1 = detector.detectAndCompute(im1, None)
  kp2, desc2 = detector.detectAndCompute(im2, None)

  print('img1 - %d features, img2 - %d features' % (len(kp1), len(kp2)))

  raw_matches = matcher.knnMatch(desc1, trainDescriptors = desc2, k = 2)
  p1, p2, kp_pairs = filter_matches(kp1, kp2, raw_matches)
  if len(p1) < 4:
    print('%d matches found, not enough for homography estimation' % len(p1))
    sys.exit()

  height, width = im2.shape

  imResult = cv2.warpPerspective(im1, H, (width, height))

  return imResult

im = cv2.imread('ref.png', cv2.IMREAD_GRAYSCALE)
imRef = cv2.imread('new.png', cv2.IMREAD_GRAYSCALE)

imNew = alignImages(im, imRef)

cv2.imwrite('output.png', imNew)

Here’s the error:

Traceback (most recent call last):
  File "align.py", line 47, in <module>
    imNew = alignImages(im, imRef)
  File "align.py", line 32, in alignImages
    raw_matches = matcher.knnMatch(desc1, trainDescriptors = desc2, k = 2)
cv2.error: OpenCV(4.4.0) /tmp/pip-req-build-sw_3pm_8/opencv/modules/flann/src/miniflann.cpp:315: error: (-210:Unsupported format or combination of formats) in function 'buildIndex_'
> type=0
>

Any ideas?

The problem images are as follows:

htt­ps://www.terrafrost.com/new.png
htt­ps://www.terrafrost.com/ref.png

(copy / paste the URL from the www and on; this forum won’t let post the link as a clickable URL so I added a soft hyphen between the ht and tps; also, I can only upload one image - I can’t upload two)

have another look at the sample code:

FLANN_INDEX_KDTREE is for SIFT/SURF (L2 norm).
for AKAZE/ORB/BRIEF features(hamming distance) you need FLANN_INDEX_LSH

1 Like

Thanks for this, it worked for me. NOTE: just don’t forget to add FLANN_INDEX_LSH=6 before this code block.