Exemplo n.º 1
0
void ImageMolecule::deserialize(const cv::FileNode& fn)
{
  FileNode atoms = fn["atoms"];
  CV_Assert(atoms.type() == FileNode::SEQ);

  std::map<int, Ptr<ImageAtom> > a_map;
  for (size_t i = 0; i < atoms.size(); i++)
  {
    Ptr<ImageAtom> atom(new ImageAtom);
    atom->deserialize(atoms[i]);
    a_map[atom->uid()] = atom;
    //we will insert from pairs...
    insertAtom(atom);
  }

  FileNode pairs = fn["pairs"];
  CV_Assert(pairs.type() == FileNode::SEQ);
  vector<AtomPair> pairs_temp;
  pairs_temp.resize(pairs.size());
  for (size_t i = 0; i < pairs.size(); i++)
  {
    pairs_temp[i].deserialize(pairs[i]);

    pairs_temp[i].setAtom1(a_map[pairs_temp[i].atom1()->uid()]);
    pairs_temp[i].setAtom2(a_map[pairs_temp[i].atom2()->uid()]);

  }

  insertPairs(pairs_temp);

}
Exemplo n.º 2
0
OpticalMusic& OpticalMusic::unpackFileStorage(string inPath) {
	OpticalMusic *result = new OpticalMusic();
	FileStorage fs(inPath, FileStorage::READ);
	int lineHeight = (int) fs["lineHeight"];
	int spaceHeight = (int) fs["spaceHeight"];
	int perStaff = (int) fs["perStaff"];

	// overwrite default relative anchor position if it is defined in the file
	float anchorRelX = anchorRelXDefault;
	FileNode anchorRelXField = fs["anchorRelX"];
	if (anchorRelXField.type() == FileNode::FLOAT) anchorRelX = (float) anchorRelXField;
	float anchorRelY = anchorRelYDefault;
	FileNode anchorRelYField = fs["anchorRelY"];
	if (anchorRelYField.type() == FileNode::FLOAT) anchorRelY = (float) anchorRelYField;

	string fileName = (string) fs["fileName"];

	result->image = imread(fileName, OpticalMusic::FILE_LOAD_FLAGS);
	result->sp.thickness = lineHeight;
	result->sp.interval = spaceHeight;
	result->sp.perStaff = perStaff;
	result->fileName = fileName;
	result->anchorRel = Point2f(anchorRelX, anchorRelY);

	return *result;
}
Exemplo n.º 3
0
static bool readModelViews( const string& filename, vector<Point3f>& box,
                            vector<string>& imagelist,
                            vector<Rect>& roiList, vector<Vec6f>& poseList )
{
    imagelist.resize(0);
    roiList.resize(0);
    poseList.resize(0);
    box.resize(0);
    
    FileStorage fs(filename, FileStorage::READ);
    if( !fs.isOpened() )
        return false;
    fs["box"] >> box;
    
    FileNode all = fs["views"];
    if( all.type() != FileNode::SEQ )
        return false;
    FileNodeIterator it = all.begin(), it_end = all.end();
    
    for(; it != it_end; ++it)
    {
        FileNode n = *it;
        imagelist.push_back((string)n["image"]);
        FileNode nr = n["rect"];
        roiList.push_back(Rect((int)nr[0], (int)nr[1], (int)nr[2], (int)nr[3]));
        FileNode np = n["pose"];
        poseList.push_back(Vec6f((float)np[0], (float)np[1], (float)np[2],
                                 (float)np[3], (float)np[4], (float)np[5]));
    }
    
    return true;
}
Exemplo n.º 4
0
//==============================================================================
void
ft_data::
read(const FileNode& node)
{
    assert(node.type() == FileNode::MAP);
    int n; node["n_connections"] >> n; connections.resize(n);
    for(int i = 0; i < n; i++){
        char str[256]; const char* ss;
        sprintf(str,"connections %d 0",i); ss = str; node[ss] >> connections[i][0];
        sprintf(str,"connections %d 1",i); ss = str; node[ss] >> connections[i][1];
    }
    node["n_symmetry"] >> n; symmetry.resize(n);
    for(int i = 0; i < n; i++){
        char str[256]; const char* ss;
        sprintf(str,"symmetry %d",i); ss = str; node[ss] >> symmetry[i];
    }
    node["n_images"] >> n; imnames.resize(n);
    for(int i = 0; i < n; i++){
        char str[256]; const char* ss;
        sprintf(str,"image %d",i); ss = str; node[ss] >> imnames[i];
    }
    Mat X; node["shapes"] >> X; int N = X.cols; n = X.rows/2; 
    points.resize(N);
    for(int i = 0; i < N; i++){
        points[i].clear();
        for(int j = 0; j < n; j++){
            Point2f p(X.at<float>(2*j,i),X.at<float>(2*j+1,i));
            if((p.x >= 0) && (p.y >= 0))points[i].push_back(p);
        }
    }
    
}
Exemplo n.º 5
0
 static inline void readVectorOrMat(const FileNode & node, std::vector<T> & v)
 {
     if (node.type() == FileNode::MAP)
     {
         Mat m;
         node >> m;
         m.copyTo(v);
     }
//==============================================================================
void
shape_model::
read(const FileNode& node)
{
    assert(node.type() == FileNode::MAP);
    node["V"] >> V; node["e"] >> e; node["C"] >> C;
    node["Y"] >> Y;
    p = Mat::zeros(e.rows,1,CV_32F);
}
Exemplo n.º 7
0
inline void readFileNodeList(const FileNode& fn, vector<_Tp>& result) {
    if (fn.type() == FileNode::SEQ) {
        for (FileNodeIterator it = fn.begin(); it != fn.end();) {
            _Tp item;
            it >> item;
            result.push_back(item);
        }
    }
}
//==============================================================================
void 
face_tracker::
read(const FileNode& node)
{
  assert(node.type() == FileNode::MAP);
  node["detector"] >> detector;
  node["smodel"]   >> smodel;
  node["pmodel"]   >> pmodel;
  node["annotations"] >> annotations;
}
void loadTex(vector<float>& out){
  FileStorage fs("txtDict.xml", FileStorage::READ);

  FileNode n = fs["TextonDictionary"];
  if(n.type() != FileNode::SEQ){
    cout << "incorrect filetype: " << n.type() << endl;
    fs.release();
    return;
  }

  FileNodeIterator it = n.begin(), it_end = n.end();
  int cnt =0;
  for(;it != it_end;++it){
    out.push_back((float)*it);
    cnt++;
  }
  cout << "finished reading Textons..\n\n";
  fs.release();
}
void loadBins(float* out){
  FileStorage fs("txtDict.xml", FileStorage::READ);

  FileNode n = fs["binArray"];
  if(n.type() != FileNode::SEQ){
    cout << "incorrect filetype: " << n.type() << endl;
    fs.release();
    return;
  }

  FileNodeIterator it = n.begin(), it_end = n.end();
  int cnt =0;
  for(;it != it_end;++it){
    out[cnt] = (float)*it;
    cnt++;
  }
  cout << "finished reading Bins..\n\n";
  fs.release();
}
Exemplo n.º 11
0
//==============================================================================
void 
face_detector::
read(const FileNode& node)
{
  assert(node.type() == FileNode::MAP);
  node["fname"]     >> detector_fname;
  node["x offset"]  >> detector_offset[0];
  node["y offset"]  >> detector_offset[1];
  node["z offset"]  >> detector_offset[2];
  node["reference"] >> reference;
  detector.load(detector_fname.c_str());
}
Exemplo n.º 12
0
//==============================================================================
void 
patch_models::
read(const FileNode& node)
{
  assert(node.type() == FileNode::MAP); 
  node["reference"] >> reference;
  int n; node["n_patches"] >> n; patches.resize(n);
  for(int i = 0; i < n; i++){
    char str[256]; const char* ss;
    sprintf(str,"patch %d",i); ss = str; node[ss] >> patches[i];
  }
}
Exemplo n.º 13
0
static bool readStringList( const string& filename, vector<string>& l )
{
    l.resize(0);
    FileStorage fs(filename, FileStorage::READ);
    if( !fs.isOpened() )
        return false;
    FileNode n = fs.getFirstTopLevelNode();
    if( n.type() != FileNode::SEQ )
        return false;
    FileNodeIterator it = n.begin(), it_end = n.end();
    for( ; it != it_end; ++it )
        l.push_back((string)*it);
    return true;
}
Exemplo n.º 14
0
	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;
	}
