batch_distance.cpp:274: error: (-215:Assertion failed)

Question:

` I have the following code :


import cv2 
import os
from os import listdir
import numpy as np
from PIL import Image
from tabulate import tabulate
import itertools


#sift
sift = cv2.SIFT_create()

#feature matching
bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)

# get the path/directory
folder_dir = "./runs/myDetect/SIFT"

col_names = []
data = []
all_keypoints = []
all_descriptors = []

for image in os.listdir(folder_dir):

    
    # check if the image ends with png or jpg or jpeg
    if (image.endswith(".png") or image.endswith(".jpg") or image.endswith(".jpeg")):
        
        col_names = ["KeyPoints lenght", "Numbers", "Keypoints"]

        opened_img = np.array(Image.open(folder_dir + image))
        
        gray_img= cv2.cvtColor(opened_img, cv2.COLOR_BGR2GRAY)
        keypoints, descriptors = sift.detectAndCompute(gray_img, None)
        data.append([image, len(keypoints)])
        all_keypoints.append([image, keypoints])
        all_descriptors.append([descriptors]) #all_descriptors.append([image, descriptors])

print(tabulate(data, headers=col_names, tablefmt="fancy_grid"))

         
for a, b in itertools.combinations(all_descriptors, 2):

    a=np.array(a).astype('uint8')
    print(type(a))
    b=np.array(b).astype('uint8')
    print(type(b))
    if type(a)!=type(None) and type(b)!=type(None) :

        if a or b is None:
          print(False)

        matches = bf.match(a,b)
        matches = sorted(matches, key = lambda x:x.distance)

cv2.waitKey(1)
cv2.destroyAllWindows() 


I am trying to find similarities between 2 images on the same file. I am using SIFT. Output of SIFT are keypoints and descriptor. I created a list named all_descriptors and for each image I add new descriptor to this list. Finally, I want to compare this descriptors between each other. On this part matches = bf.match(a,b) of the code, I receive following error : `matches = bf.match(a,b)
cv2.error: OpenCV(4.6.0) /io/opencv/modules/core/src/batch_distance.cpp:274: error: (-215:Assertion failed) type == src2.type() && src1.cols == src2.cols && (type == CV_32F || type == CV_8U) in function ‘batchDistance’. What is the solution? How can I compare 2 images in the same file?

Asked By: HusCet

||

Answers:

Please try the same code with steps in below

  1. all_descriptors.append(descriptors)
  2. a=np.array(a).astype(‘float32’)
Answered By: tgr