void OneWayDescriptorQualityTest::processRunParamsFile ()
{
    string filename = getRunParamsFilename();
    FileStorage fs = FileStorage (filename, FileStorage::READ);
    FileNode fn = fs.getFirstTopLevelNode();
    fn = fn[DEFAULT_PARAMS];

    string pcaFilename = data_path + (string)fn["pcaFilename"];
    string trainPath = data_path + (string)fn["trainPath"];
    string trainImagesList = (string)fn["trainImagesList"];
    int patch_width = fn["patchWidth"];
    int patch_height = fn["patchHeight"];
    Size patchSize = cvSize (patch_width, patch_height);
    int poseCount = fn["poseCount"];

    if (trainImagesList.length () == 0 )
        return;

    fs.release ();

    readAllDatasetsRunParams();

    Ptr<OneWayDescriptorBase> base(
        new OneWayDescriptorBase(patchSize, poseCount, pcaFilename,
                                 trainPath, trainImagesList));

    Ptr<OneWayDescriptorMatch> match = makePtr<OneWayDescriptorMatch>();
    match->initialize( OneWayDescriptorMatch::Params (), base );
    defaultDescMatcher = match;
    writeAllDatasetsRunParams();
}
void TrackerOPETest::checkDataTest()
{
  string gtFile = cvtest::TS::ptr()->get_data_path() + TRACKING_DIR + "/" + video + "/gt.txt";

  ifstream gt;
  //open the ground truth
  gt.open( gtFile.c_str() );
  if( !gt.is_open() )
  {
    FAIL()<< "Ground truth file " << gtFile << " can not be read" << endl;
  }
  string line;
  int bbCounter = 0;
  while ( getline( gt, line ) )
  {
    vector<string> tokens = splitString( line, "," );
    Rect bb( atoi( tokens.at( 0 ).c_str() ), atoi( tokens.at( 1 ).c_str() ), atoi( tokens.at( 2 ).c_str() ), atoi( tokens.at( 3 ).c_str() ) );
    if( tokens.size() != 4 )
    {
      FAIL()<< "Incorrect ground truth file";
    }
    bbs.push_back( bb );
    bbCounter++;
  }

  FileStorage fs;
  fs.open( cvtest::TS::ptr()->get_data_path() + TRACKING_DIR + "/" + video + "/" + video + ".yml", FileStorage::READ );
  fs["start"] >> startFrame;
  fs["prefix"] >> prefix;
  fs["suffix"] >> suffix;
  fs.release();

}
Esempio n. 3
0
void kNNSearcher::kNNSearchWithHOG(const Mat &inputImage, const QStringList &imPath,
                      Mat &indexes, Mat &weights, int k)
{
    //resize inputImage to the same size of training image
    Mat temp = imread( imPath[0].toLocal8Bit().data(), CV_LOAD_IMAGE_GRAYSCALE );
    Mat inputIm;
    resize( inputImage, inputIm, temp.size() );

    //compute the HOG descriptor of target image
    HOGDescriptor *hogDesr = new HOGDescriptor( cvSize( 640, 480 ), cvSize( 160, 120 ), cvSize( 160,120 ), cvSize( 160, 120 ), 9  );
    std::vector<float> targetDescriptor;
    hogDesr->compute( inputIm, targetDescriptor, Size( 0, 0 ), Size( 0, 0) );
    //###################################################################################

    //load the training descriptors into descriptorMat if there exist a HOGof44blocks.yaml file
    //otherwise, execute the train program
    Mat descriptorMat;

    QString const HOGMatfile = "HOGof44blocks.yaml";
    FileStorage fs;
    fs.open( HOGMatfile.toLocal8Bit().data(), FileStorage::READ );
    if( fs.isOpened() ){
        // the HOGof44blocks.yaml does exist
        fs["HOGMat"] >> descriptorMat;
    }else{
Esempio n. 4
0
    void write( FileStorage& fs ) const
    {
        if( layer_sizes.empty() )
            return;
        int i, l_count = layer_count();

        fs << "layer_sizes" << layer_sizes;

        write_params( fs );

        size_t esz = weights[0].elemSize();

        fs << "input_scale" << "[";
        fs.writeRaw("d", weights[0].ptr(), weights[0].total()*esz);

        fs << "]" << "output_scale" << "[";
        fs.writeRaw("d", weights[l_count].ptr(), weights[l_count].total()*esz);

        fs << "]" << "inv_output_scale" << "[";
        fs.writeRaw("d", weights[l_count+1].ptr(), weights[l_count+1].total()*esz);

        fs << "]" << "weights" << "[";
        for( i = 1; i < l_count; i++ )
        {
            fs << "[";
            fs.writeRaw("d", weights[i].ptr(), weights[i].total()*esz);
            fs << "]";
        }
        fs << "]";
    }
Esempio n. 5
0
int main(int argc, char * argv[]){
  VideoCapture capture;
  capture.open(0);
  FileStorage fs;
  //Read options
  read_options(argc,argv,capture,fs);
  //Init camera
  if (!capture.isOpened())
  {
	cout << "capture device failed to open!" << endl;
    return 1;
  }
  //Register mouse callback to draw the bounding box
  cvNamedWindow("TLD",CV_WINDOW_AUTOSIZE);
  cvSetMouseCallback( "TLD", mouseHandler, NULL );
  //TLD framework
  TLD tld, tld2;
  //Read parameters file
  tld.read(fs.getFirstTopLevelNode());
  tld2.read(fs.getFirstTopLevelNode());
  Mat frame;
  Mat last_gray, last_gray2;
  Mat first;
  if (fromfile){
      capture >> frame;
      cvtColor(frame, last_gray, CV_RGB2GRAY);
      cvtColor(frame, last_gray2, CV_RGB2GRAY);
      frame.copyTo(first);
  }else{
/**
 * For each test file, get their objects and check his class
 */
void recognition() {
	FileStorage fs = FileStorage(std::string("descriptors.yml"),
			FileStorage::READ);
	fillValues(fs, objects);

	for (int i = 0; i < 3; i++) {

		string num = static_cast<std::ostringstream*>(&(std::ostringstream()
				<< i + 1))->str();

		string path = std::string("data/reco") + num + std::string(".pgm");
		std::cout << "-----------------------------" << std::endl;
		std::cout << "-  Fichero: " << path << "  -" << std::endl;
		std::cout << "-----------------------------" << std::endl;

		Mat src = imread(path, CV_LOAD_IMAGE_GRAYSCALE);
		imshow("Image", src);

		getDescriptorsRecognition(src, objects);

		std::cout << "=============================" << std::endl;

		waitKey(0); // wait for key press
	}

	fs.release();
}
Esempio n. 7
0
int Orbit::loadPoints(std::string name)
{
    FileStorage fs;

    string fileName=name+"orbit.yml";
    fs.open(fileName, FileStorage::READ);

    if(fs.isOpened()==false)
    {
        fs.release();
        return -1;
    }

    FileNode orbitNode=fs["orbit"];
    FileNodeIterator it=orbitNode.begin();

    for(size_t i=0;it!=orbitNode.end();i++,it++)
    {

        Point3f tmp;
        (*it)["x"]>>tmp.x;
        (*it)["y"]>>tmp.y;
        (*it)["z"]>>tmp.z;
        cout<<tmp<<endl;
        robotPoints.push_back(tmp);

    }



    fs.release();
    return 0;
}
Esempio n. 8
0
Pattern::Pattern()
{
    //-- Read in the file of parameters
    std::string file_name = "data/book.yml";
    FileStorage fs;
    fs.open(file_name, FileStorage::READ);
    if(fs.isOpened())
    {
        printf("Initializer: %s is opened for reading.\n", file_name.c_str());
        fs["objWidth"]      >> obj_width;
        fs["objHeight"]     >> obj_height;
        fs["intrinsics"]    >> camera.mat_intrinsics;
        fs["extrinsics"]    >> camera.mat_extrinsics;
        fs["corners"]       >> vec_corners;
        fs["distCoeffs"]    >> camera.mat_distCoeffs;
        fs["scale"]         >> scale;

        fs.release();

        printf("Values are\n");
        std::cout << "objWidth: " << obj_width << std::endl
                  << "objHeight: " << obj_height << std::endl
                  << "intrinsics:\n" << camera.mat_intrinsics << std::endl
                  << "extrinsics:\n" << camera.mat_extrinsics << std::endl
                  << "corners: " << vec_corners << std::endl
                  << "distCoeffs:\n" << camera.mat_distCoeffs << std::endl
                  << "H_groundTruth:\n" << H_groundTruth << std::endl;

        printf("Pattern is constructed.\n");
        current_state = PATTERN_STATE_SUCCESS;
    }
int run(int clusterCount = 1024, int attemps = 1, float subsampleRatio = 0.125, int numKmeansIteration = 10000, float eps = 0.00001)
{
	cout<<"Reading allHogs.yml ..."<<endl;
	FileStorage fs;
	fs.open("allHogs.yml", FileStorage::READ);
	int num_features;
	fs["NUM_FEATURES"] >> num_features;
	cout<<num_features<<endl;
	cv::Mat allHogs;
	fs["all_hog_features"] >> allHogs;
	cout<<allHogs.cols<<endl;
	cout<<"done!"<<endl;

	Mat labels;
	Mat centers;
	cout<<"Sub-sampling ... "<<endl;
	int subsampleCount = int( subsampleRatio * allHogs.rows);
	Mat subsample = rand_select_and_shuffle( allHogs, subsampleCount);
	cout<<"Running K-Means ... "<<endl;
	kmeans(subsample, clusterCount, labels, TermCriteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, numKmeansIteration, eps), attemps, KMEANS_PP_CENTERS, centers);
	cout<<"done!"<<endl;
	cout<<"Writing Results ... "<<endl;
	FileStorage fsw("allCenters.yml", FileStorage::WRITE);
	fsw << "centers" << centers;
	fsw.release();
	fs.release();
	return 0;
}
Esempio n. 10
0
int Orbit::savePoints(std::string name)
{
    FileStorage fs;

    string fileName=name+"orbit.yml";
    fs.open(fileName, FileStorage::WRITE);

    if(fs.isOpened()==false)
    {
        fs.release();
        return -1;
    }

    fs<<"orbit";
    fs<<"[";
    for(size_t i=0;i<robotPoints.size();i++)
    {
        fs<<"{";
        fs<<"x"<<robotPoints[i].x;
        fs<<"y"<<robotPoints[i].y;
        fs<<"z"<<robotPoints[i].z;
        fs<<"}";

    }
    fs<<"]";


    fs.release();
    return 0;

}
Esempio n. 11
0
int CV_StereoMatchingTest::processStereoMatchingResults( FileStorage& fs, int caseIdx, bool isWrite,
              const Mat& leftImg, const Mat& rightImg,
              const Mat& trueLeftDisp, const Mat& trueRightDisp,
              const Mat& leftDisp, const Mat& rightDisp,
              const QualityEvalParams& qualityEvalParams )
{
    // rightDisp is not used in current test virsion
    int code = cvtest::TS::OK;
    assert( fs.isOpened() );
    assert( trueLeftDisp.type() == CV_32FC1 );
    assert( trueRightDisp.empty() || trueRightDisp.type() == CV_32FC1 );
    assert( leftDisp.type() == CV_32FC1 && rightDisp.type() == CV_32FC1 );

    // get masks for unknown ground truth disparity values
    Mat leftUnknMask, rightUnknMask;
    DatasetParams params = datasetsParams[caseDatasets[caseIdx]];
    absdiff( trueLeftDisp, Scalar(params.dispUnknVal), leftUnknMask );
    leftUnknMask = leftUnknMask < numeric_limits<float>::epsilon();
    assert(leftUnknMask.type() == CV_8UC1);
    if( !trueRightDisp.empty() )
    {
        absdiff( trueRightDisp, Scalar(params.dispUnknVal), rightUnknMask );
        rightUnknMask = rightUnknMask < numeric_limits<float>::epsilon();
        assert(leftUnknMask.type() == CV_8UC1);
    }

    // calculate errors
    vector<float> rmss, badPxlsFractions;
    calcErrors( leftImg, rightImg, trueLeftDisp, trueRightDisp, leftUnknMask, rightUnknMask,
                leftDisp, rightDisp, rmss, badPxlsFractions, qualityEvalParams );

    if( isWrite )
    {
        fs << caseNames[caseIdx] << "{";
        //cvWriteComment( fs.fs, RMS_STR.c_str(), 0 );
        writeErrors( RMS_STR, rmss, &fs );
        //cvWriteComment( fs.fs, BAD_PXLS_FRACTION_STR.c_str(), 0 );
        writeErrors( BAD_PXLS_FRACTION_STR, badPxlsFractions, &fs );
        fs << "}"; // datasetName
    }
    else // compare
    {
        ts->printf( cvtest::TS::LOG, "\nquality of case named %s\n", caseNames[caseIdx].c_str() );
        ts->printf( cvtest::TS::LOG, "%s\n", RMS_STR.c_str() );
        writeErrors( RMS_STR, rmss );
        ts->printf( cvtest::TS::LOG, "%s\n", BAD_PXLS_FRACTION_STR.c_str() );
        writeErrors( BAD_PXLS_FRACTION_STR, badPxlsFractions );

        FileNode fn = fs.getFirstTopLevelNode()[caseNames[caseIdx]];
        vector<float> validRmss, validBadPxlsFractions;

        readErrors( fn, RMS_STR, validRmss );
        readErrors( fn, BAD_PXLS_FRACTION_STR, validBadPxlsFractions );
        int tempCode = compareErrors( rmss, validRmss, rmsEps, RMS_STR );
        code = tempCode==cvtest::TS::OK ? code : tempCode;
        tempCode = compareErrors( badPxlsFractions, validBadPxlsFractions, fracEps, BAD_PXLS_FRACTION_STR );
        code = tempCode==cvtest::TS::OK ? code : tempCode;
    }
    return code;
}
Esempio n. 12
0
int main(int ac, char** av)
{
  string filename = "./data/file.yml";
  { //write
	Mat R = Mat_<uchar>::eye(3, 3),
	  T = Mat_<double>::zeros(3, 1);
	MyData m(1);
	FileStorage fs(filename, FileStorage::WRITE);

	fs << "R" << R;
	fs << "T" << T;
	fs.release();
	cout << "Write Done." << endl;
  }

  {
	cout << endl << "Reading: " << endl;
	FileStorage fs;
	fs.open(filename, FileStorage::READ);
	MyData m;
	Mat R, T;

	fs["R"] >> R;
	fs["T"] >> T;
	fs["MyData"] >> m;

	cout << endl
		 << "R = " << R << endl;
	cout << "T = " << T << endl << endl;

  }
  return 0;
}
void TODBaseImporter::importGroundTruth(int testImageIdx, PoseRT &model2test, bool shiftByOffset, PoseRT *offsetPtr, bool isKeyFrame) const
{
  std::stringstream testPoseFilename;
  if (isKeyFrame)
  {
    testPoseFilename << testFolder +"/image_" << std::setfill('0') << std::setw(5) << testImageIdx << ".png.pose.yaml.kf";
  }
  else
  {
    testPoseFilename << testFolder +"/image_" << std::setfill('0') << std::setw(5) << testImageIdx << ".png.pose.yaml";
  }
  FileStorage testPoseFS;
  testPoseFS.open(testPoseFilename.str(), FileStorage::READ);
  CV_Assert(testPoseFS.isOpened());

  testPoseFS["pose"]["rvec"] >> model2test.rvec;
  testPoseFS["pose"]["tvec"] >> model2test.tvec;
  testPoseFS.release();

  if (shiftByOffset || offsetPtr != 0)
  {
    PoseRT offset;
    importOffset(offset);
    if (shiftByOffset)
    {
      model2test = model2test * offset;
    }
    if (offsetPtr != 0)
    {
      *offsetPtr = offset;
    }
  }
}
void DetectorQualityEvaluator::openToWriteKeypointsFile( FileStorage& fs, int datasetIdx )
{
    string filename = data_path + KEYPOINTS_DIR + algName + "_"+ DATASET_NAMES[datasetIdx] + ".xml.gz" ;

    fs.open(filename, FileStorage::WRITE);
    if( !fs.isOpened() )
        printf( "keypoints can not be written in file %s because this file can not be opened\n", filename.c_str() );
}
bool ImageUtils::loadMatrix(const string& filename, const string& tag, Mat& matrixOut) {
	FileStorage fs;
	if (fs.open(filename, FileStorage::READ)) {		
		fs[tag] >> matrixOut;

		fs.release();
		return true;
	}
Esempio n. 16
0
void readKeypointsAndDesc( char* ymlpath , std::vector<KeyPoint>& ref_keypoints , Mat& ref_desc ){
	FileStorage fs ;
	fs.open(  ymlpath , FileStorage::READ);
    if(fs.isOpened()){
            read(fs["desc"], ref_keypoints ); 
            read(fs["kps"], ref_desc);   
    }   
	fs.release();
}
Esempio n. 17
0
int main3 ( int argc, char** argv )
{

    int nh;
    char* data;
    //Check params
    if(argc >= 2 )
    {
        nh= atoi(argv[1]);
        data= argv[2];
    }else{
        cout << "Usage:\n" << argv[0] << " <num hidden nodes> <data to load from xml>\n";
        return 0;
    }    
    
    Mat classes;
    Mat trainingData;
    
    //Read file storage.
    FileStorage fs;
    fs.open("OCR.xml", FileStorage::READ);
    
    fs[data] >> trainingData;
    fs["classes"] >> classes;

    float result;
    
    //init random generator
    srand(time(NULL));
    //Create 100 random pos for samples
    std::vector<int> isSample(trainingData.rows,0);
    generateRandom(0,0,trainingData.rows-1,&isSample);

    //Create sample data
    Mat train, trainClasses;
    Mat samples, samplesClasses;
    for(int i=0; i<trainingData.rows; i++){
        if(isSample[i]==1){
            samples.push_back(trainingData.row(i));
            samplesClasses.push_back(classes.row(i));
        }else{
            train.push_back(trainingData.row(i));
            trainClasses.push_back(classes.row(i));
            
        }
    }
    
    result= 0;
    
    ocr.train(train, trainClasses, nh);
    result=test(samples, samplesClasses);
    
    //cout << nh <<  "\t" << data << "\t"<< result <<"\n";
    cout << result ;

    return 0;
}
Esempio n. 18
0
Mat Utility::readFromFile(string fileName) {
    FileStorage f;
    Mat matrix;
    f.open(fileName, FileStorage::READ);
    f["cameraMatrix"] >> matrix;
    f.release();

    return matrix;
}
Esempio n. 19
0
bool CameraCalibration::readCameraInfo()
{
    FileStorage fs;
    if ( fs.open( "camera_calibration.yml", FileStorage::READ ) ) {
        fs["Camera_Matrix"] >> cameraMatrix;
        fs["Distortion_Coefficients"] >> distortionCoefficients;
        fs.release();
        return( true );
    }
Esempio n. 20
0
//Save Camera Parameter
void DialogRange::on_scpBut_clicked()
{
    {//read
        FileStorage fs;
        if (fs.open("out_camera_data.xml", FileStorage::READ)){
            fs["Camera_Matrix"]>>cm;
            fs["Distortion_Coefficients"] >> dc;
            fs.release();
        }else{
Esempio n. 21
0
int run_demo()
{
	//cv::initModule_nonfree();
	//cout <<"initModule_nonfree() called" << endl;

	// Input and output image path.
	const char * imgInFile = "/sdcard/nonfree/img1.jpg";
	const char * imgOutFile = "/sdcard/nonfree/img1_result.jpg";

	Mat image;
	image = imread(imgInFile, CV_LOAD_IMAGE_COLOR);
	if(! image.data )
	{
		LOGI("Could not open or find the image!\n");
		return -1;
	}

	vector<KeyPoint> keypoints;
	Mat descriptors;

	// Create a SIFT keypoint detector.
	SiftFeatureDetector detector;
	detector.detect(image, keypoints);
	LOGI("Detected %d keypoints\n", (int) keypoints.size());

	// Compute feature description.
	detector.compute(image,keypoints, descriptors);
	LOGI("Compute feature.\n");

	// Store description to "descriptors.des".
	FileStorage fs;
	fs.open("descriptors.des", FileStorage::WRITE);
	LOGI("Opened file to store the features.\n");
	fs << "descriptors" << descriptors;
	LOGI("Finished writing file.\n");
	fs.release();
	LOGI("Released file.\n");

	// Show keypoints in the output image.
	Mat outputImg;
	Scalar keypointColor = Scalar(255, 0, 0);
	drawKeypoints(image, keypoints, outputImg, keypointColor, DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
	LOGI("Drew keypoints in output image file.\n");

#ifdef WIN32
	namedWindow("Output image", CV_WINDOW_AUTOSIZE );
	imshow("Output image", outputImg);
	waitKey(0);
#endif
	
	LOGI("Generate the output image.\n");
	imwrite(imgOutFile, outputImg);

	LOGI("Done.\n");
	return 0;
}
Esempio n. 22
0
void GroundPlane::readCameraMatrix()
{

    cout << endl << "Reading: " << endl;
    FileStorage fs;
    if (fs.open("out_camera_data.xml", FileStorage::READ)){
        fs["Camera_Matrix"]>>cm;
        fs["Distortion_Coefficients"] >> dc;
        fs.release();
    }else{
void DataSet::saveDataSet(String filename){

	FileStorage fs;
	fs.open(filename, FileStorage::WRITE);
	fs << "type"<<2;
	fs << "Input"<<DataSet::getInput();
	fs << "Output"<<DataSet::getDesiredOutput();

	fs.release();
}
Esempio n. 24
0
void Classifier::SaveClassifierToFile(string fileName)
{
	if (em_model.isTrained() == false)
		return;

	FileStorage fs = FileStorage(fileName, FileStorage::WRITE);
	em_model.write(fs);

	fs.release();
}
Esempio n. 25
0
ostream & operator<<(ostream & os, const _eePose& toPrint)
{
  FileStorage st;
  st.open("tmp.yml", FileStorage::WRITE | FileStorage::MEMORY);
  st << "eePose"; 
  toPrint.writeToFileStorage(st);
  string result = st.releaseAndGetString();
  os << result.substr(10, result.size());
  return os;
} 
Esempio n. 26
0
void loaddistancematrix(){
	tic();
	FileStorage fs;
	printf("Opening data file...\n");
	fs.open("distances.yml", FileStorage::READ);
	if(fs.isOpened()){
		//file already computed, load it
		printf("Loading data...\n");
		fs["distances"] >> distances;
		fs["freespace"] >> freespace;
		}
Esempio n. 27
0
void DialogRange::ReadCameraMatrix()
{
    cout << endl << "Reading: " << endl;
    FileStorage fs;
    fs.open("out_camera_data.xml", FileStorage::READ);

    fs["Camera_Matrix"]>>cm;
    fs["distortion_coefficients"] >> dc;
    fs.release();

}
Esempio n. 28
0
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;
}
Esempio n. 29
0
Mat Utility::readFromFile(string fileName) {
    FileStorage f;
    Mat matrix;
    f.open(fileName, FileStorage::READ);
    if(!f.isOpened()) {
        throw string("Unable to open the file");
    }
    f["cameraMatrix"] >> matrix;
    f.release();

    return matrix;
}
Esempio n. 30
0
    void load()
    {
        vector<string> path_preference{
            "config.yaml",
            "/etc/photo-booth/config.yaml"
        };
        FileStorage fs;
        for (string &path : path_preference)
        {
            fs.open(path, FileStorage::READ);

            if (fs.isOpened())
            {
                // TODO: Debug level before reading config
                //cout << "Reading configuration from " << path << endl;
                break;
            }
        }
        if (!fs.isOpened())
        {
            // TODO: Log search path.
            throw runtime_error(string(_("Couldn't find config file.")));
        }

        string boolString;
        fs["debug"] >> boolString;
        debug = (boolString == "true");

        fs["motion_interval"] >> motion_interval;
        fs["frame_pause"] >> frame_pause;
        fs["satisfied_pause"] >> satisfied_pause;
        fs["output_dir"] >> output_dir;
        fs["camera_id"] >> camera_id;
        fs["countdown"] >> countdown;
        fs["initial_countdown"] >> initial_countdown;
        fs["minimum_area"] >> minimum_area;
        fs["max_allowed_area"] >> max_allowed_area;
        fs["acculum_weight"] >> acculum_weight;
        fs["motion_score_threshold"] >> motion_score_threshold;
        fs["sound_cmd"] >> sound_cmd;

        // Expand output_dir path.
        wordexp_t exp_result;
        wordexp(output_dir.c_str(), &exp_result, 0);
        output_dir = exp_result.we_wordv[0];
        wordfree(&exp_result);

        // Copy the map of soundfiles.
        for (FileNode sound : fs["sounds"])
        {
            sounds[sound.name()] = (string)sound;
        }
    }