OpenCV 3.0 正态贝叶斯分类器错误

Posted

技术标签:

【中文标题】OpenCV 3.0 正态贝叶斯分类器错误【英文标题】:OpenCV 3.0 Normal Bayes Classifier error 【发布时间】:2015-07-09 12:42:52 【问题描述】:

我正在尝试为一袋词创建分类器。我在这个网站 (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 X 代码 6:Thread 1:EXC_ARITHMETIC (code=EXC_i386_DIV, subcode=0x0)

【问题讨论】:

【参考方案1】:

请尝试更改

labels.push_back(label);

labels.push_back((int)label);

我在 SVM 训练中遇到了同样的问题,并意识到类标签必须是整数。

干杯!

【讨论】:

【参考方案2】:

只是为了分享我如何在我的 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);

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

【讨论】:

以上是关于OpenCV 3.0 正态贝叶斯分类器错误的主要内容,如果未能解决你的问题,请参考以下文章

贝叶斯分类器(1)贝叶斯决策论概述、贝叶斯和频率、概率和似然

我对贝叶斯分类器的理解

独家 | 一文读懂贝叶斯分类算法(附学习资源)

具有二进制数据的朴素贝叶斯分类器

数据挖掘-贝叶斯分类器

基于C++的朴素贝叶斯分类器