static void trainSVM(SVM &svm, Mat data, Mat lab, int kernel, int type, float C, float gamma) { if (data.type() != CV_32FC1) qFatal("Expected single channel floating point training data."); CvSVMParams params; params.kernel_type = kernel; params.svm_type = type; params.p = 0.1; params.nu = 0.5; if ((C == -1) || ((gamma == -1) && (kernel == CvSVM::RBF))) { try { svm.train_auto(data, lab, Mat(), Mat(), params, 5); } catch (...) { qWarning("Some classes do not contain sufficient examples or are not discriminative enough for accurate SVM classification."); svm.train(data, lab); } } else { params.C = C; params.gamma = gamma; svm.train(data, lab, Mat(), Mat(), params); } CvSVMParams p = svm.get_params(); qDebug("SVM C = %f Gamma = %f Support Vectors = %d", p.C, p.gamma, svm.get_support_vector_count()); }
TEST(ML_SVM, throw_exception_when_save_untrained_model) { SVM svm; string filename = tempfile("svm.xml"); ASSERT_THROW(svm.save(filename.c_str()), Exception); remove(filename.c_str()); }
bool SVM::deepCopyFrom(const Classifier *classifier){ if( classifier == NULL ) return false; if( this->getClassifierType() == classifier->getClassifierType() ){ SVM *ptr = (SVM*)classifier; this->clear(); //SVM variables this->problemSet = false; this->model = ptr->deepCopyModel(); this->deepCopyParam( ptr->param, this->param ); this->numInputDimensions = ptr->numInputDimensions; this->kFoldValue = ptr->kFoldValue; this->classificationThreshold = ptr->classificationThreshold; this->crossValidationResult = ptr->crossValidationResult; this->useAutoGamma = ptr->useAutoGamma; this->useCrossValidation = ptr->useCrossValidation; //Classifier variables return copyBaseVariables( classifier ); } return false; }
// Tests the default constructor TEST(SVM, Constructor) { SVM svm; //Check the type matches EXPECT_TRUE( svm.getClassifierType() == SVM::getId() ); //Check the module is not trained EXPECT_TRUE( !svm.getTrained() ); }
void columbiaTest(int testId = 0) { CascadeClassifier classifier; classifier.load("haarcascades/haarcascade_frontalface_alt_tree.xml"); ShapePredictor predictor; predictor.load("model/helen.txt"); PCA pca; FileStorage fs("model/pca.xml", FileStorage::READ); fs["mean"] >> pca.mean; fs["eigenvals"] >> pca.eigenvalues; fs["eigenvecs"] >> pca.eigenvectors; fs.release(); /*LDA lda; lda.load("model/lda.xml");*/ SVM svm; svm.load("model/svm.xml"); cout << "\nmodel loaded" << endl; // test prediction cout << "\nbegin test" << endl; int corr = 0, total = 0; Mat_<float> labels, multihog, ldmks; collectData(testId, classifier, predictor, labels, multihog, ldmks); for (int i = 0; i < multihog.rows; i++) { Mat_<float> pcaVec = pca.project(multihog.row(i)); Mat_<float> datVec(1, pcaVec.cols + ldmks.cols); for (int j = 0; j < pcaVec.cols; j++) datVec(0, j) = pcaVec(0, j); for (int j = 0; j < ldmks.cols; j++) datVec(0, j + pcaVec.cols) = ldmks(i, j); //Mat_<float> ldaVec = lda.project(datVec); float pred = svm.predict(datVec); if ((int)pred == (int)labels(i, 0)) corr++; total++; } cout << "testId = " << testId << endl; cout << "corr = " << corr << " , total = " << total << endl; cout << "percentage: " << (double)corr / total << endl; ofstream fout("data/testId" + to_string(testId) + ".txt"); fout << "corr = " << corr << " , total = " << total << endl; fout << "percentage: " << (double)corr / total << endl; fout.close(); }
int main(int argn, char *argv[]) { //SVM_verbose = true; seed_random(); SVM * i = new SVM(argv[1]); double result = i->run(); if isnan(result) cout << "WARNING: RESULT IS NAN\n"; cout << result << endl; delete i; }
void columbiaTrain(int testId = 0) { CascadeClassifier classifier; classifier.load("haarcascades/haarcascade_frontalface_alt_tree.xml"); ShapePredictor predictor; predictor.load("model/helen.txt"); cout << "face & shape detector loaded\n" << endl; FileStorage fs; Mat_<float> labels, multihog, ldmks; for (int subjId = 1; subjId <= 56; subjId++) { if (subjId == testId) continue; collectData(subjId, classifier, predictor, labels, multihog, ldmks); } cout << "multihog.rows = " << multihog.rows << endl; cout << "multihog.cols = " << multihog.cols << endl; // PCA cout << "\nbegin PCA" << endl; int pcaComp = 400; PCA pca(multihog, Mat(), CV_PCA_DATA_AS_ROW, pcaComp); fs.open("model/pca.xml", FileStorage::WRITE); fs << "mean" << pca.mean; fs << "eigenvals" << pca.eigenvalues; fs << "eigenvecs" << pca.eigenvectors; fs.release(); cout << "PCA complete" << endl; Mat_<float> pcaMat = pca.project(multihog); cout << "pcaMat.rows = " << pcaMat.rows << endl; cout << "pcaMat.cols = " << pcaMat.cols << endl; Mat_<float> dataMat(multihog.rows, pcaMat.cols + ldmks.cols); for (int i = 0; i < multihog.rows; i++) { for (int j = 0; j < pcaMat.cols; j++) dataMat(i, j) = pcaMat(i, j); for (int j = 0; j < ldmks.cols; j++) dataMat(i, j + pcaMat.cols) = ldmks(i, j); } // SVM cout << "\ntrain SVM" << endl; SVMParams params; params.svm_type = SVM::C_SVC; params.kernel_type = SVM::RBF; SVM svm; svm.train_auto(dataMat, labels, Mat(), Mat(), params); svm.save("model/svm.xml"); cout << "SVM saved!\n" << endl; }
double runSVM(char const *file) { char *oldLocale = setlocale(LC_ALL, NULL); SVM_verbose = false; setlocale(LC_ALL, "C"); seed_random(); SVM * i = new SVM(file); double result = i->run(); delete i; setlocale(LC_ALL, oldLocale); if isnan(result) cout << "WARNING: RESULT IS NAN\n"; return result; }
bool ex_model_norm(void *arg) { Trainer::SetLogLevel(SSI_LOG_LEVEL_DEBUG); ssi_size_t n_classes = 4; ssi_size_t n_samples = 50; ssi_size_t n_streams = 1; ssi_real_t train_distr[][3] = { 0.25f, 0.25f, 0.1f, 0.25f, 0.75f, 0.1f, 0.75f, 0.75f, 0.1f, 0.75f, 0.75f, 0.1f }; ssi_real_t test_distr[][3] = { 0.5f, 0.5f, 0.5f }; SampleList strain; SampleList sdevel; SampleList stest; ModelTools::CreateTestSamples(strain, n_classes, n_samples, n_streams, train_distr, "user"); ModelTools::CreateTestSamples(sdevel, n_classes, n_samples, n_streams, train_distr, "user"); ModelTools::CreateTestSamples(stest, 1, n_samples * n_classes, n_streams, test_distr, "user"); ssi_char_t string[SSI_MAX_CHAR]; for (ssi_size_t n_class = 1; n_class < n_classes; n_class++) { ssi_sprint(string, "class%02d", n_class); stest.addClassName(string); } // train svm { SVM *model = ssi_create(SVM, 0, true); model->getOptions()->seed = 1234; Trainer trainer(model); ISNorm::Params params; ISNorm::ZeroParams(params, ISNorm::METHOD::ZSCORE); trainer.setNormalization(¶ms); trainer.train(strain); trainer.save("svm+norm"); } // evaluation { Trainer trainer; Trainer::Load(trainer, "svm+norm"); Evaluation eval; eval.eval(&trainer, sdevel); eval.print(); trainer.cluster(stest); ModelTools::PlotSamples(stest, "svm (external normalization)", ssi_rect(650,0,400,400)); } return true; }
void project(const Template &src, Template &dst) const { dst = src; float prediction = svm.predict(src.m().reshape(1, 1)); if (type == EPS_SVR || type == NU_SVR) dst.file.set(outputVariable, prediction); else dst.file.set(outputVariable, reverseLookup[prediction]); }
static void loadSVM(SVM &svm, QDataStream &stream) { // Copy local file contents from stream QByteArray data; stream >> data; // Create local file QTemporaryFile tempFile(QDir::tempPath()+"/SVM"); tempFile.open(); tempFile.write(data); tempFile.close(); // Load SVM from local file svm.load(qPrintable(tempFile.fileName())); }
int main(int argc, char** argv) { /* Equation eq; eq.theta0 = -1; eq.theta[0] = 2; Equation eq1; eq.roundoff(eq1); std::cout << eq << std::endl; std::cout << eq1 << std::endl; return 0; */ if (argc < 1) { std::cout << "Arguments less than 2.\n"; exit(-1); } if (argc >= 3) { minv = atoi(argv[1]); maxv = atoi(argv[2]); } Solution inputs; init_gsets(); srand(time(NULL)); // initialize seed for rand() function int rnd; bool b_similar_last_time = false; bool b_converged = false; bool b_svm_i = false; Equation* p = NULL; int pre_positive_size = 0, pre_negative_size = 0; // , pre_question_size = 0; //int cur_positive_size = 0, cur_negative_size = 0; // , cur_question_size = 0; //Start SVM training SVM* svm = new SVM(print_null); //svm->problem.x = (svm_node**)(training_set); //svm->problem.y = training_label; for (rnd = 1; rnd <= max_iter; rnd++) { svm->main_equation = NULL; init_svm: std::cout << "[" << rnd << "]SVM-----------------------------------------------" << "-------------------------------------------------------------" << std::endl; if (rnd == 1) { /* * The first round is very special, so we put this round apart with its following rounds. * 1> We used random values as inputs for program executions in the first round. * 2> We need to make sure there are at last two classes of generated traces. "positive" and "negative" */ std::cout << "\t(1) execute programs... [" << init_exes + random_exes << "] {"; for (int i = 0; i < init_exes + random_exes; i++) { Equation::linearSolver(NULL, inputs); std::cout << inputs; if (i < init_exes + random_exes - 1) std::cout << "|"; run_target(inputs); } std::cout << "}" << std::endl; if (gsets[POSITIVE].traces_num() == 0 || gsets[NEGATIVE].traces_num() == 0) { if (gsets[POSITIVE].traces_num() == 0) std::cout << "[0] Positive trace, execute program again." << std::endl; if (gsets[NEGATIVE].traces_num() == 0) std::cout << "[0] Negative trace, execute program again." << std::endl; goto init_svm; } } else { std::cout << "\t(1) execute programs...[" << after_exes + random_exes << "] {"; for (int i = 0; i < random_exes; i++) { Equation::linearSolver(NULL, inputs); std::cout << inputs; std::cout << " | "; run_target(inputs); } for (int i = 0; i < after_exes; i++) { Equation::linearSolver(p, inputs); std::cout << " | " << inputs; run_target(inputs); } std::cout << "}" << std::endl; } std::cout << "\t(2) prepare training data... "; svm->prepare_training_data(gsets, pre_positive_size, pre_negative_size); std::cout << std::endl; std::cout << "\t(3) start training... "; svm->train(); std::cout << "|-->> "; set_console_color(std::cout); std::cout << *svm << std::endl; unset_console_color(std::cout); /* * check on its own training data. * There should be no prediction errors. */ std::cout << "\t(4) checking training traces."; double passRat = svm->predict_on_training_set(); std::cout << " [" << passRat * 100 << "%]"; if (passRat < 1) { std::cout << " [FAIL] \n The problem is not linear separable.. Trying to solve is by SVM-I algo" << std::endl; if (p != NULL) { Equation* tmp = svm->main_equation; svm->main_equation = p; double passRat = svm->predict_on_training_set(); std::cout << " last divide: " << *p << " accuracy[" << passRat * 100 << "%]\n"; svm->main_equation = tmp; } std::cerr << "*******************************USING SVM_I NOW******************************" << std::endl; b_svm_i = true; break; } std::cout << " [PASS]" << std::endl; /* * Check on Question traces. * There should not exists one traces, in which a negative state is behind a positive state. */ std::cout << "\t(5) checking question traces."; set_console_color(std::cout, RED); if (svm->check_question_set(gsets[QUESTION]) != 0) { std::cout << std::endl << "check on question set return error." << std::endl; unset_console_color(std::cout); return -1; } unset_console_color(std::cout); std::cout << std::endl; /* * b_similar_last_time is used to store the convergence check return value for the last time. * We only admit convergence if the three consecutive round are converged. * This is to prevent in some round the points are too right to adjust the classifier. */ std::cout << "\t(6) check convergence: "; if (svm->main_equation->is_similar(p) == 0) { if (b_similar_last_time == true) { std::cout << "[TT] [SUCCESS] rounding off" << std::endl; b_converged = true; break; } std::cout << "[FT]"; b_similar_last_time = true; } else { std::cout << ((b_similar_last_time == true) ? "[T" : "[F") << "F] "; b_similar_last_time = false; } std::cout << " [FAIL] neXt round " << std::endl; if (p != NULL) { delete p; } p = svm->main_equation; } // end of SVM training procedure if ((b_converged) || (rnd >= max_iter)) { std::cout << "-------------------------------------------------------" << "-------------------------------------------------------------" << std::endl; std::cout << "finish running svm for " << rnd << " times." << std::endl; int equation_num = -1; Equation* equs = svm->roundoff(equation_num); assert(equation_num == 1); set_console_color(std::cout); if (b_converged) std::cout << " Hypothesis Invairant(Converged): {\n"; else std::cout << " Hypothesis Invairant(Reaching Maximium Iteration): {\n"; std::cout << "\t\t" << equs[0] << std::endl; std::cout << " }" << std::endl; unset_console_color(std::cout); delete[]equs; delete p; delete svm->main_equation; delete svm; return 0; } if (p == NULL) { // get out svm in the first round, p has not been set yet p = svm->main_equation; } delete svm; b_similar_last_time = false; int pre_equation_num = 1; //start SVM_I training assert(b_svm_i == true); SVM_I* svm_i = new SVM_I(print_null, p); int svm_i_start = rnd; for (; rnd <= max_iter; rnd++) { // init_svm_i: std::cout << "[" << rnd << "]SVM-I---------------------------------------------" << "-------------------------------------------------------------" << std::endl; if (rnd != svm_i_start) { int exes_each_equation = (after_exes + pre_equation_num - 1) / pre_equation_num; std::cout << "\t(1) execute programs...[" << exes_each_equation * pre_equation_num + random_exes << "] {"; for (int i = 0; i < random_exes; i++) { Equation::linearSolver(NULL, inputs); std::cout << inputs << " | "; run_target(inputs); } p = svm_i->main_equation; for (int j = 0; j < exes_each_equation; j++) { Equation::linearSolver(p, inputs); std::cout << " | " << inputs; run_target(inputs); } for (int i = 0; i < svm_i->equ_num; i++) { p = &(svm_i->equations[i]); for (int j = 0; j < exes_each_equation; j++) { Equation::linearSolver(p, inputs); std::cout << " | " << inputs; run_target(inputs); } } std::cout << "}" << std::endl; } else { pre_positive_size = 0; pre_negative_size = 0; } std::cout << "\t(2) prepare training data... "; svm_i->prepare_training_data(gsets, pre_positive_size, pre_negative_size); std::cout << std::endl; std::cout << "\t(3) start training... "; int ret = svm_i->train(); if (ret == -1) return -1; std::cout << svm_i->equ_num; std::cout << "|-->> "; set_console_color(std::cout); std::cout << *svm_i << std::endl; unset_console_color(std::cout); /* * check on its own training data. * There should be no prediction errors. */ std::cout << "\t(4) checking training traces."; double passRat = svm_i->predict_on_training_set(); std::cout << " [" << passRat * 100 << "%]"; if (passRat < 1) { set_console_color(std::cout, RED); std::cerr << "[FAIL] ..... Can not dividey by SVM_I." << std::endl; //std::cerr << "[FAIL] ..... Reaching maximium num of equation supported by SVM_I." << std::endl; //std::cerr << "You can increase the limit by modifying [classname::methodname]=SVM-I::SVM-I(..., int equ = **) " << std::endl; unset_console_color(std::cout); return -1; // b_svm_i = true; // break; } else { std::cout << " [PASS]" << std::endl; } /* * Check on Question traces. * There should not exists one traces, in which a negative state is behind a positive state. */ std::cout << "\t(5) checking question traces."; if (svm_i->check_question_set(gsets[QUESTION]) != 0) { std::cout << std::endl << "check on question set return error." << std::endl; return -1; } std::cout << std::endl; /* * b_similar_last_time is used to store the convergence check return value for the last time. * We only admit convergence if the three consecutive round are converged. * This is to prevent in some round the points are too right to adjust the classifier. */ std::cout << "\t(6) check convergence: "; if (pre_equation_num == svm_i->equ_num + 1) { if (b_similar_last_time == true) { std::cout << "[TT] [SUCCESS] rounding off" << std::endl; b_converged = true; break; } std::cout << "[FT]"; b_similar_last_time = true; } else { std::cout << ((b_similar_last_time == true) ? "[T" : "[F") << "F] "; b_similar_last_time = false; } std::cout << " [FAIL] neXt round " << std::endl; pre_equation_num = svm_i->equ_num + 1; std::cout << std::endl; } // end of SVM-I training procedure std::cout << "-------------------------------------------------------" << "-------------------------------------------------------------" << std::endl; std::cout << "finish running svm-I for " << rnd - svm_i_start << " times." << std::endl; int equation_num = -1; Equation* equs = svm_i->roundoff(equation_num); set_console_color(std::cout); std::cout << "Hypothesis Invairant: {\n"; std::cout << "\t " << equs[0] << std::endl; for (int i = 1; i < equation_num; i++) std::cout << "\t /\\ " << equs[i] << std::endl; std::cout << "}" << std::endl; unset_console_color(std::cout); delete[]equs; delete svm_i->main_equation; delete svm_i; return 0; }
// Tests the learning algorithm on a basic dataset TEST(SVM, TrainBasicDataset) { SVM svm; //Check the module is not trained EXPECT_TRUE( !svm.getTrained() ); //Generate a basic dataset const UINT numSamples = 1000; const UINT numClasses = 10; const UINT numDimensions = 10; ClassificationData::generateGaussDataset( "gauss_data.csv", numSamples, numClasses, numDimensions, 10, 1 ); ClassificationData trainingData; EXPECT_TRUE( trainingData.load( "gauss_data.csv" ) ); ClassificationData testData = trainingData.split( 50 ); //Train the classifier EXPECT_TRUE( svm.train( trainingData ) ); EXPECT_TRUE( svm.getTrained() ); for(UINT i=0; i<testData.getNumSamples(); i++){ EXPECT_TRUE( svm.predict( testData[i].getSample() ) ); } EXPECT_TRUE( svm.save( "svm_model.grt" ) ); svm.clear(); EXPECT_TRUE( !svm.getTrained() ); EXPECT_TRUE( svm.load( "svm_model.grt" ) ); EXPECT_TRUE( svm.getTrained() ); for(UINT i=0; i<testData.getNumSamples(); i++){ EXPECT_TRUE( svm.predict( testData[i].getSample() ) ); } }
void test(set<int> &testSet, int code) { CascadeClassifier classifier; classifier.load("haarcascades/haarcascade_frontalface_alt_tree.xml"); ShapePredictor predictor; predictor.load("model/helen.txt"); PCA pca; FileStorage fs("model/girl_pca.xml", FileStorage::READ); fs["mean"] >> pca.mean; fs["eigenvals"] >> pca.eigenvalues; fs["eigenvecs"] >> pca.eigenvectors; SVM svm; svm.load("model/girl_svm.xml"); cout << "\nmodel loaded" << endl; ifstream fin("img/labels.txt"); ofstream fout("data/out_" + to_string(code) + ".txt"); VideoWriter writer("data/out.avi", 0, 10, Size(1920, 1080), true); string line; int corr = 0, total = 0; while (getline(fin, line)) { stringstream ss(line); int frame, label; ss >> frame >> label; label -= 49; if (testSet.find(frame) == testSet.end()) continue; Mat vis = imread("img/" + to_string(frame) + ".jpg", CV_LOAD_IMAGE_UNCHANGED); Mat_<uchar> img; cvtColor(vis, img, COLOR_BGR2GRAY); BBox bbox = getTestBBox(img, classifier); if (EmptyBox(bbox)) continue; Mat_<double> shape = predictor(img, bbox); Geom G; initGeom(shape, G); Pose P; calcPose(G, P); Mat_<uchar> lEye, rEye; regularize(img, bbox, P, shape, lEye, rEye); vector<float> lRlt; vector<float> rRlt; calcMultiHog(lEye, lRlt); calcMultiHog(rEye, rRlt); Mat_<float> pcaVec, ldmks; vector<float> _hog2nd_vec; for (int k = 0; k < lRlt.size(); k++) _hog2nd_vec.push_back(lRlt[k]); for (int k = 0; k < rRlt.size(); k++) _hog2nd_vec.push_back(rRlt[k]); Mat_<float> multihog = Mat_<float>(_hog2nd_vec).reshape(1, 1); pcaVec = pca.project(multihog); vector<float> _ldmks; for (int i = 28; i < 48; i++) { _ldmks.push_back((shape(i, 0) - bbox.cx) / bbox.w); _ldmks.push_back((shape(i, 1) - bbox.cy) / bbox.h); } float mouthx = (shape(51, 0) + shape(62, 0) + shape(66, 0) + shape(57, 0)) / 4; float mouthy = (shape(51, 1) + shape(62, 1) + shape(66, 1) + shape(57, 1)) / 4; _ldmks.push_back((mouthx - bbox.cx) / bbox.w); _ldmks.push_back((mouthy - bbox.cy) / bbox.h); float maxVal = *std::max_element(_ldmks.begin(), _ldmks.end()); for (int i = 0; i < _ldmks.size(); i++) _ldmks[i] *= 1.0 / maxVal; // scale to [-1, 1] ldmks = Mat_<float>(_ldmks).reshape(1, 1); Mat_<float> sample(1, pcaVec.cols + ldmks.cols); for (int j = 0; j < pcaVec.cols; j++) sample(0, j) = pcaVec(0, j); for (int j = 0; j < ldmks.cols; j++) sample(0, j + pcaVec.cols) = ldmks(0, j); int pred = svm.predict(sample); if (pred == label) corr++; total++; fout << frame << ' ' << label << ' ' << pred << endl; string s1, s2; switch (label) { case 0: s1 = "annotation: Eye"; break; case 1: s1 = "annotation: Face"; break; case 2: s1 = "annotation: NOF"; break; } switch (pred) { case 0: s2 = "prediction: Eye"; break; case 1: s2 = "prediction: Face"; break; case 2: s2 = "prediction: NOF"; break; } Scalar c1, c2; c1 = CV_RGB(255, 255, 0); // yellow if (pred == label) c2 = CV_RGB(0, 255, 0); // green else c2 = CV_RGB(255, 0, 0); // red putText(vis, s1, Point(1280, 100), CV_FONT_HERSHEY_PLAIN, 4.0, c1, 3); putText(vis, s2, Point(1280, 200), CV_FONT_HERSHEY_PLAIN, 4.0, c2, 3); /*imshow("glance", vis); waitKey(0);*/ writer.write(vis); } cout << corr << ' ' << total << endl; cout << (double)corr / total << endl; fin.close(); fout.close(); writer.release(); }
void train(set<int> &testSet) { CascadeClassifier classifier; classifier.load("haarcascades/haarcascade_frontalface_alt_tree.xml"); ShapePredictor predictor; predictor.load("model/helen.txt"); cout << "face & shape detector loaded\n" << endl; ifstream fin("img/labels.txt"); string line; Mat_<float> labels, multihog, landmarks; while (getline(fin, line)) { stringstream ss(line); int frame, label; ss >> frame >> label; label -= 49; if (testSet.find(frame) != testSet.end()) continue; Mat_<uchar> img = imread("img/" + to_string(frame) + ".jpg", 0); BBox bbox = getTestBBox(img, classifier); if (EmptyBox(bbox)) continue; Mat_<float> lbl(1, 1); lbl(0, 0) = label; labels.push_back(lbl); Mat_<double> shape = predictor(img, bbox); Geom G; initGeom(shape, G); Pose P; calcPose(G, P); Mat_<uchar> lEye, rEye; regularize(img, bbox, P, shape, lEye, rEye); vector<float> lRlt; vector<float> rRlt; calcMultiHog(lEye, lRlt); calcMultiHog(rEye, rRlt); vector<float> _hog2nd_vec; for (int k = 0; k < lRlt.size(); k++) _hog2nd_vec.push_back(lRlt[k]); for (int k = 0; k < rRlt.size(); k++) _hog2nd_vec.push_back(rRlt[k]); Mat_<float> mhog = Mat_<float>(_hog2nd_vec).reshape(1, 1); multihog.push_back(mhog); vector<float> _ldmks; for (int i = 28; i < 48; i++) { _ldmks.push_back((shape(i, 0) - bbox.cx) / bbox.w); _ldmks.push_back((shape(i, 1) - bbox.cy) / bbox.h); } float mouthx = (shape(51, 0) + shape(62, 0) + shape(66, 0) + shape(57, 0)) / 4; float mouthy = (shape(51, 1) + shape(62, 1) + shape(66, 1) + shape(57, 1)) / 4; _ldmks.push_back((mouthx - bbox.cx) / bbox.w); _ldmks.push_back((mouthy - bbox.cy) / bbox.h); float maxVal = *std::max_element(_ldmks.begin(), _ldmks.end()); for (int i = 0; i < _ldmks.size(); i++) _ldmks[i] *= 1.0 / maxVal; // scale to [-1, 1] Mat_<float> ldmks = Mat_<float>(_ldmks).reshape(1, 1); landmarks.push_back(ldmks); } // PCA cout << "\nbegin PCA" << endl; int pcaComp = 400; PCA pca(multihog, Mat(), CV_PCA_DATA_AS_ROW, pcaComp); FileStorage fs("model/girl_pca.xml", FileStorage::WRITE); fs << "mean" << pca.mean; fs << "eigenvals" << pca.eigenvalues; fs << "eigenvecs" << pca.eigenvectors; fs.release(); cout << "PCA complete" << endl; Mat_<float> pcaMat = pca.project(multihog); cout << "pcaMat.rows = " << pcaMat.rows << endl; cout << "pcaMat.cols = " << pcaMat.cols << endl; Mat_<float> dataMat(multihog.rows, pcaMat.cols + landmarks.cols); for (int i = 0; i < multihog.rows; i++) { for (int j = 0; j < pcaMat.cols; j++) dataMat(i, j) = pcaMat(i, j); for (int j = 0; j < landmarks.cols; j++) dataMat(i, j + pcaMat.cols) = landmarks(i, j); } // SVM cout << "\ntrain SVM" << endl; SVMParams params; params.svm_type = SVM::C_SVC; params.kernel_type = SVM::RBF; SVM svm; svm.train_auto(dataMat, labels, Mat(), Mat(), params); svm.save("model/girl_svm.xml"); cout << "SVM saved!\n" << endl; }
bool ex_model(void *arg) { Trainer::SetLogLevel (SSI_LOG_LEVEL_DEBUG); ssi_size_t n_classes = 4; ssi_size_t n_samples = 50; ssi_size_t n_streams = 1; ssi_real_t train_distr[][3] = { 0.25f, 0.25f, 0.1f, 0.25f, 0.75f, 0.1f, 0.75f, 0.75f, 0.1f, 0.75f, 0.75f, 0.1f }; ssi_real_t test_distr[][3] = { 0.5f, 0.5f, 0.5f }; SampleList strain; SampleList sdevel; SampleList stest; ModelTools::CreateTestSamples (strain, n_classes, n_samples, n_streams, train_distr, "user"); ModelTools::CreateTestSamples (sdevel, n_classes, n_samples, n_streams, train_distr, "user"); ModelTools::CreateTestSamples (stest, 1, n_samples * n_classes, n_streams, test_distr, "user"); ssi_char_t string[SSI_MAX_CHAR]; for (ssi_size_t n_class = 1; n_class < n_classes; n_class++) { ssi_sprint (string, "class%02d", n_class); stest.addClassName (string); } // train svm { SVM *model = ssi_create(SVM, 0, true); model->getOptions()->seed = 1234; Trainer trainer(model); trainer.train(strain); trainer.save("svm"); } // evaluation { Trainer trainer; Trainer::Load(trainer, "svm"); Evaluation eval; eval.eval(&trainer, sdevel); eval.print(); trainer.cluster(stest); ModelTools::PlotSamples(stest, "svm (internal normalization)", ssi_rect(650, 0, 400, 400)); } // train knn { KNearestNeighbors *model = ssi_create(KNearestNeighbors, 0, true); model->getOptions()->k = 5; //model->getOptions()->distsum = true; Trainer trainer (model); trainer.train (strain); trainer.save ("knn"); } // evaluation { Trainer trainer; Trainer::Load (trainer, "knn"); Evaluation eval; eval.eval (&trainer, sdevel); eval.print (); trainer.cluster (stest); ModelTools::PlotSamples(stest, "knn", ssi_rect(650, 0, 400, 400)); } // train naive bayes { NaiveBayes *model = ssi_create(NaiveBayes, 0, true); model->getOptions()->log = true; Trainer trainer (model); trainer.train (strain); trainer.save ("bayes"); } // evaluation { Trainer trainer; Trainer::Load (trainer, "bayes"); Evaluation eval; eval.eval (&trainer, sdevel); eval.print (); trainer.cluster (stest); ModelTools::PlotSamples(stest, "bayes", ssi_rect(650, 0, 400, 400)); } // training { LDA *model = ssi_create(LDA, "lda", true); Trainer trainer (model); trainer.train (strain); model->print(); trainer.save ("lda"); } // evaluation { Trainer trainer; Trainer::Load (trainer, "lda"); Evaluation eval; eval.eval (&trainer, sdevel); eval.print (); trainer.cluster (stest); ModelTools::PlotSamples(stest, "lda", ssi_rect(650, 0, 400, 400)); } ssi_print ("\n\n\tpress a key to contiue\n"); getchar (); return true; }
int main(int argc, char **argv) { string nameImage(argv[1]); //Parameters of the simulation for the drive dataset bool includeOddOrders = false; bool includeEvenOrders = true; bool includeOrder0 = false; float sigmaImgs = 2.0; string directory = getDirectoryFromPath(nameImage); string xFile = "/home/ggonzale/mount/cvlabfiler/drive/training/svm_1.000e+01_1.000e-02.svm"; double sk = 1e-02; double C = 10; /* //Paramters for road images bool includeOddOrders = true; bool includeEvenOrders = true; bool includeOrder0 = false; string directory = getDirectoryFromPath(nameImage); float sigmaImgs = 3.0; string xFile = "/home/ggonzale/mount/cvlabfiler/roads/training/svm_1.000e+01_1.000e+01.svm"; double sk = 1e+01; double C = 10; */ string imageName = nameImage; string outputName = directory + "/out.jpg"; string imageThetaN = directory + "/theta.jpg"; if(!fileExists(imageThetaN)){ Image<float>* image = new Image<float>(imageName); // image->computeHessian(sigmaImgs, directory+"/l1.jpg", directory + "/l2.jpg", // true, directory + "theta.jpg"); } string imageHessianN = directory + "/l1.jpg"; double sigma = 1.0/(sk*sk); SteerableFilter2DM* stf = new SteerableFilter2DM(imageName, 4, sigmaImgs, outputName, includeOddOrders, includeEvenOrders, includeOrder0); stf->result->put_all(0.0); // int xInit = 575; //int yInit = 525; //int xEnd = 650; //int yEnd = 549; // int xInit = 489; // int yInit = 509; // int xEnd = 769; // int yEnd = 765; int xInit = 0; int yInit = 0; int xEnd = stf->image->width; int yEnd = stf->image->height; Image< float >* theta = new Image<float>(imageThetaN); Image< float >* hessian = new Image<float>(imageHessianN); int nSupportVectors = 0; int dimensionOfSupportVectors = 0; Allocator *allocator = new Allocator; SVM *svm = NULL; Kernel *kernel = NULL; kernel = new(allocator) GaussianKernel((double)sigma); svm = new(allocator) SVMClassification(kernel); DiskXFile* model = new(allocator) DiskXFile(xFile.c_str(),"r"); svm->loadXFile(model); svm->setROption("C", C); svm->setROption("cache size", 100); nSupportVectors = svm->n_support_vectors; dimensionOfSupportVectors = svm->sv_sequences[0]->frame_size; vector< vector< double > > svectors = allocateMatrix(nSupportVectors, dimensionOfSupportVectors); vector< double > alphas(nSupportVectors); for(int i = 0; i < nSupportVectors; i++){ alphas[i] = svm->sv_alpha[i]; for(int j = 0; j < dimensionOfSupportVectors; j++){ svectors[i][j] = svm->sv_sequences[i]->frames[0][j]; } } //saveMatrix(svectors, "supportVectors.txt"); //saveVectorDouble(alphas, "alphas.txt"); // svectors.resize(1); //alphas.resize(1); //for(int i = 0; i < svectors[0].size(); i++) // svectors[0][i] = 1; //alphas[0] = 1; saveMatrix(svectors, "supportVectors.txt"); saveVectorDouble(alphas, "alphas.txt"); printf("CubeName = %s\nxFile = %s\nsigma = %f\n" "C = %f\nstdv = %f\nCubeTheta = %s\n" "cubeAguet = %s\noutputName = %s\n", imageName.c_str(), xFile.c_str(), sigmaImgs, C, sigma, imageThetaN.c_str(), imageHessianN.c_str(), outputName.c_str()); printf("Computing between [%i,%i] and [%i,%i]\n", xInit, yInit, xEnd, yEnd); #pragma omp parallel for for(int y = yInit; y < yEnd; y++){ printf("#"); fflush(stdout); for(int x = xInit; x < xEnd; x++){ // printf("[%i,%i,%i] %f\n", x, y, z, cubeAguet->at(x,y,z)); double res = 0; double expn = 0; // if(hessian->at(x,y) > 0){ vector< float > coords = stf->getDerivativeCoordinatesRotated (x,y, theta->at(x,y)); if(0){ res = 0; expn = 0; for(int i = 0; i < alphas.size(); i++){ expn = 0; for(int j = 0; j < svectors[i].size(); j++) expn -= (svectors[i][j] - coords[j])* (svectors[i][j] - coords[j]); res += alphas[i]*exp(expn*sigma); } } else { res = getResponseSVMSF(svm, coords); } stf->result->put(x,y, res); //} //if > 0 } //X }//Y printf("]\n"); stf->result->save(); printf("And out!\n"); }
int Main(int argc, char* argv[]) { if(argc!=8) { cout << "Usage: lsvm <data_filename> <train_portion> <mix_seed> <lambda>" " <epsilon_abs> <epsilon_tol> <max_iter>" << endl; return 1; } const char* dataPathStr = argv[1]; const char* trainPortionStr = argv[2]; const char* seedStr = argv[3]; const char* lambdaStr = argv[4]; const char* epsilonAbsStr = argv[5]; const char* epsilonTolStr = argv[6]; const char* maxIterStr = argv[7]; cout << "Data file: " << dataPathStr << endl; Data data; data.ReadFile(dataPathStr); if(!data.IsLoaded()) { cout << "Error while loading data" << endl; return 1; } float trainPortion = atof(trainPortionStr); data.SetTrainTestSplit(trainPortion); int seed = atoi(seedStr); if(seed>=0) { srand(unsigned(seed)); data.Mix(); cout << "Data mixed with seed=" << seed << endl; } else { cout << "Data not mixed" << endl; } Real lambda = Real(atof(lambdaStr)); Real epsilon_abs = Real(atof(epsilonAbsStr)); Real epsilon_tol = Real(atof(epsilonTolStr)); int maxIter = atoi(maxIterStr); cout << endl; cout << "Lambda = " << lambda << endl; cout << "Abs epsilon = " << epsilon_abs << endl; cout << "Tol epsilon = " << epsilon_tol << endl; cout << "Max number of iterations = " << maxIter << endl; cout << "Svm training..." << endl; SVM svm; long long time_svm = -gettimeus(); svm.Train(data, lambda, epsilon_abs, epsilon_tol, maxIter); time_svm += gettimeus(); cout << endl << "Svm training completed." << endl; cout << "svm training time: " << double(time_svm)/1000000 << " seconds" << endl; cout << "Number of variables: " << data.VarNumber() << endl; cout << "Number of samples: " << data.TestSampleIdx().size() + data.TrainSampleIdx().size() << endl; cout << trainPortion*100 << "% of data is used for training" << endl; cout << "Train sample count: " << data.TrainSampleIdx().size() << endl; cout << "Test sample count: " << data.TestSampleIdx().size() << endl; cout << "Train accuracy: " << (1.0-svm.CalcError(data, SVM::TRAIN))*100 << "%" << endl; if(data.TestSampleIdx().size()!=0) { cout << "Test accuracy: " << (1.0-svm.CalcError(data, SVM::TEST))*100 << "%" << endl; } return 0; }
bool ex_hierarchical(void *arg) { Trainer::SetLogLevel(SSI_LOG_LEVEL_DEBUG); ssi_size_t n_classes = 6; ssi_size_t n_samples = 50; ssi_size_t n_streams = 1; ssi_real_t train_distr[][3] = { 0.2f, 0.2f, 0.1f, 0.2f, 0.5f, 0.1f, 0.2f, 0.8f, 0.1f, 0.8f, 0.8f, 0.1f, 0.8f, 0.5f, 0.1f, 0.8f, 0.2f, 0.1f, }; ssi_real_t test_distr[][3] = { 0.5f, 0.5f, 0.5f }; SampleList strain; SampleList sdevel; SampleList stest; ModelTools::CreateTestSamples(strain, n_classes, n_samples, n_streams, train_distr, "user"); ModelTools::CreateTestSamples(sdevel, n_classes, n_samples, n_streams, train_distr, "user"); ModelTools::CreateTestSamples(stest, 1, n_samples * n_classes, n_streams, test_distr, "user"); ssi_char_t string[SSI_MAX_CHAR]; for (ssi_size_t n_class = 1; n_class < n_classes; n_class++) { ssi_sprint(string, "class%02d", n_class); stest.addClassName(string); } ModelTools::PlotSamples(strain, "train", ssi_rect(650, 0, 400, 400)); // non-hierarchical { SVM *model = ssi_create(SVM, 0, true); model->getOptions()->params.kernel_type = LINEAR; model->getOptions()->balance = SVM::BALANCE::OFF; Trainer trainer(model); trainer.train(strain); trainer.eval(sdevel); trainer.cluster(stest); ModelTools::PlotSamples(stest, "svm", ssi_rect(650, 0, 400, 400)); OptionList::SaveXML("svm", model->getOptions()); } // hierarchical { HierarchicalModel *hmodel = ssi_create(HierarchicalModel, 0, true); /* hmodel->initTree(5); hmodel->addNode(0, 0, ssi_create(SVM, "svm", true), "0, 1, 2, 3, 4, 5"); hmodel->addNode(1, 0, ssi_create(SVM, "svm", true), "0, 1, 2, 3, 4"); hmodel->addNode(1, 1, ssi_create(SVM, "svm", true), "5"); hmodel->addNode(2, 0, ssi_create(SVM, "svm", true), "0, 1, 2"); hmodel->addNode(2, 1, ssi_create(SVM, "svm", true), "3, 4"); hmodel->addNode(3, 0, ssi_create(SVM, "svm", true), "0, 1"); hmodel->addNode(3, 1, ssi_create(SVM, "svm", true), "2"); */ hmodel->initTree(2); hmodel->addNode(0, 0, ssi_create(SVM, "svm", true), "0, 1, 2, 3, 4, 5"); hmodel->addNode(1, 0, ssi_create(SVM, "svm", true), "0, 1, 2", "1"); hmodel->addNode(1, 1, ssi_create(SVM, "svm", true), "3, 4, 5", "1"); hmodel->getTree()->print(HierarchicalModel::ToString); Trainer trainer(hmodel); trainer.train(strain); trainer.eval(sdevel); trainer.save("hierarchical"); } { Trainer trainer; Trainer::Load(trainer, "hierarchical"); trainer.eval(sdevel); trainer.cluster(stest); ModelTools::PlotSamples(stest, "hierarchical svm", ssi_rect(650, 0, 400, 400)); } return true; }
void project(const Template &src, Template &dst) const { dst = src; dst.file.set("Label", svm.predict(src.m().reshape(1, 1))); }
void Database::Execute(string com){ size_t tail = com.size()-1; if (tail != 0 && isBlank(com[tail]))--tail; com = com.substr(0,tail+1);//删去末尾空格 size_t poi = 0;//读取字符串的指针 string ex = NextStr(com,poi,' ');//输入的指令操作名 if (IgnoreLU(ex,"sort")){ vector<string> vs; StrSplit(com,vs,' '); comparer.clear(); for (size_t i = 1;i<vs.size();++i){ char c = vs[i][vs[i].size()-1]; bool has = false; bool z = 0; if (c == '-'){ z = 1; has = true; }else if (c == '+')has=true; string s = vs[i].substr(0,vs[i].size()-size_t(has)); //cout << s<<"--"<<vs[i]<<endl; if (IgnoreLU(s,"id"))comparer.push(ID,z); else if (IgnoreLU(s,"name"))comparer.push(NAME,z); else if (IgnoreLU(s,"kind"))comparer.push(KIND,z); else if (IgnoreLU(s,"age"))comparer.push(AGE,z); else if (IgnoreLU(s,"state"))comparer.push(STATE,z); else if (IgnoreLU(s,"sales"))comparer.push(SALES,z); else if (IgnoreLU(s,"events"))comparer.push(EVENTS,z); } cout << "当前排序优先级别为" << endl; comparer.show(); Show(); }else if (IgnoreLU(ex,"update") || IgnoreLU(ex,"set")){ size_t wi = com.rfind("where"); if (wi == string::npos){ cout << "请填写过滤条件,过滤器的使用方法在帮助文档里。" << endl; }else{ Exp* oldFilter = viewFilter; string oldName = filterName; try{ if (com[poi] == '*'){ filterName = "*"; viewFilter = 0; }else{ string condition = com.substr(wi+5); viewFilter = Build(condition); filterName = condition; } }catch(const char *s){ cout << s << endl; } Show(); vector<Staff *> vs; GetStaffList(vs,viewFilter); string choice; while(true){ cout << "是否要对这些数据进行操作?yes:是,no:否" << endl; cin >> choice; if (IgnoreLU(choice,"yes") || choice == "是"){ SVM vm; SBuild bu; streamx ss; //srand(size_t(time(0))); bu.SetStream(ss); JumpSpace(com,poi); string temp = com.substr(poi,wi - poi);//使用SLang的语法糖 #展开 string sl; for(auto &c:temp){ if (c != ' ')sl+=c; } //Macro展开 replace_all_distinct(sl,"=active","=0"); replace_all_distinct(sl,"=resign","=1"); replace_all_distinct(sl,"=leave","=2"); replace_all_distinct(sl,"job=","kind="); replace_all_distinct(sl,"=salesmanager","=3"); replace_all_distinct(sl,"=manager","=2"); replace_all_distinct(sl,"=salesman","=1"); //cout << sl << endl; ss << "#" << sl; //cout << "Slang"<<sl<<endl; SExp *e = bu.Build();//操作生成 for (auto &ps:vs){ vm.SetVar("id",ps->GetID()); vm.SetVar("kind",int(ps->GetKind())); vm.SetVar("age",ps->GetAge()); vm.SetVar("state",ps->GetState()); vm.SetVar("manager_id",-1); if (ps->GetKind() == SALESMAN){ SalesMan *psm = dynamic_cast<SalesMan*>(ps); vm.SetVar("manager_id",psm->GetManagerID()); } vm.SetVar("sales",ps->GetAchievement().sales); vm.SetVar("events",ps->GetAchievement().events); vm.Eval(e); int id = vm.GetVar("id"); int kind = vm.GetVar("kind"); int age = vm.GetVar("age"); int state = vm.GetVar("state"); int manager_id = vm.GetVar("manager_id"); int sales = vm.GetVar("sales"); int events = vm.GetVar("events"); if (age < 200 && state <= 2 && kind <= 3 && kind>=1){ ps -> ChangeAge(age); ps -> ChangeState(STAFF_STATE(state)); if (ps -> GetKind() == SALESMAN){ SalesMan *p = dynamic_cast<SalesMan*>(ps); p -> SetManagerID(manager_id); p -> SetSales(sales); }else{ Manager *p = dynamic_cast<Manager*>(ps); p -> SetEvents(events); } //太麻烦,不做批量更改id了 //牵连太大 if (ps -> GetKind() != kind){ //更改kind if (ps -> GetKind() == SALESMAN){ SalesMan *p = dynamic_cast<SalesMan*>(ps); slaves[p -> GetManagerID()].erase(p -> GetID()); } Staff *o; SalesMan *sa; Manager *ma; SalesManager *sam; switch(kind){ case STAFF://forbid warning case SALESMAN: sa = new SalesMan(ps->GetID(),ps->GetName(),ps->GetAge(),ps->GetState()); sa -> SetSales(sales); sa -> SetManagerID(manager_id); o = dynamic_cast<Staff*>(sa);break; case MANAGER: ma = new Manager(ps->GetID(),ps->GetName(),ps->GetAge(),ps->GetState()); ma -> SetEvents(events); o = dynamic_cast<Staff*>(ma);break; case SALESMANAGER: sam = new SalesManager(ps->GetID(),ps->GetName(),ps->GetAge(),ps->GetState()); sam -> SetEvents(events); o = dynamic_cast<Staff*>(sam);break; } int oid = ps->GetID(); o -> ChangeID(oid); o -> ChangeName(ps->GetName()); o -> ChangeAge(ps->GetAge()); o -> ChangeState(ps->GetState()); delete staffs[oid]; staffs[oid] = o; Update(); } /* if (ps -> GetID() != id && staffs.count(id)==0){ int oid = ps -> GetID(); //更新存储列表和从属关系 staffs[id] = staffs[oid]; staffs.erase(oid); slaves[id] = slaves[oid]; slaves.erase(oid); Update();//低效率解决方案 }*/ }else{ cout << "员工:" << ps->GetName() << "(" << ps->GetID() << ")更新数据时出现错误" << endl; } } cout << "更新操作完毕" << endl; filterName = oldName; viewFilter = oldFilter; changed = true; Update(); Show(); break; }else{ if (IgnoreLU(choice,"no") || choice == "否"){ cout << "已取消操作" <<endl; filterName = oldName; viewFilter = oldFilter; break; }else{ } } } } }else if (IgnoreLU(ex,"filter") || ex == "f"){
int main(void) { using namespace std; const cv::Size2i BlockSize(8, 8); const string sRootPath = "D:/Dataset/01/"; const bool bHOG = true; const bool bLBP = false; // read the smv model # if CV_MAJOR_VERSION < 3 SVM oSVM; oSVM.load("Result.xml"); # else cv::Ptr<cv::ml::SVM> poSVM = cv::ml::StatModel::load<cv::ml::SVM>("hog_02.xml"); # endif // read the positive smaples and calculate the hog feature myImageSequence oPositiveReader(sRootPath + "Positive/", "", "bmp", false); oPositiveReader.SetAttribute(myImageSequence::Attribute::PADDING_LENGTH, 6); std::cout << "loading positive images" << std::endl; cv::Mat mPositiveSample; while (oPositiveReader >> mPositiveSample) { std::cout << "\r" << oPositiveReader.GetSequenceNumberString(); myFeatureExtractor oExtractor(mPositiveSample, BlockSize); if (bHOG) { oExtractor.EnableFeature(myFeatureExtractor::Features::HOG_WITHOUT_NORM); } if (bLBP) { oExtractor.EnableFeature(myFeatureExtractor::Features::LBP_8_1_UNIFORM); } vector<vector<float>> vvfHOGFeature; for (int y = 0; y < mPositiveSample.rows / BlockSize.height; ++y) { for (int x = 0; x < mPositiveSample.cols / BlockSize.width; ++x) { vector<float> vfFeature; oExtractor.Describe(cv::Point2i(x * BlockSize.width, y * BlockSize.height), vfFeature); vvfHOGFeature.push_back(vfFeature); } } cv::Mat mSample(1, static_cast<int>(vvfHOGFeature.size() * vvfHOGFeature.at(0).size()), CV_32FC1); int i = 0; for (const auto& vfHOGFeature : vvfHOGFeature) { for (const auto fFeature : vfHOGFeature) { mSample.at<float>(0, i++) = fFeature; } } # if CV_MAJOR_VERSION < 3 int iPrediction = static_cast<int>(oSVM.predict(mSample)); if (iPrediction == static_cast<int>(mLabels.at<float>(y))) { ++iCorection; } # else auto result = static_cast<int>(poSVM->predict(mSample)); if (result != 1) { std::string sPath = "Wrong/" + std::string("pos") + oPositiveReader.GetSequenceNumberString() + std::string(".jpg"); cv::imwrite(sPath, mPositiveSample); } # endif } //read the negative smaples and calculate the hog feature myImageSequence oNegativeReader(sRootPath + "Negative/", "", "bmp", false); oNegativeReader.SetAttribute(myImageSequence::Attribute::PADDING_LENGTH, 6); std::cout << std::endl << "loading negative images" << std::endl; cv::Mat mNegativeSample; vector<vector<float>> vvfNegativeFeatures; while (oNegativeReader >> mNegativeSample) { myFeatureExtractor oExtractor(mNegativeSample, BlockSize); if (bHOG) { oExtractor.EnableFeature(myFeatureExtractor::Features::HOG_WITHOUT_NORM); } if (bLBP) { oExtractor.EnableFeature(myFeatureExtractor::Features::LBP_8_1_UNIFORM); } vector<vector<float>> vvfHOGFeature; for (int y = 0; y < mNegativeSample.rows / BlockSize.height; ++y) { for (int x = 0; x < mNegativeSample.cols / BlockSize.width; ++x) { vector<float> vfFeature; oExtractor.Describe(cv::Point2i(x * BlockSize.width, y * BlockSize.height), vfFeature); vvfHOGFeature.push_back(vfFeature); } } cv::Mat mSample(1, static_cast<int>(vvfHOGFeature.size() * vvfHOGFeature.at(0).size()), CV_32FC1); int i = 0; for (const auto& vfHOGFeature : vvfHOGFeature) { for (const auto fFeature : vfHOGFeature) { mSample.at<float>(0, i++) = fFeature; } } # if CV_MAJOR_VERSION < 3 int iPrediction = static_cast<int>(oSVM.predict(mSample)); if (iPrediction == static_cast<int>(mLabels.at<float>(y))) { ++iCorection; } # else auto result = static_cast<int>(poSVM->predict(mSample)); if (result != -1) { std::string sPath = "Wrong/" + std::string("neg") + oNegativeReader.GetSequenceNumberString() + std::string(".jpg"); cv::imwrite(sPath, mNegativeSample); } # endif } return 0; }