Skip to content

knnSearch in Flann Index segfaults if used after leaving the local scope #17553

@EhsanKia

Description

@EhsanKia
  • OpenCV => 4.2.0.34
  • Operating System / Platform => Windows 32 Bit, Debian 64 bit
  • Compiler => precompiled manylinux/windows binaries, as well as manually compiled with g++
Detailed description

knnSearch on FLANN Index causes a segfault (windows and debian, 32bit and 64bit, precompiled and manually compiled) when using algorithm 0, 1, 2, 3 and 5 (not with algorithm 4), if you create the index in a function and return it, then use knnSearch in another method.

It seems to be a memory issue. With < around 20s images (~1000 features), it never segfaults, but as the number of images go up, the probability of segfault does too, and eventually at around 40 images/2000 features, it gets to 100%.

My uneducated guess is that some things are getting freed after we leave the function scope which shouldn't, and the more stuff you have loaded, the higher the probability of a GC run which wipes one of those variables that are needed.

Steps to reproduce
import cv2
import glob
import numpy

def create_index(feature):
    descriptors = []
    for filename in glob.glob('*.png')[:30]:  # Adjust this 30
        img = cv2.imread(filename)
        _, des = feature.detectAndCompute(img, None)
        descriptors.append(des)

    index_params = dict(algorithm=1)
    descriptor_array = numpy.concatenate(descriptors)
    print(descriptor_array.shape)
    flann = cv2.flann_Index(descriptor_array, index_params)
    return flann

feature = cv2.xfeatures2d.SURF_create()  # Same for SIFT and ORB
index = create_index(feature)
query_img = cv2.imread('barrel.png')
_, query_des = feature.detectAndCompute(query_img, None)
idx, _ = index.knnSearch(query_des, 1)  # <-- segfault
print('this line is never reached')

The images are these, but I believe any would do:
https://github.com/EhsanKia/CatalogScanner/tree/master/diys/generated

Issue submission checklist
  • [ X ] I report the issue, it's not a question
  • [ X ] I checked the problem with documentation, FAQ, open issues,
    answers.opencv.org, Stack Overflow, etc and have not found solution
  • [ X ] I updated to latest OpenCV version and the issue is still there
  • [ X ] There is reproducer code and related data files: videos, images, onnx, etc

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions