OpenCV 3.0 Normal Bayes Classifier错误

时间:2015-07-09 12:42:52

标签: c++ opencv3.0

我正在尝试为一包单词创建一个分类器。我在这个网站(here)上发现了一个问题,帮助我将下面的代码放在一起,但我被classifier->train(trainingData,ml::ROW_SAMPLE, labels);困住了。本质上,程序运行正常,但当它到达这一行时,程序崩溃。显然,该线正在执行除零,因此崩溃。我查看了代码,但我无法找到错误。它可能是openCV 2的翻译错误 - > 3,不太确定。任何帮助将不胜感激!

#include <opencv2/core/core.hpp>
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <opencv2/ml.hpp>

#include <iostream>
#include <stdio.h>
#include <dirent.h>
#include <string.h>




using namespace std;
using namespace cv;

#define TRAINING_DATA_DIR "testImages/"
#define EVAL_DATA_DIR "evalImages/"


int dictSize = 1000;
TermCriteria tc(CV_TERMCRIT_ITER, 10, 0.001);
int retries = 1;
int flags = KMEANS_PP_CENTERS;

Ptr<FeatureDetector> detector = xfeatures2d::SURF::create();
Ptr<DescriptorExtractor> extractor = xfeatures2d::SURF::create();
Ptr<DescriptorMatcher> matcher = FlannBasedMatcher::create("FlannBased");



BOWKMeansTrainer bowTrainer(dictSize, tc, retries, flags);
BOWImgDescriptorExtractor bowDE(extractor, matcher);

void extractTrainingVocabulary(string path){
    struct dirent *de = NULL;
    DIR *d = NULL;
    d = opendir(path.c_str());

    if(d == NULL)
    {
        cerr << "Couldn't open directory" << endl;

    } else {
        // Add all the names of the files to be processed to a vector
        vector<string> files;
        while ((de = readdir(d))) {
            string nameOfFile(de->d_name);
            if ((strcmp(de->d_name,".") != 0) && (strcmp(de->d_name,"..") != 0)  && (strcmp(de->d_name,".DS_Store") != 0)) {
                files.push_back(nameOfFile);
            }
        }

        // Loop through all elements
        for (int f = 0; f < files.size(); f++){
            string fullPath = "./";
            fullPath += TRAINING_DATA_DIR;
            fullPath += files[f];

            cout << "[" << f+1 << "/" << files.size() << "]\tProcessing image: " << fullPath << endl;

            Mat input = imread(fullPath);
            if (!input.empty()){
                // Find all keypoints
                vector<KeyPoint> keypoints;
                detector->detect(input, keypoints);
                if (keypoints.empty()){
                    cerr << "Warning! could not find any keypoints in image " << fullPath << endl;
                } else {
                    // Extract the features
                    Mat features;
                    extractor->compute(input, keypoints, features);
                    // Add them to the trainer
                    bowTrainer.add(features);
                }
            } else {
                cerr << "Could not read image " << fullPath << endl;
            }
        }

    }
}

void extractBOWDescriptor(string path, Mat& descriptors, Mat& labels){
    struct dirent *de = NULL;
    DIR *d = NULL;
    d = opendir(path.c_str());

    if(d == NULL)
    {
        cerr << "Couldn't open directory" << endl;

    } else {
        // Add all the names of the files to be processed to a vector
        vector<string> files;
        while ((de = readdir(d))) {
            string nameOfFile(de->d_name);
            if ((strcmp(de->d_name,".") != 0) && (strcmp(de->d_name,"..") != 0)  && (strcmp(de->d_name,".DS_Store") != 0)) {
                files.push_back(nameOfFile);
            }
        }

        // Loop through all elements
        for (int f = 0; f < files.size(); f++){
            string fullPath = "./";
            fullPath += EVAL_DATA_DIR;
            fullPath += files[f];

            cout << "[" << f+1 << "/" << files.size() << "]\tProcessing image: " << fullPath << endl;

            Mat input = imread(fullPath);
            if (!input.empty()){
                // Find all keypoints
                vector<KeyPoint> keypoints;
                detector->detect(input, keypoints);
                if (keypoints.empty()){
                    cerr << "Warning! could not find any keypoints in image " << fullPath << endl;
                } else {
                    Mat bowDescriptor;
                    bowDE.compute(input, keypoints, bowDescriptor);
                    descriptors.push_back(bowDescriptor);
                    // Current file
                    string fileName = files[f];
                    // Strip extension
                    fileName.erase (fileName.end()-4, fileName.end());

                    float label = atof(fileName.c_str());
                    cout << "Filename: " << fileName << endl;

                    labels.push_back(label);
                }
            } else {
                cerr << "Could not read image " << fullPath << endl;
            }
        }

    }
}




int main(int argc, char ** argv) {
    // ============================ LEARN ============================
    cout << "Creating dict" << endl;
    extractTrainingVocabulary(TRAINING_DATA_DIR);




    vector<Mat> descriptors = bowTrainer.getDescriptors();

    int count=0;
    for(vector<Mat>::iterator iter=descriptors.begin();iter!=descriptors.end();iter++){
        count+=iter->rows;
    }

    cout << "Clustering " << count << " features. This might take a while..." << endl;

    Mat dictionary = bowTrainer.cluster();

    cout << "Writing to dict...";
    FileStorage fs("dict.yml",FileStorage::WRITE);
    fs << "vocabulary" << dictionary;
    fs.release();
    cout << "Done!" << endl;

    // =========================== EXTRACT ===========================
    // This will have to be loaded if we run it in two different instances
    bowDE.setVocabulary(dictionary);

    cout << "Processing training data..." << endl;
    Mat trainingData(0, dictSize, CV_32FC1);
    Mat labels(0,1,CV_32FC1);

    extractBOWDescriptor(EVAL_DATA_DIR, trainingData, labels);



    Ptr<ml::NormalBayesClassifier> classifier = ml::NormalBayesClassifier::create();

    if (trainingData.data == NULL || labels.data == NULL){
        cerr << "Mats are NULL!!" << endl;
    } else {
      classifier->train(trainingData,ml::ROW_SAMPLE, labels);
    }
//#warning Not yet tested
//    cout << "Processing evaluation data" << endl;
//    Mat evalData(0,dictSize,CV_32FC1);
//    Mat groundTruth(0,1,CV_32FC1);
//    extractBOWDescriptor(EVAL_DATA_DIR, evalData, groundTruth);

    return 0;
}

修改

这里要求的是错误。

  • 通过终端:Floating point exception: 8
  • XCode 6:Thread 1:EXC_ARITHMETIC (code=EXC_i386_DIV, subcode=0x0)

2 个答案:

答案 0 :(得分:0)

请尝试更改

labels.push_back(label);

labels.push_back((int)label);

我遇到了与SVM培训相同的问题,并意识到类标签必须是整数。

干杯!

答案 1 :(得分:0)

分享我在os x项目中解决同样问题的方法。

显然,包含标签的矩阵似乎也是我项目中的问题。出于某些奇怪的原因,以任何其他方式创建矩阵,或者将矩阵类型转换为int,这对我来说不起作用。

问题只能通过遵循OpenCV 3.0.0 SVM教程的示例代码初始化其标签矩阵的方式来解决。 OpenCV SVM tutorial

过去了:

int labels[4] = {1, -1, -1, -1};
Mat labelsMat(4, 1, CV_32SC1, labels);

在我将标签矩阵更改为从整数标签数组中初始化之后,错误就消失了。