cv2.error: OpenCV(4.1.0) /home/pi/opencv/opencv-4.1.0/modules/features2d/src/bagofwords.cpp:55: error: (-215:Assertion failed) !_descriptors.empty() in function 'add'

asked 2019-11-26 13:59:12 -0600

updated 2019-12-09 08:08:47 -0600

Akhil Patel gravatar image

This is my project tree:

car_detector |-- detector.py |-- __init__.py |-- non_maximum.py |-- pyramid.py |-- README.md |-- sliding_window.py

This my code for detector.py:

import cv2
import numpy as np

datapath = '/home/pi/CarData/TrainImages'
SAMPLES = 400

def path(cls,i):
    return "%s/%s%d.pgm" % (datapath,cls,i+1)

def get_flann_matcher():
    flann_params = dict(algorithm = 1, trees = 5)
    return cv2.FlannBasedMatcher(flann_params, {})

def get_bow_extractor(extract,flann):
    return cv2.BOWImgDescriptorExtractor(extract, flann)

def get_extract_detect():
    return cv2.xfeatures2d.SIFT_create(), cv2.xfeatures2d.SIFT_create()

def extract_sift(fn,extractor,detector):
    im = cv2.imread(fn,0)
    return extractor.compute(im, detector.detect(im))[1]

def bow_features(img, extractor_bow, detector):
    return extractor_bow.compute(img, detector.detect(img))

def car_detector():
    pos, neg = "pos-", "neg-"
    detect, extract = get_extract_detect()
    flann = get_flann_matcher()
    print("Building BOWKMeansTrainer...")
    bow_kmeans_trainer = cv2.BOWKMeansTrainer(1000)
    extract_bow = cv2.BOWImgDescriptorExtractor(extract,flann)

    print("Adding features to trainer...")
    for i in range(SAMPLES):
        print(i)
        bow_kmeans_trainer.add(extract_sift(path(pos,i),extract,detect))
        bow_kmeans_trainer.add(extract_sift(path(neg,i),extract,detect))

    voc = bow_kmeans_trainer.cluster()
    extract_bow.setVocabulary(voc)

    traindata, trainlabels = [], []
    print("Adding to train data...")
    for i in range(SAMPLES):
        print(i)
        traindata.extend(bow_features(cv2.imread(path(pos,i),0), extract_bow, detect))
        trainlabels.append(1)
        traindata.extend(bow_features(cv2.imread(path(neg,i),0), extract_bow, detect))
        trainlabels.append(-1)

    svm = cv2.ml.SVM_create()
    cvm.setType(cv2.ml.SVM_C_SVC)
    svm.setGamma(0.5)
    svm.setC(30)
    svm.setKernel(cv2.ml.SVM_RBF)

    svm.train(np.array(traindata), cv2.ml.ROW_SAMPLE,np.array(trainlabels))
    return svm, extract_bow

I keep on getting this error:

bow_kmeans_trainer.add(extract_sift(path(neg,i),extract,detect))
cv2.error: OpenCV(4.1.0) /home/pi/opencv/opencv-4.1.0/modules/features2d/src/bagofwords.cpp:55: error: (-215:Assertion failed) !_descriptors.empty() in function 'add'

I know it's something to do with the the OpenCV I downloaded (OpenCV 4.1.0).

edit retag flag offensive close merge delete

Comments

!_descriptors.empty() in function 'add'

you try to feed empty SIFT descriptors to bow_kmeans_trainer.add.

please add checks, and avoid "nesting" functions

berak gravatar imageberak ( 2019-11-27 01:02:32 -0600 )edit