im learning about SVM, so im making a sample program that trains an SVM to detect if a symbol is in an image or if its not. All the images are black and white (the symbols would be black and the background white). I have 12 training images, 6 positives (with the symbol) and 6 negatives (without it). Im using
hu moments
to get the descriptors of every image and then i construct the training matrix with those descriptors. also i have a
Labels
matrix, which contains a label for each image: 1 if its positive and 0 if it
s negative. but im getting an error (something like a segmentation fault) at the line where i train the SVM. here is my code:
using namespace cv;
using namespace std;
int main(int argc, char* argv[])
{
float labels[12] ;
float trainingData[12][7] ;
Moments moment;
double hu[7];
for ( int i = 0; i <= 5; i++){
std::string path("train/t");
path += std::to_string(i);
path += ".png";
Mat input = imread(path, 0);
bitwise_not(input, input);
Mat BinaryInput;
threshold(input, BinaryInput, 100, 255, cv::THRESH_BINARY);
moment = moments(BinaryInput, true);
HuMoments(moment, hu);
for (int j = 0; j <= 6; j++){
trainingData[i][j] = (float)hu[j];
}
labels[i] = 1;
}
for (int i = 0; i <= 5; i++){
std::string path("train/tn");
path += std::to_string(i);
path += ".png";
Mat input = imread(path, 0);
bitwise_not(input, input);
Mat BinaryInput;
threshold(input, BinaryInput, 100, 255, cv::THRESH_BINARY);
moment = moments(BinaryInput, true);
HuMoments(moment, hu);
for (int j = 0; j <= 6; j++){
trainingData[i + 6][j] = (float)hu[j];
}
labels[i + 6] = 0;
}
Mat labelsMat(12, 1, CV_32FC1, labels);
Mat trainingDataMat(12, 7, CV_32FC1, trainingData);
Ptr<ml::SVM> svm = ml::SVM::create();
svm->setType(ml::SVM::C_SVC);
svm->setKernel(ml::SVM::LINEAR);
CvTermCriteria criteria = cvTermCriteria(CV_TERMCRIT_ITER, 100, 1e-6);
svm->setTermCriteria(criteria);
svm->train(trainingDataMat, ml::ROW_SAMPLE, labelsMat);
Mat test = imread("train/t1.png", 0);
bitwise_not(test, test);
Mat testBin;
threshold(test, testBin, 100, 255, cv::THRESH_BINARY);
Moments momentP = moments(testBin, true);
double huP[7];
HuMoments(momentP, huP);
Mat testMat(1, 7, CV_32FC1, huP);
double resp = svm->predict(testMat);
printf("%f", resp);
getchar();
}
i know that the program is running fine until that line because i printed
labelsMat
and
trainingDataMat
and the values inside them are ok. Even in the console i can see that the program is running fine until that exact line executes. the console then shows this message:
OpenCV error: Bad argument (in the case of classification problem the responses must be categorical; either specify varType when creating TrainDatam or pass integer responses)
i dont really know what this means. any idea of what could be causing the problem? if you need any other details please tell me.