I need to SVM for training data and for predicting data,having pca matrix.What is wrong in the code?It is running well but no output obtained.Neither the xml file is being saved.
#include
#include
#include "opencv2/imgcodecs.hpp"
#include
#include
using namespace cv;
using namespace cv::ml;
using namespace std;
int main()
{
Mat img_mat = imread("C:/Users/Documents//Projects/TrainingData/pic.jpg");
// Load images in the C++ format
Size size(240, 320);//the image size,e.g.64x124
resize(img_mat, img_mat, size);//resize image
int num_files = 1;//number of images
int img_area = 240 * 320;//imag size
//initialize the training matrix
//The number of rows in the matrix would be 5, and the number of columns would be the area of the image, 64*124 = 12
//Mat training_mat(num_files, img_area, CV_32FC1);
Mat training_mat(img_area, num_files, CV_32FC1);
// "fill in" the rows of training_mat with the data from each image.
cvtColor(img_mat, img_mat, CV_RGB2GRAY);
imshow("", img_mat);
int ii = 0; // Current column in training_mat
//Do this for every training image
int file_num = 0;
for (int i = 0; i(file_num, ii++) = img_mat.at(i, j);
}
}
// training matrix set up properly to pass into the SVM functions
//set up labels for each training image
//1D matrix, where each element in the 1D matrix corresponds to each row in the 2D matrix.
//-1 for non-human and 1 for human
//labels matrix
float label = 1.0;
cout << training_mat.rows << endl;
cout << training_mat.cols << endl;
//Mat labels(1, 7936, CV_32SC1, label);
Mat labels(training_mat.rows, 1, CV_32SC1, label);
//Mat labels(num_files, 1, CV_32FC1);
/*Reduce dimensionality using PCA*/
Mat projection_result;
PCA pca(training_mat, Mat(), CV_PCA_DATA_AS_ROW, 512);
pca.project(training_mat, projection_result);
/*Classification*/
// Set up SVM's parameters
Ptr svmOld = SVM::create();
svmOld->setType(SVM::C_SVC);
svmOld->setKernel(SVM::LINEAR);
svmOld->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER, 100, 1e-6));
//train it based on your data
svmOld->train(training_mat, ROW_SAMPLE, labels);
//same svm
svmOld->save("svm_classification.xml");
//Initialize SVM object
Ptr svmNew = SVM::create();
//Load Previously saved SVM from XML
//can save the trained SVM so you don't have to retrain it every time
svmNew = SVM::load("svm_classification.xml");
Mat testData(1, 23040, CV_32F);
Mat test_projected;
pca.project(testData, test_projected); // should result in a 512 x 1 Mat
//int label = svmOld.predict(test_projected);
//To test your images using the trained SVM, simply read an image, convert it to a 1D matrix, and pass that in to svm
//svmNew->predict(training_mat);
//td.predict( training_mat);//It will return a value based on what you set as your labels
// to disk:
FileStorage fs("pca.xml", FileStorage::WRITE);
pca.write(fs);
fs.release(); // flush
// and back:
PCA pca;
FileStorage fs("pca.xml", FileStorage::READ);
pca.read(fs.root());
fs.release();
waitKey(0);
return(0);
}
↧