Exemplo n.º 15
0
//==============================================================================
void 
face_tracker_params::
read(const FileNode& node)
{
  assert(node.type() == FileNode::MAP);
  int n; node["nlevels"] >> n; ssize.resize(n);
  for(int i = 0; i < n; i++){ char str[256]; const char* ss;
    sprintf(str,"w %d",i); ss = str; node[ss] >> ssize[i].width;
    sprintf(str,"h %d",i); ss = str; node[ss] >> ssize[i].height;
  }
  node["robust"] >> robust;
  node["itol"] >> itol;
  node["ftol"] >> ftol;
  node["scaleFactor"] >> scaleFactor;
  node["minNeighbours"] >> minNeighbours;
  node["minWidth"] >> minSize.width;
  node["minHeight"] >> minSize.height;
}
Exemplo n.º 16
0
static bool readStringList(const string &filename, vector<string> &l)
{
    l.resize(0);
    FileStorage fs(filename, FileStorage::READ);
    if (!fs.isOpened())
        return false;
    FileNode n = fs.getFirstTopLevelNode();
    if (n.type() != FileNode::SEQ)
        return false;
    FileNodeIterator it = n.begin(), it_end = n.end();

    string temp = filename;
    int pos = temp.find_last_of('/') + 1;
    temp = temp.substr(0, pos);
    for (; it != it_end; ++it)
        l.push_back(temp + (string)*it);
    return true;
}
Exemplo n.º 17
0
void NMPTUtils::readMatBinary(const FileNode &tm, Mat &mat) {
    //FileNode tm = fs[name];
    int rows = (int)tm["rows"], cols = (int)tm["cols"], type = (int)tm["type"];
    mat.create(rows,cols,type);
    if (rows > 0 && cols > 0) {
        vector<string> vs;

        FileNode tl = tm["data"];
        //std::cout << tl.type() << std::endl;
        CV_Assert(tl.type() == FileNode::SEQ);
        vs.resize(tl.size());
        for (size_t i = 0; i < tl.size(); i++) {
            tl[i] >> vs[i];
        }
//		CV_Assert(tl.size() == (size_t)numRegs);
//		tm["data"] >> vs;
        string s;
        joinString(vs, s);
        asciiToBinary(s, mat.data, mat.rows*mat.step);
    }
static bool readStringList( const string& filename, const string& tempFile, vector<string>& l )
{

/*  // Immediately generate the file name that we will read from
    FileStorage fs(tempFile, FileStorage::WRITE);
    fs << "images" << "[";
    fs << string(filename);
    fs << "]";
*/

    l.resize(0);
    FileStorage fs(filename, FileStorage::READ);
    if( !fs.isOpened() )
        return false;
    FileNode n = fs.getFirstTopLevelNode();
    if( n.type() != FileNode::SEQ )
        return false;
    FileNodeIterator it = n.begin(), it_end = n.end();
    for( ; it != it_end; ++it )
        l.push_back((string)*it);
               
    return true;
}
Exemplo n.º 19
0
int main(int ac, char** av)
{
    if (ac != 2)
    {
        help(av);
        return 1;
    }

    string filename = av[1];
    { //write
        Mat R = Mat_<uchar>::eye(3, 3),
            T = Mat_<double>::zeros(3, 1);
        MyData m(1);

        FileStorage fs(filename, FileStorage::WRITE);

        fs << "iterationNr" << 100;
        fs << "strings" << "[";                              // text - string sequence
        fs << "image1.jpg" << "Awesomeness" << "../data/baboon.jpg";
        fs << "]";                                           // close sequence

        fs << "Mapping";                              // text - mapping
        fs << "{" << "One" << 1;
        fs <<        "Two" << 2 << "}";

        fs << "R" << R;                                      // cv::Mat
        fs << "T" << T;

        fs << "MyData" << m;                                // your own data structures

        fs.release();                                       // explicit close
        cout << "Write Done." << endl;
    }

    {//read
        cout << endl << "Reading: " << endl;
        FileStorage fs;
        fs.open(filename, FileStorage::READ);

        int itNr;
        //fs["iterationNr"] >> itNr;
        itNr = (int) fs["iterationNr"];
        cout << itNr;
        if (!fs.isOpened())
        {
            cerr << "Failed to open " << filename << endl;
            help(av);
            return 1;
        }

        FileNode n = fs["strings"];                         // Read string sequence - Get node
        if (n.type() != FileNode::SEQ)
        {
            cerr << "strings is not a sequence! FAIL" << endl;
            return 1;
        }

        FileNodeIterator it = n.begin(), it_end = n.end(); // Go through the node
        for (; it != it_end; ++it)
            cout << (string)*it << endl;


        n = fs["Mapping"];                                // Read mappings from a sequence
        cout << "Two  " << (int)(n["Two"]) << "; ";
        cout << "One  " << (int)(n["One"]) << endl << endl;


        MyData m;
        Mat R, T;

        fs["R"] >> R;                                      // Read cv::Mat
        fs["T"] >> T;
        fs["MyData"] >> m;                                 // Read your own structure_

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

        //Show default behavior for non existing nodes
        cout << "Attempt to read NonExisting (should initialize the data structure with its default).";
        fs["NonExisting"] >> m;
        cout << endl << "NonExisting = " << endl << m << endl;
    }

    cout << endl
        << "Tip: Open up " << filename << " with a text editor to see the serialized data." << endl;

    return 0;
}
Exemplo n.º 20
0
int main(int ac, char** av)
{
  if (ac != 2)
  {
    help(av);
    return 1;
  }

  string filename = av[1];

  //write
  {
    FileStorage fs(filename, FileStorage::WRITE);

    cout << "writing images\n";
    fs << "images" << "[";

    fs << "image1.jpg" << "myfi.png" << "baboon.jpg";
    cout << "image1.jpg" << " myfi.png" << " baboon.jpg" << endl;

    fs << "]";

    cout << "writing mats\n";
    Mat R =Mat_<double>::eye(3, 3),T = Mat_<double>::zeros(3, 1);
    cout << "R = " << R << "\n";
    cout << "T = " << T << "\n";
    fs << "R" << R;
    fs << "T" << T;

    cout << "writing MyData struct\n";
    MyData m(1);
    fs << "mdata" << m;
    cout << m << endl;
  }

  //read
  {
    FileStorage fs(filename, FileStorage::READ);

    if (!fs.isOpened())
    {
      cerr << "failed to open " << filename << endl;
      help(av);
      return 1;
    }

    FileNode n = fs["images"];
    if (n.type() != FileNode::SEQ)
    {
      cerr << "images is not a sequence! FAIL" << endl;
      return 1;
    }

    cout << "reading images\n";
    FileNodeIterator it = n.begin(), it_end = n.end();
    for (; it != it_end; ++it)
    {
      cout << (string)*it << "\n";
    }

    Mat R, T;
    cout << "reading R and T" << endl;

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

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

    MyData m;
    fs["mdata"] >> m;

    cout << "read mdata\n";
    cout << m << endl;

    cout << "attempting to read mdata_b\n";   //Show default behavior for empty matrix
    fs["mdata_b"] >> m;
    cout << "read mdata_b\n";
    cout << m << endl;

  }

  cout << "Try opening " << filename << " to see the serialized data." << endl << endl;

  //read from string
  {
    cout << "Read data from string\n";
    string dataString = 
        "%YAML:1.0\n"
        "mdata:\n"
        "   A: 97\n"
        "   X: 3.1415926535897931e+00\n"
        "   id: mydata1234\n";
    MyData m;
    FileStorage fs(dataString, FileStorage::READ | FileStorage::MEMORY);
    cout << "attempting to read mdata_b from string\n";   //Show default behavior for empty matrix
    fs["mdata"] >> m;
    cout << "read mdata\n";
    cout << m << endl;
  }

  //write to string
  {
    cout << "Write data to string\n";
    FileStorage fs(filename, FileStorage::WRITE | FileStorage::MEMORY | FileStorage::FORMAT_YAML);

    cout << "writing MyData struct\n";
    MyData m(1);
    fs << "mdata" << m;
    cout << m << endl;
    string createdString = fs.releaseAndGetString();
    cout << "Created string:\n" << createdString << "\n";
  }

  return 0;
}
Exemplo n.º 21
0
int main(int ac, char** av)
{
  if (ac != 2)
  {
    help(av);
    return 1;
  }

  string filename = av[1];

  //write
  {
    FileStorage fs(filename, FileStorage::WRITE);

    cout << "writing images\n";
    fs << "images" << "[";

    fs << "image1.jpg" << "myfi.png" << "baboon.jpg";
    cout << "image1.jpg" << " myfi.png" << " baboon.jpg" << endl;

    fs << "]";

    cout << "writing mats\n";
    Mat R =Mat_<double>::eye(3, 3),T = Mat_<double>::zeros(3, 1);
    cout << "R = " << R << "\n";
    cout << "T = " << T << "\n";
    fs << "R" << R;
    fs << "T" << T;

    cout << "writing MyData struct\n";
    MyData m(1);
    fs << "mdata" << m;
    cout << m << endl;
  }

  //read
  {
    FileStorage fs(filename, FileStorage::READ);

    if (!fs.isOpened())
    {
      cerr << "failed to open " << filename << endl;
      help(av);
      return 1;
    }

    FileNode n = fs["images"];
    if (n.type() != FileNode::SEQ)
    {
      cerr << "images is not a sequence! FAIL" << endl;
      return 1;
    }

    cout << "reading images\n";
    FileNodeIterator it = n.begin(), it_end = n.end();
    for (; it != it_end; ++it)
    {
      cout << (string)*it << "\n";
    }

    Mat R, T;
    cout << "reading R and T" << endl;

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

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

    MyData m;
    fs["mdata"] >> m;

    cout << "read mdata\n";
    cout << m << endl;

    cout << "attempting to read mdata_b\n";   //Show default behavior for empty matrix
    fs["mdata_b"] >> m;
    cout << "read mdata_b\n";
    cout << m << endl;

  }

  cout << "Try opening " << filename << " to see the serialized data." << endl;

  return 0;
}
Exemplo n.º 22
0
int main() {
	//leap motion data
	Controller controller;
	controller.setPolicy(Leap::Controller::POLICY_IMAGES);
	controller.setPolicy(Leap::Controller::POLICY_BACKGROUND_FRAMES);

	//process variables
	int updateRate;
	int frameAmount; //amount of frame to record
	int counter;
	bool done;
	FileStorage fs;
	vector<string> imagelist;
	FileNode n;
	FileNodeIterator it, it_begin, it_end;
	Size boardSize;
	int64 t1, t2;
	double time;
	Vector slopes_left, slopes_right, position;
	float cameraZ, cameraY, cameraX;

	//behavior options	
	Behaviour behaviour;
	
start:
	//initialization
	updateRate = 100;
	frameAmount = 20; //amount of frame to record
	counter = 0;
	done = false;
	imagelist.clear();
	time = 0;

	behaviour = CheckBehaviour();
	if (behaviour == Quit) return 0;
	else {
		system("cls");
		std::cout << "Press 'q' to quit, 'r' to restart (set focus on image window)\n";
	}

	char key = ' ';
	while (key != 'q' && key != 'r') {

		key = waitKey(updateRate); //refresh rate

		//image acquisition
		Frame frame = controller.frame();
		if (!frame.isValid()) {
			//std::cout << "Frame is Invalid" << std::endl;
			continue;
		}

		ImageList images = frame.images();
		if (images.isEmpty() || images.count() == 1) {
			//std::cout << "imageList.isEmpty()" << std::endl;
			continue;
		}

		Image imageLeft = images[0];
		Image imageRight = images[1];

		cvImgLeft = Mat(imageLeft.height(), imageLeft.width(), CV_8UC1);
		cvImgRight = Mat(imageRight.height(), imageRight.width(), CV_8UC1);		

		cvImgLeft.data = (unsigned char*)imageLeft.data();
		cvImgRight.data = (unsigned char*)imageRight.data();

		//image output
		imshow("Left image", cvImgLeft);
		imshow("Right image", cvImgRight);

		//behaviour check
		switch (behaviour) {
		case Show_images:
			//do nothing
			break;
		case Undistort_images:
			//use Leap Motion distortion map
			UndistortLeap(imageLeft, "Undistorted left image", true);
			UndistortLeap(imageRight, "Undistorted right image", true);
			break;
		case Calib_image_recording:
			//record calibration images
			counter++;
			//done = imgSave(cvImgLeft, cvImgRight, frameAmount, counter);
			done = imgSave(UndistortLeap(imageLeft, "Undistorted left image", true), UndistortLeap(imageRight, "Undistorted right image", true), frameAmount, counter);
			if (done) {
				system("cls");
				std::cout << "Images for calibration recorded!" <<
					"\nPress 'q' to quit, 'r' to restart (set focus on image window)";
				behaviour = Show_images;
			}
			break;
		case Stereo_calibration:
			//read calibration names to list			
			fs.open(calibFileNames, FileStorage::READ);
			n = fs["strings"];                         // Read string sequence - Get node
			if (n.type() != FileNode::SEQ)
			{
				cerr << "strings is not a sequence! FAIL" << endl;
				behaviour = Show_images;
				break;
			}
			it = n.begin();
			it_end = n.end(); // Go through the node
			for (; it != it_end; ++it) {
				imagelist.push_back((string)*it);
				cout << (string)*it << endl;
			}
			fs.release();

			//provide board size
			boardSize.width = 9;
			boardSize.height = 6;

			//apply calibration, save parameters
			StereoCalibration(imagelist, boardSize, true, true);

			//exit calibration, revert to showing images
			behaviour = Show_images;
			break;
		case Hough_circle_transform:
			//apply calibration
			//rectify calibrated images
			//apply threshold
			//Hough circle transform detection
			t1 = getTickCount();
			TrackingHoughCircles(cvImgLeft);
			t2 = getTickCount();
			time = (t2 - t1) / getTickFrequency();
			cout << "\nExecution time (ms): " << time * 1000.0f;
			break;
		case Tracking_blobs:
			//uncalibrated
			//threshold
			//simple blob detector			
			t1 = getTickCount();
			TrackingBlobs(cvImgLeft);
			t2 = getTickCount();
			time = (t2 - t1) / getTickFrequency();
			cout << "\nExecution time (ms): " << time * 1000.0f;
			break;
		case Tracking_contours:
			//uncalibrated
			//threshold
			//blur + contours + enclosing circle			
			t1 = getTickCount();
			TrackingContours(cvImgLeft);
			t2 = getTickCount();
			time = (t2 - t1) / getTickFrequency();
			cout << "\nExecution time (ms): " << time * 1000.0f;
			break;
		case Triangulation:
			//triangulation based on two tracked points and Leap Motion rectify() function
			t1 = getTickCount();

			//get the direction to the centere of object from left and right images
			//since there is only one tracked object, points should correspond
			slopes_left = imageLeft.rectify(GetTrackedPoint(imageLeft));
			slopes_right = imageRight.rectify(GetTrackedPoint(imageRight));

			//Do the triangulation from the rectify() slopes
			//40 mm camera separation
			cameraZ = 40 / (slopes_right.x - slopes_left.x);
			cameraY = cameraZ * slopes_right.y;
			cameraX = cameraZ * slopes_right.x - 20;
			position = Vector(cameraX, -cameraZ, cameraY);

			t2 = getTickCount();
			time = (t2 - t1) / getTickFrequency();
			cout << "\nPosition: " << position;
			cout << "\nExecution time (ms): " << time * 1000.0f;
			break;
		default:
			//do nothing
			break;
		}
	}

	//restart
	if (key == 'r') {
		destroyAllWindows();
		goto start;
	}

	return 0;
}
    void run(int)
    {
        double ranges[][2] = {{0, 256}, {-128, 128}, {0, 65536}, {-32768, 32768},
            {-1000000, 1000000}, {-10, 10}, {-10, 10}};
        RNG& rng = ts->get_rng();
        RNG rng0;
        test_case_count = 4;
        int progress = 0;
        MemStorage storage(cvCreateMemStorage(0));

        for( int idx = 0; idx < test_case_count; idx++ )
        {
            ts->update_context( this, idx, false );
            progress = update_progress( progress, idx, test_case_count, 0 );

            cvClearMemStorage(storage);

            bool mem = (idx % 4) >= 2;
            string filename = tempfile(idx % 2 ? ".yml" : ".xml");

            FileStorage fs(filename, FileStorage::WRITE + (mem ? FileStorage::MEMORY : 0));

            int test_int = (int)cvtest::randInt(rng);
            double test_real = (cvtest::randInt(rng)%2?1:-1)*exp(cvtest::randReal(rng)*18-9);
            string test_string = "vw wv23424rt\"&amp;&lt;&gt;&amp;&apos;@#$@$%$%&%IJUKYILFD@#$@%$&*&() ";

            int depth = cvtest::randInt(rng) % (CV_64F+1);
            int cn = cvtest::randInt(rng) % 4 + 1;
            Mat test_mat(cvtest::randInt(rng)%30+1, cvtest::randInt(rng)%30+1, CV_MAKETYPE(depth, cn));

            rng0.fill(test_mat, CV_RAND_UNI, Scalar::all(ranges[depth][0]), Scalar::all(ranges[depth][1]));
            if( depth >= CV_32F )
            {
                exp(test_mat, test_mat);
                Mat test_mat_scale(test_mat.size(), test_mat.type());
                rng0.fill(test_mat_scale, CV_RAND_UNI, Scalar::all(-1), Scalar::all(1));
                multiply(test_mat, test_mat_scale, test_mat);
            }

            CvSeq* seq = cvCreateSeq(test_mat.type(), (int)sizeof(CvSeq),
                                     (int)test_mat.elemSize(), storage);
            cvSeqPushMulti(seq, test_mat.data, test_mat.cols*test_mat.rows);

            CvGraph* graph = cvCreateGraph( CV_ORIENTED_GRAPH,
                                           sizeof(CvGraph), sizeof(CvGraphVtx),
                                           sizeof(CvGraphEdge), storage );
            int edges[][2] = {{0,1},{1,2},{2,0},{0,3},{3,4},{4,1}};
            int i, vcount = 5, ecount = 6;
            for( i = 0; i < vcount; i++ )
                cvGraphAddVtx(graph);
            for( i = 0; i < ecount; i++ )
            {
                CvGraphEdge* edge;
                cvGraphAddEdge(graph, edges[i][0], edges[i][1], 0, &edge);
                edge->weight = (float)(i+1);
            }

            depth = cvtest::randInt(rng) % (CV_64F+1);
            cn = cvtest::randInt(rng) % 4 + 1;
            int sz[] = {cvtest::randInt(rng)%10+1, cvtest::randInt(rng)%10+1, cvtest::randInt(rng)%10+1};
            MatND test_mat_nd(3, sz, CV_MAKETYPE(depth, cn));

            rng0.fill(test_mat_nd, CV_RAND_UNI, Scalar::all(ranges[depth][0]), Scalar::all(ranges[depth][1]));
            if( depth >= CV_32F )
            {
                exp(test_mat_nd, test_mat_nd);
                MatND test_mat_scale(test_mat_nd.dims, test_mat_nd.size, test_mat_nd.type());
                rng0.fill(test_mat_scale, CV_RAND_UNI, Scalar::all(-1), Scalar::all(1));
                multiply(test_mat_nd, test_mat_scale, test_mat_nd);
            }

            int ssz[] = {cvtest::randInt(rng)%10+1, cvtest::randInt(rng)%10+1,
                cvtest::randInt(rng)%10+1,cvtest::randInt(rng)%10+1};
            SparseMat test_sparse_mat = cvTsGetRandomSparseMat(4, ssz, cvtest::randInt(rng)%(CV_64F+1),
                                                               cvtest::randInt(rng) % 10000, 0, 100, rng);

            fs << "test_int" << test_int << "test_real" << test_real << "test_string" << test_string;
            fs << "test_mat" << test_mat;
            fs << "test_mat_nd" << test_mat_nd;
            fs << "test_sparse_mat" << test_sparse_mat;

            fs << "test_list" << "[" << 0.0000000000001 << 2 << CV_PI << -3435345 << "2-502 2-029 3egegeg" <<
            "{:" << "month" << 12 << "day" << 31 << "year" << 1969 << "}" << "]";
            fs << "test_map" << "{" << "x" << 1 << "y" << 2 << "width" << 100 << "height" << 200 << "lbp" << "[:";

            const uchar arr[] = {0, 1, 1, 0, 1, 1, 0, 1};
            fs.writeRaw("u", arr, (int)(sizeof(arr)/sizeof(arr[0])));

            fs << "]" << "}";
            cvWriteComment(*fs, "test comment", 0);

            fs.writeObj("test_seq", seq);
            fs.writeObj("test_graph",graph);
            CvGraph* graph2 = (CvGraph*)cvClone(graph);

            string content = fs.releaseAndGetString();

            if(!fs.open(mem ? content : filename, FileStorage::READ + (mem ? FileStorage::MEMORY : 0)))
            {
                ts->printf( cvtest::TS::LOG, "filename %s can not be read\n", !mem ? filename.c_str() : content.c_str());
                ts->set_failed_test_info( cvtest::TS::FAIL_MISSING_TEST_DATA );
                return;
            }

            int real_int = (int)fs["test_int"];
            double real_real = (double)fs["test_real"];
            string real_string = (string)fs["test_string"];

            if( real_int != test_int ||
               fabs(real_real - test_real) > DBL_EPSILON*(fabs(test_real)+1) ||
               real_string != test_string )
            {
                ts->printf( cvtest::TS::LOG, "the read scalars are not correct\n" );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }

            CvMat* m = (CvMat*)fs["test_mat"].readObj();
            CvMat _test_mat = test_mat;
            double max_diff = 0;
            CvMat stub1, _test_stub1;
            cvReshape(m, &stub1, 1, 0);
            cvReshape(&_test_mat, &_test_stub1, 1, 0);
            vector<int> pt;

            if( !m || !CV_IS_MAT(m) || m->rows != test_mat.rows || m->cols != test_mat.cols ||
               cvtest::cmpEps( Mat(&stub1), Mat(&_test_stub1), &max_diff, 0, &pt, true) < 0 )
            {
                ts->printf( cvtest::TS::LOG, "the read matrix is not correct: (%.20g vs %.20g) at (%d,%d)\n",
                            cvGetReal2D(&stub1, pt[0], pt[1]), cvGetReal2D(&_test_stub1, pt[0], pt[1]),
                            pt[0], pt[1] );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }
            if( m && CV_IS_MAT(m))
                cvReleaseMat(&m);

            CvMatND* m_nd = (CvMatND*)fs["test_mat_nd"].readObj();
            CvMatND _test_mat_nd = test_mat_nd;

            if( !m_nd || !CV_IS_MATND(m_nd) )
            {
                ts->printf( cvtest::TS::LOG, "the read nd-matrix is not correct\n" );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }

            CvMat stub, _test_stub;
            cvGetMat(m_nd, &stub, 0, 1);
            cvGetMat(&_test_mat_nd, &_test_stub, 0, 1);
            cvReshape(&stub, &stub1, 1, 0);
            cvReshape(&_test_stub, &_test_stub1, 1, 0);

            if( !CV_ARE_TYPES_EQ(&stub, &_test_stub) ||
               !CV_ARE_SIZES_EQ(&stub, &_test_stub) ||
               //cvNorm(&stub, &_test_stub, CV_L2) != 0 )
               cvtest::cmpEps( Mat(&stub1), Mat(&_test_stub1), &max_diff, 0, &pt, true) < 0 )
            {
                ts->printf( cvtest::TS::LOG, "readObj method: the read nd matrix is not correct: (%.20g vs %.20g) vs at (%d,%d)\n",
                           cvGetReal2D(&stub1, pt[0], pt[1]), cvGetReal2D(&_test_stub1, pt[0], pt[1]),
                           pt[0], pt[1] );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }

            MatND mat_nd2;
            fs["test_mat_nd"] >> mat_nd2;
            CvMatND m_nd2 = mat_nd2;
            cvGetMat(&m_nd2, &stub, 0, 1);
            cvReshape(&stub, &stub1, 1, 0);

            if( !CV_ARE_TYPES_EQ(&stub, &_test_stub) ||
               !CV_ARE_SIZES_EQ(&stub, &_test_stub) ||
               //cvNorm(&stub, &_test_stub, CV_L2) != 0 )
               cvtest::cmpEps( Mat(&stub1), Mat(&_test_stub1), &max_diff, 0, &pt, true) < 0 )
            {
                ts->printf( cvtest::TS::LOG, "C++ method: the read nd matrix is not correct: (%.20g vs %.20g) vs at (%d,%d)\n",
                           cvGetReal2D(&stub1, pt[0], pt[1]), cvGetReal2D(&_test_stub1, pt[1], pt[0]),
                           pt[0], pt[1] );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }

            cvRelease((void**)&m_nd);

            Ptr<CvSparseMat> m_s = (CvSparseMat*)fs["test_sparse_mat"].readObj();
            Ptr<CvSparseMat> _test_sparse_ = (CvSparseMat*)test_sparse_mat;
            Ptr<CvSparseMat> _test_sparse = (CvSparseMat*)cvClone(_test_sparse_);
            SparseMat m_s2;
            fs["test_sparse_mat"] >> m_s2;
            Ptr<CvSparseMat> _m_s2 = (CvSparseMat*)m_s2;

            if( !m_s || !CV_IS_SPARSE_MAT(m_s) ||
               !cvTsCheckSparse(m_s, _test_sparse,0) ||
               !cvTsCheckSparse(_m_s2, _test_sparse,0))
            {
                ts->printf( cvtest::TS::LOG, "the read sparse matrix is not correct\n" );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }

            FileNode tl = fs["test_list"];
            if( tl.type() != FileNode::SEQ || tl.size() != 6 ||
               fabs((double)tl[0] - 0.0000000000001) >= DBL_EPSILON ||
               (int)tl[1] != 2 ||
               fabs((double)tl[2] - CV_PI) >= DBL_EPSILON ||
               (int)tl[3] != -3435345 ||
               (string)tl[4] != "2-502 2-029 3egegeg" ||
               tl[5].type() != FileNode::MAP || tl[5].size() != 3 ||
               (int)tl[5]["month"] != 12 ||
               (int)tl[5]["day"] != 31 ||
               (int)tl[5]["year"] != 1969 )
            {
                ts->printf( cvtest::TS::LOG, "the test list is incorrect\n" );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }

            FileNode tm = fs["test_map"];
            FileNode tm_lbp = tm["lbp"];

            int real_x = (int)tm["x"];
            int real_y = (int)tm["y"];
            int real_width = (int)tm["width"];
            int real_height = (int)tm["height"];

            int real_lbp_val = 0;
            FileNodeIterator it;
            it = tm_lbp.begin();
            real_lbp_val |= (int)*it << 0;
            ++it;
            real_lbp_val |= (int)*it << 1;
            it++;
            real_lbp_val |= (int)*it << 2;
            it += 1;
            real_lbp_val |= (int)*it << 3;
            FileNodeIterator it2(it);
            it2 += 4;
            real_lbp_val |= (int)*it2 << 7;
            --it2;
            real_lbp_val |= (int)*it2 << 6;
            it2--;
            real_lbp_val |= (int)*it2 << 5;
            it2 -= 1;
            real_lbp_val |= (int)*it2 << 4;
            it2 += -1;
            CV_Assert( it == it2 );

            if( tm.type() != FileNode::MAP || tm.size() != 5 ||
               real_x != 1 ||
               real_y != 2 ||
               real_width != 100 ||
               real_height != 200 ||
               tm_lbp.type() != FileNode::SEQ ||
               tm_lbp.size() != 8 ||
               real_lbp_val != 0xb6 )
            {
                ts->printf( cvtest::TS::LOG, "the test map is incorrect\n" );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }

            CvGraph* graph3 = (CvGraph*)fs["test_graph"].readObj();
            if(graph2->active_count != vcount || graph3->active_count != vcount ||
               graph2->edges->active_count != ecount || graph3->edges->active_count != ecount)
            {
                ts->printf( cvtest::TS::LOG, "the cloned or read graph have wrong number of vertices or edges\n" );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }

            for( i = 0; i < ecount; i++ )
            {
                CvGraphEdge* edge2 = cvFindGraphEdge(graph2, edges[i][0], edges[i][1]);
                CvGraphEdge* edge3 = cvFindGraphEdge(graph3, edges[i][0], edges[i][1]);
                if( !edge2 || edge2->weight != (float)(i+1) ||
                   !edge3 || edge3->weight != (float)(i+1) )
                {
                    ts->printf( cvtest::TS::LOG, "the cloned or read graph do not have the edge (%d, %d)\n", edges[i][0], edges[i][1] );
                    ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                    return;
                }
            }

            fs.release();
            if( !mem )
                remove(filename.c_str());
        }
    }
KDvoid FileInputOutput ( KDint nIdx )
{
    string  filename = "/data/outputfile.xml.gz";
	string  sOuput;

	// write
    { 
        Mat R = Mat_<uchar>::eye(3, 3),
            T = Mat_<double>::zeros(3, 1);
        MyData m(1);

        FileStorage fs ( filename, FileStorage::WRITE );

        fs << "iterationNr" << 100;
        fs << "strings" << "[";                              // text - string sequence
        fs << "image1.jpg" << "Awesomeness" << "baboon.jpg";
        fs << "]";                                           // close sequence
        
        fs << "Mapping";                              // text - mapping
        fs << "{" << "One" << 1;
        fs <<        "Two" << 2 << "}";               

        fs << "R" << R;                                      // cv::Mat
        fs << "T" << T;

        fs << "MyData" << m;                                // your own data structures

        fs.release();                                       // explicit close
    }

	// read
    {
		sOuput += "Reading: \n";
        
        FileStorage		fs; 
        fs.open ( filename, FileStorage::READ );

        int  itNr;
        itNr = (int) fs [ "iterationNr" ];
		sOuput += itNr;

        if (!fs.isOpened())
        {
            return;
        }

        FileNode n = fs["strings"];                         // Read string sequence - Get node
        if (n.type() != FileNode::SEQ)
        {
            return;
        }

        n = fs["Mapping"];                                // Read mappings from a sequence

        MyData m;
        Mat R, T;

        fs["R"] >> R;                                      // Read cv::Mat
        fs["T"] >> T;
        fs["MyData"] >> m;                                 // Read your own structure_

        //cout << endl 
        //    << "R = " << R << endl;
        //cout << "T = " << T << endl << endl;
        //cout << "MyData = " << endl << m << endl << endl;

        //Show default behavior for non existing nodes
        //cout << "Attempt to read NonExisting (should initialize the data structure with its default).";  
        fs["NonExisting"] >> m;
    }

	g_pController->setMessage ( "See Data Folder" );
}
Exemplo n.º 25
0
//==============================================================================
void
patch_model::
read(const FileNode& node)
{
  assert(node.type() == FileNode::MAP); node["P"] >> P; 
}
Exemplo n.º 26
0
  bool loadGraph(const std::string graph_file)
  {
    LOG(INFO) << "loading graph " << graph_file;
    
    FileStorage fs; 
    fs.open(graph_file, FileStorage::READ);
    
    if (!fs.isOpened()) {
      LOG(ERROR) << "couldn't open " << graph_file;
      return false;
    }
  
    FileNode nd = fs["nodes"]; 
    if (nd.type() != FileNode::SEQ) {
      LOG(ERROR) << "no nodes";

      return false;
    }

    for (FileNodeIterator it = nd.begin(); it != nd.end(); ++it) {
      string type_id = (*it)["typeid"];
      string name;
      (*it)["name"] >> name;
      cv::Point loc;
      loc.x = (*it)["loc"][0];
      loc.y = (*it)["loc"][1];
      bool enable;
      (*it)["enable"] >> enable;
      
      Node* node;
      if (type_id.compare("bm::Webcam") == 0) {
        // TBD make a version of getNode that takes a type_id string
        Webcam* cam_in = getNode<Webcam>(name, loc);
        node = cam_in;

        test_im = cam_in->getImage("out").clone();
        test_im = cv::Scalar(200,200,200);

      } else if (type_id.compare("bm::ScreenCap") == 0) {
        node = getNode<ScreenCap>(name, loc);
        node->update();
      } else if (type_id.compare("bm::ImageNode") == 0) {
        node = getNode<ImageNode>(name, loc);
      } else if (type_id.compare("bm::Sobel") == 0) {
        node = getNode<Sobel>(name, loc);
      } else if (type_id.compare("bm::GaussianBlur") == 0) {
        node = getNode<GaussianBlur>(name, loc);
      } else if (type_id.compare("bm::Buffer") == 0) {
        node = getNode<Buffer>(name, loc);
      } else if (type_id.compare("bm::ImageDir") == 0) {
        node = getNode<ImageDir>(name, loc);
      } else if (type_id.compare("bm::Add") == 0) {
        node = getNode<Add>(name, loc);
      } else if (type_id.compare("bm::Multiply") == 0) {
        node = getNode<Multiply>(name, loc);
      } else if (type_id.compare("bm::AbsDiff") == 0) {
        node = getNode<AbsDiff>(name, loc);
      } else if (type_id.compare("bm::Greater") == 0) {
        node = getNode<Greater>(name, loc);
      } else if (type_id.compare("bm::Resize") == 0) {
        node = getNode<Resize>(name, loc);
      } else if (type_id.compare("bm::Flip") == 0) {
        node = getNode<Flip>(name, loc);
      } else if (type_id.compare("bm::Rot2D") == 0) {
        node = getNode<Rot2D>(name, loc);
      } else if (type_id.compare("bm::Signal") == 0) {
        node = getNode<Signal>(name, loc);
      } else if (type_id.compare("bm::Saw") == 0) {
        node = getNode<Saw>(name, loc);
      } else if (type_id.compare("bm::Tap") == 0) {
        node = getNode<Tap>(name, loc);
      } else if (type_id.compare("bm::TapInd") == 0) {
        node = getNode<TapInd>(name, loc);
      } else if (type_id.compare("bm::Bezier") == 0) {
        node = getNode<Bezier>(name, loc);
      } else if (type_id.compare("bm::Random") == 0) {
        node = getNode<Random>(name, loc);
      } else if (type_id.compare("bm::Mouse") == 0) {
        node = getNode<Mouse>(name, loc);

        input_node = (Mouse*) node;
        if (output_node) {
          input_node->display = output_node->display;
          input_node->win = output_node->win;
          input_node->opcode = output_node->opcode;
        }
      } else if (type_id.compare("bm::Output") == 0) {
        node = getNode<Output>(name, loc);
        output_node = (Output*)node;
        output_node->setup(Config::inst()->out_width, Config::inst()->out_height);
      
        // TBD need better way to share X11 info- Config probably
        if (input_node) {
          input_node->display = output_node->display;
          input_node->win = output_node->win;
          input_node->opcode = output_node->opcode;
        }
      } else {
        LOG(WARNING) << "unknown node type " << type_id << ", assuming imageNode";
        node = getNode<ImageNode>(name, loc);
      }

      if (dynamic_cast<ImageNode*>(node)) {
        (dynamic_cast<ImageNode*> (node))->setImage("out", test_im);
      }
      node->load(it);

      if (name == "output") {
        output_node = (Output*)node;
        cv::Mat tmp;
        node->setImage("in", tmp); 
      }

      LOG(INFO) << type_id << " " << CLTXT << name << CLVAL << " " 
          << node  << " " << loc << " " << enable << CLNRM;
      
      int ind;
      (*it)["ind"] >> ind;
      LOG(INFO) << CLTXT << "first pass inputs " << CLVAL << ind << CLNRM << " " << node->name;

      for (int i = 0; i < (*it)["inputs"].size(); i++) {
        int type;
        string port;

        (*it)["inputs"][i]["type"] >> type;
        (*it)["inputs"][i]["name"] >> port;
      
        LOG(INFO) << "input " << ind << " \"" << node->name
            << "\", type " << type << " " << port;
        
        // TBD make function for this
        /*
        conType con_type = NONE;
        if (type == "ImageNode") con_type = IMAGE;
        if (type == "ImageOut") con_type = IMAGE;
        if (type == "Signal") con_type = SIGNAL;
        if (type == "Buffer") con_type = BUFFER;
        */
        
        node->setInputPort((conType)type, port, NULL, "");
      }
    }

    // second pass for inputs (the first pass was necessary to create them 
    // all in right order
    LOG(INFO) << "second pass inputs";
    for (FileNodeIterator it = nd.begin(); it != nd.end(); ++it) {
      int ind;
      (*it)["ind"] >> ind;
      LOG(INFO) << "second pass inputs " << ind << " " << CLTXT << all_nodes[ind]->name << CLNRM;
      for (int i = 0; i < (*it)["inputs"].size(); i++) {
        int input_ind;
        int type;
        string port;
        string src_port;
        float value;

        (*it)["inputs"][i]["type"] >> type;
        (*it)["inputs"][i]["name"] >> port;
        (*it)["inputs"][i]["src_ind"] >> input_ind;
        (*it)["inputs"][i]["src_port"] >> src_port;
        (*it)["inputs"][i]["value"] >> value;
        
        if (input_ind >= 0) {
        LOG(INFO) << "input " 
            << " " << input_ind << ", type " << type << " " << port << " " << input_ind
            << " " << src_port;
      
          all_nodes[ind]->setInputPort((conType)type, port, all_nodes[input_ind], src_port);
        } // input_ind > 0

        if (type == SIGNAL) {
          
          all_nodes[ind]->setSignal(port, value);
        }

      }
    } // second input pass

    if (output_node == NULL) {
      LOG(WARNING) << CLWRN << "No output node found, setting it to " 
          << all_nodes[all_nodes.size() - 1]->name << CLNRM;
      // TBD could make sure that this node is an output node
      
      output_node = (Output*) all_nodes[all_nodes.size() - 1];
    }

    LOG(INFO) << all_nodes.size() << " nodes total";
    //output_node->loc = cv::Point2f(graph.cols - (test_im.cols/2+100), 20);
    

  } // loadGraph