OpenCV:训练SVM错误 - 断言失败

时间:2016-03-10 19:11:59

标签: c++ opencv svm

我正在编写程序来使用SVM和BoW对对象进行分类。当我尝试使用TrainData :: create()成员函数来创建训练SVM分类器所需的数据时,我收到以下错误。

  

OpenCV错误:断言失败(response.type()== CV_32F || responses.type()== CV_32S)in setData

这是我从导演读取列车数据,计算每个列车图像的BoW直方图,创建矩阵中所有列车图像的所有描述符矩阵并创建列车数据,标签然后训练SVM的功能

void trainClassifier(string dictionaryPath, string trainDataPath, string saveClassifierPath, int samples){

//Write file
FileStorage readFile(dictionaryPath, FileStorage::READ);

//Load into Dictionary matrix
readFile["Data"] >> dictionary;

if(dictionary.empty() == false)
{
    cout << "Error loading visual vocalbulary" << endl;
}

//Set the Bow descripter with the dictionary
testBOW.setVocabulary(dictionary);

//Inititate variables
vector<KeyPoint> keypointTrain;
vector<DMatch> matchTrain;
Mat descriptorTrain;

//inputTrain -> input images, inputFeatures -> BoW descriptor output
Mat inputTrain;
Mat inputFeatures;

//Label array
vector<string> label;

//Create a string to read files from directory
string updatedDataPath;

for(int i = 1; i <= samples; i++)
{
    //Update the string updateDataPath to correspond the image FILENAME with each iteration
    updatedDataPath.append(trainDataPath);
    updatedDataPath += to_string(i);
    updatedDataPath.append(".JPEG");

    //Read FILE from the updated datapath
    inputTrain = imread(updatedDataPath);

    //Convert to single channel, since classifier takes only single channel data
    cvtColor(inputTrain, inputTrain, CV_BGR2GRAY);

    //Generate BoW features/histogram for the train image
    testBOW.compute(inputTrain, keypointTrain, inputFeatures);

    //Load the data in the descriptor Matrix
    descriptorTrain.push_back(inputFeatures);

    //Generate label according to the sample
    if(samples > 1 && samples <= 10)
    {
        label.push_back("OBJ1 POSSITIVE");
    }
    else if (samples > 11 && samples <= 20)
    {
        label.push_back("OBJ1 NEGATIVE");
    }

    //Reset data path
    updatedDataPath.clear();
}

//Convert the descriptor matrix into 32-pt float to make it compatible with classifier
if(descriptorTrain.type() != CV_32F)
{
    descriptorTrain.convertTo(descriptorTrain, CV_32F);
}

//Create train data using TrainData::create()
Ptr<TrainData> trainData = TrainData::create(descriptorTrain, ROW_SAMPLE, label);
//Iniitialize Support vector based classifier (SVM) to classify and detect object
Ptr<SVM>SVM = SVM::create();
SVM->setType(SVM::C_SVC);
SVM->setKernel(SVM::LINEAR);
SVM->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER, 100, 1e-6));

//Now train the SVM
SVM->trainAuto(trainData);
SVM->save(saveClassifierPath);

cout << "Classifier training status: SUCCESSFUL" << endl;}

感谢任何帮助。谢谢和欢呼:)

1 个答案:

答案 0 :(得分:1)

您使用order_items作为TrainData回复。

vector<string>

它应该是//Label array vector<string> label; // [long code] //Create train data using TrainData::create() Ptr<TrainData> trainData = TrainData::create(descriptorTrain, ROW_SAMPLE, label); MatCV_32F,如错误所示。

您可以在以下位置确认: