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; }
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; }
int main(int argc, char * argv[]){ VideoCapture capture; capture.open(0); FileStorage fs; //Read options // read_options(argc,argv,capture,fs); fs.open("parameters.yml", FileStorage::READ); //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; //Read parameters file tld.read(fs.getFirstTopLevelNode()); Mat frame; Mat last_gray; Mat first; if (fromfile){ capture >> frame; cvtColor(frame, last_gray, CV_RGB2GRAY); frame.copyTo(first); }else{
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; }
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; }
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 read_options(int argc, char** argv,VideoCapture& capture,FileStorage &fs){ for (int i=0;i<argc;i++){ if (strcmp(argv[i],"-b")==0){ if (argc>i){ readBB(argv[i+1]); gotBB = true; } else print_help(argv); } if (strcmp(argv[i],"-s")==0){ if (argc>i){ video = string(argv[i+1]); capture.open(video); fromfile = true; } else print_help(argv); } if (strcmp(argv[i],"-p")==0){ if (argc>i){ fs.open(argv[i+1], FileStorage::READ); } else print_help(argv); } if (strcmp(argv[i],"-tl")==0){ tl = true; } if (strcmp(argv[i],"-r")==0){ rep = true; } } }
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; }
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{
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(); }
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; }
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; }
Mat Utility::readFromFile(string fileName) { FileStorage f; Mat matrix; f.open(fileName, FileStorage::READ); f["cameraMatrix"] >> matrix; f.release(); return matrix; }
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(); }
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 ); }
//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{
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; }
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(); }
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; }
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 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(); }
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; }
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; }
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; } }
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; }
void readPathData(fs::path filePath) { FileStorage storage; storage.open(filePath.string(), FileStorage::READ); storage["points"] >> controlPoints; storage["pointsOrders"] >> pointsBezierOrders; storage["distancePerFrame"] >> distancePerFrame; storage["frameRate"] >> frameRate; writeRate = frameRate; storage.release(); curvePoints = generalizedBezierCurve(controlPoints,pointsBezierOrders,1.0/divs); animatePoints = curveAnimateSequence(curvePoints, distancePerFrame); }
stereocam1() { printf("Constructor called!\n"); M1 = Mat::eye(3, 3, CV_64F); M2 = Mat::eye(3, 3, CV_64F); fsL.open(intrinsic_filename, FileStorage::READ); if (fsL.isOpened()) { fsL["M1"] >> M1; fsL["D1"] >> D1; fsL["M2"] >> M2; fsL["D2"] >> D2; fsL.release(); }
int main(int argc, char *argv[]) { if (argc != 3) { cout << "Usage: Prepare [-p|-n] image_list" << endl; return -1; } int pos_flag; if (strcmp(argv[1], "-n") == 0) pos_flag = 0; else if (strcmp(argv[1], "-p") == 0) pos_flag = 1; else return -1; /* get filepaths vector */ ifstream filelist; vector<string> filepaths; string filepath; filelist.open(argv[2]); if (!filelist) { cout << "Can't read image_list!" << endl; return -1; } while (getline(filelist, filepath)) filepaths.push_back(filepath); /* get BOW vocabulary */ Mat img; vector<KeyPoint> keypoints; Mat descriptors; Mat all_descriptors; Ptr<FeatureDetector> detector(new SurfFeatureDetector(SURF_HESSIAN_THRESHOLD)); Ptr<DescriptorExtractor> extractor(new SurfDescriptorExtractor); Mat vocabulary; FileStorage fs; if (!pos_flag) { cout << "Build negative training set." << endl; if (!fs.open("vocabulary.yml", FileStorage::READ)) { cout << "Can't read vocabulary file." << endl; return -1; } fs["vocabulary"] >> vocabulary; fs.release(); }
int Map::getMapFromFile(string filename) { FileStorage fs; fs.open(filename, FileStorage::READ); FileNode n = fs["Map"]; if (n.type() != FileNode::SEQ) return -1; // Map n'est pas une séquence FileNodeIterator it = n.begin(), it_end = n.end(); // Itérateur pour lire la séquence for (; it != it_end; ++it) cout << (string)*it << endl; fs.release(); // énoncer la fermeture return 0; }