bool loadCallback(LoadClassifier::Request &req, LoadClassifier::Response &res ) { string id = req.identifier; Classifier *c; if(!createHelper(req.class_type, c)){ res.success = false; return false; } if(!c->load(req.filename)){ res.success = false; return false; } if(classifier_list.find(id) != classifier_list.end()){ cout << "WARNING: ID already exists, overwriting: " << req.identifier << endl; delete classifier_list[id]; } classifier_list[id] = c; res.success = true; return true; }
HeNodeB::HeNodeB ( int idElement, Femtocell *cell) { SetIDNetworkNode (idElement); SetNodeType(NetworkNode::TYPE_HOME_BASE_STATION); SetFemtoCell (cell); double pos_X = cell->GetCellCenterPosition()->GetCoordinateX(); double pos_Y = cell->GetCellCenterPosition()->GetCoordinateY(); CartesianCoordinates *position = new CartesianCoordinates(pos_X, pos_Y); Mobility* m = new ConstantPosition (); m->SetAbsolutePosition (position); SetMobilityModel (m); CreateUserEquipmentRecords(); HenbLtePhy *phy = new HenbLtePhy (); phy->SetDevice(this); SetPhy (phy); ProtocolStack *stack = new ProtocolStack (this); SetProtocolStack (stack); Classifier *classifier = new Classifier (); classifier->SetDevice (this); SetClassifier (classifier); }
/** * @brief Handler::determineFinishMask */ void Handler::determineFinishMask() { finish_img = cv::imread("TrackMask.png", CV_LOAD_IMAGE_GRAYSCALE); dipFinishMask.setSourceImage(&finish_img); dipFinishMask.visionSet2(); finish_img = *dipFinishMask.getEnhancedImage(); cv::imwrite("FinishMask.png", finish_img); Classifier finishClassifier; finishClassifier.setSourceImage(&finish_img); finishClassifier.classifyFinish(); finish_img = *finishClassifier.getLabeldImage(); finish_t *finish = finishClassifier.getFinish(); cout << "finish label:" << int(finish->blobLabel) << "\tinvarianceMoment1:" << finish->invarianceMoment1 << endl; /// Check is finish label is not zero. if (int(finish->blobLabel)){ cout << "Finish mask is created succesfully" << endl; } else{ cerr << "Finish mask is not created" << endl; } }
int main(int argc, char *argv[]) { Classifier* clp; string text; int ch; if((ch=getopt(argc,argv,"hw:"))!=-1){ switch(ch) { case 'h': cout<<"-h ----for help\n-w ----选择数据加载方式:db 表示存储在数据库,mem 表示初始完全加载于内存.默认db\n"; return 0; case 'w': if(!strcmp(optarg,"db")) clp=server("db","navi").clp; else if(!strcmp(optarg,"mem")) clp=server("mem","navi").clp; else { cout<<"Undefined: "<<optarg<<endl; return 1; } while(cin>>text) cout<<"类:"<<clp->classify(text)<<endl; default: return 1; } } clp=server("db","navi").clp; while(cin>>text) cout<<"类:"<<clp->classify(text)<<endl; return 0; }
pair<Emotion, float> EmoDetector::predictBestWinsOneVsAll(cv::Mat& frame) { pair<Emotion, float> best(UNKNOWN, numeric_limits<float>::min()); if (detectors_ext.size() == 0) { return make_pair(UNKNOWN, 0.0f); } for (map<string, pair<vector<Emotion>, Classifier*> >::iterator ii = this->detectors_ext.begin(); ii != this->detectors_ext.end(); ++ii) { if (ii->second.first.size() != 1) { continue; } Emotion emo = ii->second.first[0]; Classifier* cl = ii->second.second; float prediction = cl->predict(frame); if (best.second < prediction) { best.first = emo; best.second = prediction; } } return best; }
ENodeB::ENodeB (int idElement, Cell *cell, double posx, double posy) { SetIDNetworkNode (idElement); SetNodeType(NetworkNode::TYPE_ENODEB); SetCell (cell); CartesianCoordinates *position = new CartesianCoordinates(posx, posy); Mobility* m = new ConstantPosition (); m->SetAbsolutePosition (position); SetMobilityModel (m); m_userEquipmentRecords = new UserEquipmentRecords; EnbLtePhy *phy = new EnbLtePhy (); phy->SetDevice(this); SetPhy (phy); ProtocolStack *stack = new ProtocolStack (this); SetProtocolStack (stack); Classifier *classifier = new Classifier (); classifier->SetDevice (this); SetClassifier (classifier); }
Predictor getTestPredictorLibSvm(){ //Load sample structure SampleStructure sampleStructure = getTestSampleStructure(); //Load training data Array<Sample> trainingData = getTrainingSampleData(); //Make creator lambdas MlCreators creators; creators.rc = new RegressorCreator[1]; creators.rc[0] = [](SampleStructure* st, Array<Sample> training, unsigned index){ svm_parameter svm_param; svm_param.svm_type = EPSILON_SVR; // default for frac.libsvr is EPSILON_SVR, not C_SVC svm_param.kernel_type = LINEAR; // noto changed default from RBF svm_param.degree = 3; svm_param.gamma = 0; // 1/num_features svm_param.coef0 = 0; svm_param.nu = 0.5; svm_param.cache_size = 100; svm_param.C = 1; svm_param.eps = 1e-3; svm_param.p = 0.0; // noto changed default from 0.1 svm_param.shrinking = 1; svm_param.probability = 0; svm_param.nr_weight = 0; svm_param.weight_label = NULL; svm_param.weight = NULL; svm_param.timeout = 86400; // noto Regressor* r = new SvmRegressor(*st, index, &svm_param); r->train(training); return r; }; creators.cc = new ClassifierCreator[1]; creators.cc[0] = [](SampleStructure* st, Array<Sample> training, unsigned index){ Classifier* c = new WafflesDecisionTreeClassifier(*st, index, true); c->train(training); return c; }; creators.bcc = new BinaryClassifierCreator[1]; creators.bcc[0] = [](SampleStructure* st, Array<Sample> training, unsigned index){ BinaryClassifier* r = new ConstantBinaryClassifier(false); r->train(training); return r; }; //TODO build + use takeBest. Predictor p = Predictor(sampleStructure, trainingData, creators); return p; }
pair<Emotion, float> EmoDetector::predictVotingOneVsAllExt(cv::Mat& frame) { map<Emotion,float> votes; if (detectors_ext.size() == 0) { return make_pair(UNKNOWN, 0.0f); } votes.insert(make_pair(NEUTRAL, 0.f)); votes.insert(make_pair(CONTEMPT , 0.f)); votes.insert(make_pair(DISGUST, 0.f)); votes.insert(make_pair(SADNESS, 0.f)); votes.insert(make_pair(ANGER, 0.f)); votes.insert(make_pair(HAPPY, 0.f)); votes.insert(make_pair(FEAR, 0.f)); votes.insert(make_pair(UNKNOWN, 0.f)); for(map<string, pair<vector<Emotion>, Classifier*> >::iterator ii = this->detectors_ext.begin(); ii != this->detectors_ext.end(); ++ii) { vector<Emotion> emo = ii->second.first; // detected emotions Classifier* cl = ii->second.second; float prediction = cl->predict(frame); for(vector<Emotion>::iterator emo_it = emo.begin(); emo_it != emo.end(); ++emo_it) { map<Emotion, float>::iterator it = votes.find(*emo_it); if (it == votes.end()) { votes.insert(make_pair(*emo_it, prediction)); } else{ if (prediction > 0.5) { it->second += 0.5; //1.0; } else { //for(map<Emotion,float>::iterator votes_it = votes.begin(); votes_it != votes.end(); ++votes_it) { // vector<Emotion>::iterator e_it = find(emo.begin(), emo.end(), votes_it->first); // if (e_it == emo.end()) { // // if I dont find emotion in detected emotion // votes_it->second+=1.0; // } //} it->second -= 0.0; } } } } pair<Emotion,float> max_pair = make_pair(UNKNOWN, numeric_limits<float>::min()); for( map<Emotion, float>::iterator ii = votes.begin(); ii != votes.end(); ++ii) { if (ii->second > max_pair.second) { max_pair.first = ii->first; max_pair.second = ii->second; } } return max_pair; }
void inputCallback(const sensor_msgs::Image::ConstPtr& color_image_msg, const sensor_msgs::PointCloud2::ConstPtr& pointcloud_msg) { //ROS_INFO("Input Callback"); //Elements needed for recognition // convert color image to cv::Mat cv_bridge::CvImageConstPtr color_image_ptr; cv::Mat color_image; convertColorImageMessageToMat(color_image_msg, color_image_ptr, color_image); // get color image from point cloud pcl::PointCloud<pcl::PointXYZRGB> point_cloud_src; pcl::fromROSMsg(*pointcloud_msg, point_cloud_src); // cv::Mat color_image = cv::Mat::zeros(point_cloud_src.height, point_cloud_src.width, CV_8UC3); // for (unsigned int v=0; v<point_cloud_src.height; v++) // { // for (unsigned int u=0; u<point_cloud_src.width; u++) // { // pcl::PointXYZRGB point = point_cloud_src(u,v); // if (isnan_(point.z) == false) // color_image.at<cv::Point3_<unsigned char> >(v,u) = cv::Point3_<unsigned char>(point.b, point.g, point.r); // } // } cv::Mat color_image_copy = color_image.clone(); int half_side_length = 50; cv::rectangle(color_image_copy, cv::Point(color_image.cols/2-half_side_length, color_image.rows/2-half_side_length), cv::Point(color_image.cols/2+half_side_length, color_image.rows/2+half_side_length), CV_RGB(0, 255, 0), 3); cv::imshow("color image", color_image_copy); char key= cv::waitKey(20); //std::cout<<key; //char key = 'c'; //std::cout<<"gut"<<std::endl; //std::cout<< "How do you want to name the image? (The name of the data cloud is the same as the one of the image"<<std::endl; if (key=='c') { //The image captured is in 'color_image_copy' and then classified Classifier C; C.imageExtractROI(color_image_copy); C.classify(); } else if (key=='q') ros::shutdown(); }
// Tests the Create function TEST(Classifier, Create) { Classifier *knn = Classifier::create( KNN::getId() ); EXPECT_TRUE( knn != NULL ); //The classifier ID should match KNN EXPECT_TRUE( knn->getId() == KNN::getId() ); EXPECT_TRUE( knn->getClassifierType() == KNN::getId() ); }
int main() { // build a naive bayes classifier Classifier classifier; // test for accuracy classifier.test(); return 0; }
void classify_continuously(Classifier& classifier, const fs::path& val_path, const fs::path& dir) { std::map<std::string, std::string> correct_labels; std::ifstream val_file(val_path.string()); while (!val_file.eof()) { std::string fname = ""; int index = 0; val_file >> fname >> index; if (fname != "") { std::string label = classifier.GetLabel(index); if (label != "") { correct_labels[boost::to_upper_copy(fname)] = label; } } } const int timer = 2; fs::directory_iterator end_iter; while (true) { for (fs::directory_iterator dir_iter(dir) ; dir_iter != end_iter ; ++dir_iter){ if (interrupt_requested()) { return; } if (!fs::is_regular_file(dir_iter->status())) { // skip non-images continue; } string file = dir_iter->path().string(); cv::Mat img = cv::imread(file, -1); if (img.empty()) { // TODO: should we complain? continue; } std::vector<Prediction> predictions; x_clock_start(timer); predictions = classifier.Classify(img); x_clock_end(timer); std::cout << "File: " << file << std::endl; std::cout << "Duration: " << x_get_time(timer) << " sec" << std::endl; auto correct_iter = correct_labels.find(boost::to_upper_copy(dir_iter->path().filename().string())); std::string label = ""; if (correct_iter != correct_labels.end()) { label = correct_iter->second; } std::cout << "Correct label: " << label << std::endl; std::cout << "Predictions: " << predictions.size() << std::endl; for (size_t i = 0; i < predictions.size(); ++i) { Prediction p = predictions[i]; std::cout << std::fixed << std::setprecision(4) << p.second << " - \"" << p.first << "\"" << std::endl; } std::cout << std::endl; std::cout.flush(); } } }
void EmoDetector::init(std::vector<std::string>& classifier_paths) { map<string, pair<vector<Emotion>, Classifier*> > classifiers; for(size_t i = 0; i < classifier_paths.size(); i++) { string clpath = classifier_paths[i]; Classifier* cvD = this->createClassifier(); cvD->load(clpath); string fname = matrix_io_fileBaseName(clpath); // std::cout<<"the file locations starts at: "<<std::endl; Emotion emo = UNKNOWN; vector<string> emotions_list = split_string(fname, "_"); vector<Emotion> fin_emo_list; fin_emo_list.reserve(emotions_list.size()); string label = ""; for(vector<string>::iterator it = emotions_list.begin(); it != emotions_list.end(); ++it) { emo = UNKNOWN; if (*it == "vs") { break; } else if (*it == emotionStrings(NEUTRAL)) { emo = NEUTRAL; } else if (*it == emotionStrings(ANGER)) { emo = ANGER; } else if (*it == emotionStrings(CONTEMPT)) { emo = CONTEMPT; } else if (*it == emotionStrings(DISGUST)) { emo = DISGUST; } else if (*it == emotionStrings(FEAR)) { emo = FEAR; } else if (*it == emotionStrings(HAPPY)) { emo = HAPPY; } else if (*it == emotionStrings(SADNESS)) { emo = SADNESS; } else if (*it == emotionStrings(SURPRISE)) { emo = SURPRISE; } if(emo != UNKNOWN) { if(label.size() > 0) { label.append("_"); } label.append(emotionStrings(emo)); fin_emo_list.push_back(emo); } } pair<vector<Emotion>, Classifier*> value(fin_emo_list, cvD); pair<string, pair<vector<Emotion>, Classifier*> > entry(label, value); classifiers.insert(entry); } init(classifiers); }
Classifier* Classifier::deepCopy() const{ Classifier *newInstance = createInstanceFromString( classifierType ); if( newInstance == NULL ) return NULL; if( !newInstance->deepCopyFrom( this ) ){ delete newInstance; return NULL; } return newInstance; }
int main(int argc, char const *argv[]){ Classifier c; int numClasses, m, d, indexDescriptor, minoritySize; double prob = 0.5; std::string newDir, baseDir, featuresDir, csvOriginal, directory, str, bestDir; std::vector<ImageClass> originalData; if (argc != 3){ std::cout << "\nUsage: ./rebalanceTest (0) (1) (2) (3) (4)\n " << std::endl; std::cout << "\t(0) Directory to place tests\n" << std::endl; std::cout << "\t(1) Image Directory\n" << std::endl; std::cout << "\t(2) Features Directory\n" << std::endl; std::cout << "\t(3) Analysis Directory\n" << std::endl; std::cout << "\t./rebalanceTest Desbalanced/ Desbalanced/original/ Desbalanced/features/ Desbalanced/analysis/ 0\n" << std::endl; exit(-1); } newDir = std::string(argv[1]); baseDir = std::string(argv[2]); // featuresDir = std::string(argv[3]); // analysisDir = std::string(argv[4]); /* Available descriptorMethod: {"BIC", "GCH", "CCV", "Haralick6", "ACC", "LBP", "HOG", "Contour", "Fisher"} Quantization quantizationMethod: {"Intensity", "Luminance", "Gleam", "MSB"} */ std::vector <int> descriptors {1, 2, 3, 4, 5, 6, 7, 8}; for (indexDescriptor = 0; indexDescriptor < (int)descriptors.size(); indexDescriptor++){ d = descriptors[indexDescriptor]; for (m = 1; m <= 5; m++){ csvOriginal = newDir+"/analysis/original_"+descriptorMethod[d-1]+"_"+quantizationMethod[m-1]+"_"; featuresDir = newDir+"/features/"; /* Feature extraction from images */ std::string originalDescriptor = desc(baseDir, featuresDir, d, m, "original"); /* Read the feature vectors */ originalData = ReadFeaturesFromFile(originalDescriptor); numClasses = originalData.size(); if (numClasses != 0){ std::cout << "---------------------------------------------------------------------------------------" << std::endl; std::cout << "Classification using original data" << std::endl; std::cout << "Features vectors file: " << originalDescriptor.c_str() << std::endl; std::cout << "---------------------------------------------------------------------------------------" << std::endl; c.findSmallerClass(originalData, &minoritySize); c.classify(prob, 1, originalData, csvOriginal.c_str(), minoritySize); originalData.clear(); } } } return 0; }
// Tests the EnableNullRejection functions TEST(Classifier, EnableNullRejection) { Classifier classifier; { const bool nullRejectionState = true; EXPECT_TRUE( classifier.enableNullRejection(nullRejectionState) ); EXPECT_TRUE( classifier.getNullRejectionEnabled() == nullRejectionState ); } { const bool nullRejectionState = false; EXPECT_TRUE( classifier.enableNullRejection(nullRejectionState) ); EXPECT_TRUE( classifier.getNullRejectionEnabled() == nullRejectionState ); } }
int main(int argc, char *argv[]) { Network yarp; if (!yarp.checkNetwork()) return 1; ResourceFinder rf; rf.setVerbose(true); rf.configure(argc,argv); Classifier classifier; return classifier.runModule(rf); }
void classify_single_image(Classifier& classifier, const fs::path& file_path) { long ct_repeat=0; long ct_repeat_max=1; int ct_return=0; if (getenv("CT_REPEAT_MAIN")!=NULL) ct_repeat_max=atol(getenv("CT_REPEAT_MAIN")); string file = file_path.string(); std::cout << "---------- Prediction for " << file << " ----------" << std::endl; x_clock_start(1); cv::Mat img = cv::imread(file, -1); x_clock_end(1); CHECK(!img.empty()) << "Unable to decode image " << file; x_clock_start(2); std::vector<Prediction> predictions; for (ct_repeat=0; ct_repeat<ct_repeat_max; ct_repeat++) { predictions = classifier.Classify(img); } x_clock_end(2); /* Print the top N predictions. */ for (size_t i = 0; i < predictions.size(); ++i) { Prediction p = predictions[i]; std::cout << std::fixed << std::setprecision(4) << p.second << " - \"" << p.first << "\"" << std::endl; } }
void check_cv(Index& idx, Classifier& c, double min_accuracy) { std::vector<doc_id> docs = idx.docs(); classify::confusion_matrix mtx = c.cross_validate(docs, 5); ASSERT_GREATER(mtx.accuracy(), min_accuracy); ASSERT_LESS(mtx.accuracy(), 100.0); }
void check_split(Index& idx, Classifier& c, double min_accuracy) { // create splits std::vector<doc_id> docs = idx.docs(); std::mt19937 gen(47); std::shuffle(docs.begin(), docs.end(), gen); size_t split_idx = docs.size() / 8; std::vector<doc_id> train_docs{docs.begin() + split_idx, docs.end()}; std::vector<doc_id> test_docs{docs.begin(), docs.begin() + split_idx}; // train and test c.train(train_docs); classify::confusion_matrix mtx = c.test(test_docs); ASSERT_GREATER(mtx.accuracy(), min_accuracy); ASSERT_LESS(mtx.accuracy(), 100.0); }
int main () { DataBase db("Database.txt", FALSE); std::string name; int cl; float error=0; for(int i=0; i<db.getSize(); i++){ Classifier c; name = db.getElement(i); std::cout<<"Analizying image "<<name<<" ..."<<std::endl; cv::Mat image= cv::imread(name+".jpg"); std::cout<<"Image read..."<<std::endl; if(name[0]=='O' || name[0]=='P'){ std::cout <<"ROI Extraction..."<<std::endl; std::cout<<"Image size: "<<image.size()<<std::endl; c.imageExtractROI(image); } else c.setImage(image); std::cout<<"Image set..."<<std::endl; c.classify(); cl = c.getClass(); if(name[0]=='P' && cl!=PEN) error++; else if(name[0]=='S' && cl!=SCISSORS) error++; else if (name[0]=='O' && cl!=NO_IDENTIFIED) error++; } std::cout<<"Error= "<<error/db.getSize()<<std::endl; return 0; }
bool BAG::addClassifierToEnsemble(const Classifier &classifier,double weight){ trained = false; Classifier *newClassifier = classifier.createNewInstance(); if( newClassifier == NULL ){ return false; } if( !newClassifier->deepCopyFrom( &classifier ) ){ return false; } weights.push_back( weight ); ensemble.push_back( newClassifier ); return false; }
int testRange(std::vector<const typename Classifier<Val>::ExampleTrain*>& tcollect, int start_idx, int end_idx, Classifier<Val>& classifier ) { typename Classifier<Val>::ExamplesTrain test; typename Classifier<Val>::ExamplesTrain train; typename std::vector<const typename Classifier<Val>::ExampleTrain* >::iterator it = tcollect.begin(); for(int idx=0; it != tcollect.end(); ++it, ++idx ) { if( idx < start_idx ) train.push_back( **it ); else if( idx < end_idx ) test.push_back( **it ); else train.push_back( **it ); } classifier.reset(); classifier.train(train); return checkClassifier( test, classifier ); }
int main() { Classifier c; c.add("alyson"); c.add("bob"); c.add("beckie"); c.add("charlie"); c.add("chester"); c.add("alfred"); c.add("hannah"); c.add("armanda"); c.add("cherry"); c.print_all(’a’); cout << endl; c.print_all(’c’); return 0; }
Predictor getTestPredictorWaffles(){ //Load sample structure SampleStructure sampleStructure = getTestSampleStructure(); //Load training data Array<Sample> trainingData = getTrainingSampleData(); //Make creator lambdas MlCreators creators; //Lambdas and side effects are best friends! creators.rc = new RegressorCreator[1]; creators.rc[0] = [](SampleStructure* st, Array<Sample> training, unsigned index){ //Regressor* r = new ConstantRegressor(0); Regressor* r = new WafflesDecisionTreeRegressor(*st, index); r->train(training); return r; }; creators.cc = new ClassifierCreator[1]; creators.cc[0] = [](SampleStructure* st, Array<Sample> training, unsigned index){ Classifier* c = new WafflesDecisionTreeClassifier(*st, index, true); //TODO Why does this random give identical results to the default? c->train(training); return c; }; creators.bcc = new BinaryClassifierCreator[1]; creators.bcc[0] = [](SampleStructure* st, Array<Sample> training, unsigned index){ BinaryClassifier* r = new ConstantBinaryClassifier(false); r->train(training); return r; }; //TODO build + use takeBest. //std::cout << "Making predictor." << std::endl; Predictor p = Predictor(sampleStructure, trainingData, creators); //std::cout << "Made predictor." << std::endl; return p; }
classify::confusion_matrix cv(Index& idx, Classifier& c, bool even) { std::vector<doc_id> docs = idx.docs(); classify::confusion_matrix matrix; auto seconds = common::time<std::chrono::seconds>( [&]() { matrix = c.cross_validate(docs, 5, even); }); std::cerr << "time elapsed: " << seconds.count() << "s" << std::endl; matrix.print(); matrix.print_stats(); return matrix; }
// Tests the GetSetullRejectionCoeff functions TEST(Classifier, GetSetullRejectionCoeff) { Classifier classifier; { const Float nullRejectionCoeff = 2.0; EXPECT_TRUE( classifier.setNullRejectionCoeff(nullRejectionCoeff) ); EXPECT_TRUE( classifier.getNullRejectionCoeff() == nullRejectionCoeff ); } { const Float nullRejectionCoeff = 5.0; EXPECT_TRUE( classifier.setNullRejectionCoeff(nullRejectionCoeff) ); EXPECT_TRUE( classifier.getNullRejectionCoeff() == nullRejectionCoeff ); EXPECT_FALSE( classifier.setNullRejectionCoeff(0.0) ); //This should fail, as the null rejection coeff should be greater than zero EXPECT_FALSE( classifier.setNullRejectionCoeff(-2.0) ); //This should fail, as the null rejection coeff should be greater than zero EXPECT_TRUE( classifier.getNullRejectionCoeff() == nullRejectionCoeff ); } }
pair<Emotion, float> EmoDetector::predictMayorityOneVsAll(cv::Mat& frame){ map<Emotion,float> votes; if (detectors_ext.size() == 0) { return make_pair(UNKNOWN, 0.0f); } for (map<string, pair<vector<Emotion>, Classifier*> >::iterator ii = this->detectors_ext.begin(); ii != this->detectors_ext.end(); ++ii) { if (ii->second.first.size() != 1) { continue; } Emotion emo = ii->second.first[0]; Classifier* cl = ii->second.second; float prediction = cl->predict(frame); map<Emotion, float>::iterator it = votes.find(emo); if (it == votes.end()) { votes.insert(make_pair(emo, prediction)); } else { it->second+=prediction; } } pair<Emotion,float> max_pair = make_pair(UNKNOWN, numeric_limits<float>::min()); for( map<Emotion, float>::iterator ii=votes.begin(); ii!=votes.end(); ++ii){ if (ii->second > max_pair.second){ max_pair.first=ii->first; max_pair.second=ii->second; } } return max_pair; }
void classifyAndMark(const Mat& src, Mat& marked, Classifier& c) { int inLaneStart = 389; marked = Mat(src.size(), src.type()); Mat lab; if (getCvType() >= 0) { cvtColor(src, lab, getCvType()); } else { lab = src; } uchar features[2]; for(int row = 0; row < lab.rows; ++row) { //cout << "Row: " << row << endl; Point3_<uchar> *p = lab.ptr<Point3_<uchar> > (row); Point3_<uchar> *sp = marked.ptr<Point3_<uchar> >(row); //assumes CV_8UC3 LAB color image, with 3 values per pixel for(int col = 0; col < lab.cols; ++col, ++p, ++sp) { //throw away the L // cout << "Col: " << col << endl; getFeatures(p, features); const Instance inst = makeInstance(features, abs(col - inLaneStart), -1); int label = c.classify(inst); if (row == 2) { //cout << "Col " << col << ": " << (int)p->x << ", " << (int)p->y << ", " << (int)p->z << ", " << label << endl; } sp->x = 0; //cout << countPositives << endl; if (label) { sp->y = 0xFF; sp->z = 0; } else { sp->y = 0; sp->z = 0; } } } }
int main(int argc, char **argv) { short frameCount; int width; int height; std::string arg; Input *input; Frame *image; Frame *motion; MHIOPCV *myMHI; Environment *env; MotionDetect *detection; RelevanceVector *rv; Classifier *classifier; ClassifierBehavior *nBayes; try { input = new InputOPCV(); if (argc == 1) { if (!input->open(0)) { std::cerr << "Camera not available" << std::endl; return (1); } } else if (argc == 2) { arg = argv[1]; if (!input->open(arg)) { std::cerr << "Video: " << arg << " not available" << std::endl; return (1); } } else { throw (new ParameterException("./grecon [video file name] | [without parameter gets the camera]")); return (1); } motion = NULL; width = 0; height = 0; frameCount = 0; myMHI = new MHIOPCV(); env = new EnvironmentOPCV(); detection = new MotionDetect(); rv = new RelevanceVectorOPCV(0.5, 0.05); nBayes = new NBayesClassifierOPCV("./trainData/trainData.txt"); classifier = new Classifier(); detection->setMHIBehavior(myMHI); classifier->setClassifier("NBayes", nBayes); classifier->performTrain("NBayes"); while (42) // answer of everything! { image = input->getFrame(); if (!image) break; if (!motion) { width = reinterpret_cast<IplImage *>(image->getImage())->width; height = reinterpret_cast<IplImage *>(image->getImage())->height; motion = new FrameOPCV(width, height, 8, 3); cvZero(reinterpret_cast<IplImage *>(motion->getImage())); // this will change reinterpret_cast<IplImage *>(motion->getImage())->origin = reinterpret_cast<IplImage *>(image->getImage())->origin; } detection->updateMHI(image, motion, env); rv->setWROI(width / 5); rv->setHROI(height / 5); rv->setWSROI((width - ((width / 5) * 2)) / 4); rv->setHSROI((height - ((height / 5) * 2)) / 4); rv->computeVectors(motion, env); ++frameCount; if (frameCount > 14) { frameCount = 0; classifier->performPredict("NBayes", rv); } image->showImage("original"); motion->showImage("motion"); if (cvWaitKey(10) >= 0) break; } cvDestroyWindow("motion"); cvDestroyWindow("original"); } catch (std::exception *e) { std::cerr << "grecon: " << e->what() << std::endl; } return (0); }