2013-09-09 4 views
0

Я пытаюсь сделать следующий код Mohammad Reza Mostajabi (http://alum.sharif.ir/~mostajabi/Tutorial.html) под Ubuntu 12.04 с OpenCV 2.4.6.1. Я внес некоторые незначительные изменения с включенными библиотеками и добавил «cv :: initModule_nonfree()» сразу после запуска основного файла.Код OpenCV - C++ работает в Eclipse, но не в терминале?

#include "cv.h" 
#include "highgui.h" 
#include "ml.h" 
#include <stdio.h> 
#include <iostream> 
#include <opencv2/features2d/features2d.hpp> 
#include <opencv2/imgproc/imgproc.hpp> 
#include <opencv2/highgui/highgui.hpp> 
#include <opencv2/nonfree/nonfree.hpp> 
#include <vector> 

using namespace cv; 
using namespace std; 

using std::cout; 
using std::cerr; 
using std::endl; 
using std::vector; 






char ch[30]; 

//--------Using SURF as feature extractor and FlannBased for assigning a new point to the nearest one in the dictionary 
Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create("FlannBased"); 
Ptr<DescriptorExtractor> extractor = new SurfDescriptorExtractor(); 
SurfFeatureDetector detector(500); 
//---dictionary size=number of cluster's centroids 
int dictionarySize = 1500; 
TermCriteria tc(CV_TERMCRIT_ITER, 10, 0.001); 
int retries = 1; 
int flags = KMEANS_PP_CENTERS; 
BOWKMeansTrainer bowTrainer(dictionarySize, tc, retries, flags); 
BOWImgDescriptorExtractor bowDE(extractor, matcher); 



void collectclasscentroids() { 
    IplImage *img; 
    int i,j; 
    for(j=1;j<=4;j++) 
    for(i=1;i<=60;i++){ 
     sprintf(ch,"%s%d%s%d%s","train/",j," (",i,").jpg"); 
        const char* imageName = ch; 
        img = cvLoadImage(imageName,0); 
        vector<KeyPoint> keypoint; 
        detector.detect(img, keypoint); 
        Mat features; 
        extractor->compute(img, keypoint, features); 
        bowTrainer.add(features); 
    } 
return; 
} 



int main(int argc, char* argv[]) 
{ 
    cv::initModule_nonfree(); 
    int i,j; 
    IplImage *img2; 
    cout<<"Vector quantization..."<<endl; 
    collectclasscentroids(); 
    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"<<endl; 
    //choosing cluster's centroids as dictionary's words 
    Mat dictionary = bowTrainer.cluster(); 
    bowDE.setVocabulary(dictionary); 
    cout<<"extracting histograms in the form of BOW for each image "<<endl; 
    Mat labels(0, 1, CV_32FC1); 
    Mat trainingData(0, dictionarySize, CV_32FC1); 
    int k=0; 
    vector<KeyPoint> keypoint1; 
    Mat bowDescriptor1; 
    //extracting histogram in the form of bow for each image 
for(j=1;j<=4;j++) 
    for(i=1;i<=60;i++){ 


        sprintf(ch,"%s%d%s%d%s","train/",j," (",i,").jpg"); 
        const char* imageName = ch; 
        img2 = cvLoadImage(imageName,0); 

        detector.detect(img2, keypoint1); 


         bowDE.compute(img2, keypoint1, bowDescriptor1); 

         trainingData.push_back(bowDescriptor1); 

         labels.push_back((float) j); 
    } 



    //Setting up SVM parameters 
    CvSVMParams params; 
    params.kernel_type=CvSVM::RBF; 
    params.svm_type=CvSVM::C_SVC; 
    params.gamma=0.50625000000000009; 
    params.C=312.50000000000000; 
    params.term_crit=cvTermCriteria(CV_TERMCRIT_ITER,100,0.000001); 
    CvSVM svm; 



    printf("%s\n","Training SVM classifier"); 

    bool res=svm.train(trainingData,labels,cv::Mat(),cv::Mat(),params); 

    cout<<"Processing evaluation data..."<<endl; 


    Mat groundTruth(0, 1, CV_32FC1); 
    Mat evalData(0, dictionarySize, CV_32FC1); 
    k=0; 
    vector<KeyPoint> keypoint2; 
    Mat bowDescriptor2; 


    Mat results(0, 1, CV_32FC1);; 
    for(j=1;j<=4;j++) 
    for(i=1;i<=60;i++){ 


        sprintf(ch,"%s%d%s%d%s","eval/",j," (",i,").jpg"); 
        const char* imageName = ch; 
        img2 = cvLoadImage(imageName,0); 

        detector.detect(img2, keypoint2); 
         bowDE.compute(img2, keypoint2, bowDescriptor2); 

         evalData.push_back(bowDescriptor2); 
         groundTruth.push_back((float) j); 
         float response = svm.predict(bowDescriptor2); 
         results.push_back(response); 
    } 



    //calculate the number of unmatched classes 
    double errorRate = (double) countNonZero(groundTruth- results)/evalData.rows; 
    printf("%s%f","Error rate is ",errorRate); 
    return 0; 

} 

После этого я могу скомпилировать код без проблем. Я также могу запустить его в Eclipse, но как только я попытаюсь заставить его работать на терминале, я получаю следующее сообщение об ошибке:

«Ошибка OpenCV: утверждение не выполнено (! _descriptors.empty()) в файле add/file/home/mark/Downloads/FP/opencv-2.4.6.1/modules/features2d/src/bagofwords.cpp, строка 57 завершение вызова после вызова экземпляра 'cv :: Exception' what():/home/mark/Downloads/FP/opencv-2.4.6.1/modules/features2d/src/bagofwords.cpp: 57: error: (-215)! _descriptors.empty() в функции add "

Я пытался решить проблему для через несколько дней, но я просто не могу избавиться от этой ошибки. Я также пытался сделать это с помощью CodeBlocks, что дает мне ту же ошибку. Я был бы очень признателен за помощь!

Спасибо!

ответ

0

Возможно, ваша программа не может загружать входные изображения (при запуске из окна терминала), потому что не может их найти. Убедитесь, что ваши входные изображения скопированы в каталог, из которого вы запускаете приложение. Eclipse может иметь другой домашний каталог и, следовательно, он видит изображение, когда программа запускается в Eclipse.

+0

Большое спасибо! Это была проблема. Он работает сейчас :) – user2746420