当前位置:网站首页>[opencv] - input and output XML and yaml files

[opencv] - input and output XML and yaml files

2022-06-25 08:56:00 I love to learn

ad locum , The study of Chapter 5 is over , Go ahead tomorrow Chapter 6 《《 master imgproc Components 》》, Set sail , Continue refueling .....


1、XML and YAML File info

(1)XML: Extensible markup language .XML The first is a meta markup language . So-called “ Meta tag ”, That is, developers can define their own tags according to their own needs , For example, the tag can be defined 、. Any satisfaction XML The names of naming rules can be marked . This opens the door to different applications . Besides ,XML Is a kind of semantic / Structured language , It describes the structure and semantics of the document .

One 、 What is extensible markup language ?

  • Extensible markup language is a markup language much like hypertext markup language .
  • It's designed to transmit data , Instead of showing the data .
  • Its label is not predefined . You need to define your own tags .
  • It's designed to be self descriptive .
  • It is W3C The recommended standard of .

Two 、 The difference between extensible markup language and hypertext markup language

It is not an alternative to hypertext markup language .

It is a supplement to hypertext markup language .

It is designed for a different purpose than hypertext markup language :

  • It's designed to transmit and store data , The focus is on the content of the data .
  • Hypertext markup language is designed to display data , The focus is on the appearance of the data .

Hypertext markup language is designed to display information , And it aims to transmit information .

The best description of it is : It is an information transmission tool independent of software and hardware .

(2)YAML: Emphasize that the language is data centric , Instead of focusing on Markup Language , And rename it with anti Pu words .YAML Is a high readability , The format used to express a sequence of data .

Scripting language

Because the implementation is simple , The cost of parsing is very low ,YAML Especially suitable for use in scripting languages . List the existing language implementations :Ruby,Java,Perl,Python,PHP,OCaml,JavaScript,Go . except Java and Go, The rest are scripting languages .

serialize

YAML It is more suitable for serialization . Because it is a direct conversion of the host language data type .

The configuration file

YAML It's also good to make configuration files . Write YAML Better than writing XML Much faster ( No need to pay attention to labels or quotation marks ), And ratio ini Documentation is more powerful .

Due to compatibility issues , It is not recommended to use... For data flow between different languages YAML.


2、FileStorage( File store ) The use of class operation files

explain :XML and YAML Is a very widely used file format , You can use XML perhaps YAML Format files store and restore a variety of data structures . You can also store and load any complex data structure , That's one of them opencv Related peripheral data structures , And raw data types , Such as integer or floating-point numbers and text strings .

The following procedure is used to write or read data to XML or YAML In file :

  • 1、 Instantiate a FileStorage Class object , Initialize with the default constructor with parameters ; Or use FileStorage::open() Member function assisted initialization
  • 2、 Use the flow operator << File write operation , perhaps << Read the file
  • 3、 Use FileStorage::release() Function destructs FileStorage Class object , Close the file at the same time .

3、 Instance to explain

【 First step 】XML、YAML Opening of files

(1) Prepare file for writing

explain :FileStorage yes OpenCV in XML and YAML File storage class , Encapsulates all relevant information . It is OpenCV A class that must be used when reading data from or writing data to a file .

The constructor of this class is FileStorage :FileStorage, There are two overloads , as follows :

FileStorage::FileStorage();
FileStorage::FileStorage(const string& source,int flags,const string& encoding=string());
  • For the second constructor with parameters , An example of a write operation is as follows :

    FileStorage fs("abc.xml",FileStorage::WRITE);
    
  • For the first constructor without parameters , You can make its member functions FileStorage::open Write data

    FileStorage fs;
    fs.open("abc.xml",FileStorage::WRITE);
    

(2) Prepare file read operation

What is mentioned above is based on FileStorage::WRITE Write operation for identifier , The read operation uses FileStorage::READ Identifier is enough

  • The first way

    FileStorage fs("abc.xml",FileStorage::READ);
    
  • The second way

    FileStorage fs;
    fs.open("abc.xml",FileStorage::READ);
    

Be careful : The rising operation mode is for YAML The same applies , take XML Switch to YAML that will do

【 The second step 】 Read and write files

(1) Input and output of text and numbers

  • Well defined FileStorage After class object , Writing to a file can use "<<" Operator , for example :

    fs<<"iterationNr"<<100;
    
  • Read the file , Use ">>" Operator , Such as :

    int itNr;
    fs["itreationNr"]>>itNr;
    itNr=(int)fs["iterationNr"];
    

(2)OpenCV Input and output of data structure

  • About OpenCV Input and output of data structure , And basic C++ In the same form , Here's an example :

    // Data structure initialization 
    Mat R=Mat_<uchar>::eye(3,3);
    Mat T=Mat_<double>::zeros(3,1);
    // towards Mat Middle write data 
    fs<<"R"<<R;
    fs<<"T"<<T;
    // from Mat Read data from 
    fs["R"]>>R;
    fs["T"]>>T;
    

【 The third step 】vector(arrays) and maps Input and output of

(1) about vector Structure input and output , Notice that the first element is preceded by ”[“, Add... Before the last element ”]".

fs <<"string"<<"[";// Start reading in string Text sequence 
fs<<"imagel.jpg"<<"Awesomeness"<<"baboon.jpg";
fs<<"]";// Close the sequence 

(2) about map Operation of structure , The use is consistent with “{ ” and “}”, Such as :

fs<<"Mapping";// Start reading in Mapping Text 
fs<<"{"<<"One"<<1;
fs<<"Two"<<2<<"}";

(3) When reading these structures , use FileNode and FileNOdeIterator data structure . about FileStorage Class “[”,“]" The operator returns FileNode data type ; For a series of node, have access to FileNodeIterator.

FileNode n=fs["string"];// Read the string sequence to get the node 
if(n.type()!=FileNode::SEQ)
{
    
    cerr<<" An error occurred ! The string is not a sequence !"<<endl;
    reruen 1;
}
FileNodeIterator it=n.begin(),it_end=n.end();// Traversal node 
for(;it!=it_end;++it)
    cout<<(string)*it<<endl;

【 Step four 】 File close

explain : The file closing operation will be in FileStorage Class is destroyed automatically , But we can also show how to call its destructor FileStorage::release() Realization .FileStorage::release() The function will destruct FileStorage Class object , Close the file at the same time .

Destructor (destructor) Contrary to constructors , When an object ends its life cycle , When the function of the object has been called , The system automatically performs the destructor . Destructors are often used to do “ Clean up the aftermath ” The job of ( For example, when creating an object, use new Opened up a piece of memory space ,delete Will automatically call the destructor to free up memory ).

fs.release();

4、 The sample program :XML and YAML Writing files

#include<opencv2/opencv.hpp>
#include<time.h>
using namespace cv;
int main()
{
    
	// initialization 
	FileStorage fs("D:\\test.yaml", FileStorage::WRITE);
	// Start file writing 
	fs << "frameCount" << 5;
	time_t rawtime; time(&rawtime);
	fs << "calibrationDate" << asctime(localtime(&rawtime));
	Mat cameraMatrix = (Mat_<double>(3, 3) << 1000, 0, 320, 0, 1000, 240, 0, 0, 1);
	Mat distCoeffs = (Mat_<double>(5, 1) << 0.1, 0.01, -0.01, 0, 0);
	fs << "cameraMatrix" << cameraMatrix << "distCoeffs" << distCoeffs;
	fs << "features" << "[";
	for (int i = 0; i < 3; i++) {
    
		int x = rand() % 640;
		int y = rand() % 480;
		uchar lbp = rand() % 256;
		fs << "{:" << "x" << x << "y" << y << "lbp" << "[:";
		for (int j = 0; j < 8; j++) {
    
			fs << ((lbp >> j) & 1);
		}
		fs << "]" << "}";
	}
	fs << "]";
	fs.release();
	printf(" The file is read and written , Please view the generated files in the project directory ");
	getchar();
	return 0;
}

 Insert picture description here

 Insert picture description here

5、 The sample program :XML and YAML File reading

#include<opencv2/opencv.hpp>
#include <time.h> 
#include <string>
using namespace cv;
using namespace std;
int main()
{
    
	// Change font color 
	system("color 6F");
	// initialization 
	FileStorage fs2("D:\\test.yaml", FileStorage::READ);

	//  The first method , Yes FileNode operation 
	int frameCount = (int)fs2["frameCount"];

	string date;
	//  The second method , Use FileNode Operator > > 
	fs2["calibrationDate"] >> date;

	Mat cameraMatrix2, distCoeffs2;
	fs2["cameraMatrix"] >> cameraMatrix2;
	fs2["distCoeffs"] >> distCoeffs2;
	cout << "frameCount: " << frameCount << endl
		<< "calibration date: " << date << endl
		<< "camera matrix: " << cameraMatrix2 << endl
		<< "distortion coeffs: " << distCoeffs2 << endl;
	FileNode features = fs2["features"];
	FileNodeIterator it = features.begin(), it_end = features.end();
	int idx = 0;
	vector<uchar> lbpval;

	// Use FileNodeIterator Ergodic sequence 
	for (; it != it_end; ++it, idx++)
	{
    
		cout << "feature #" << idx << ": ";
		cout << "x=" << (int)(*it)["x"] << ", y=" << (int)(*it)["y"] << ", lbp: (";
		//  We can also use filenode > > std::vector Operators can easily read numeric arrays 
		(*it)["lbp"] >> lbpval;
		for (int i = 0; i < (int)lbpval.size(); i++)
			cout << " " << (int)lbpval[i];
		cout << ")" << endl;
	}
	fs2.release();

	// Program end , Output some help text 
	printf("\n File read complete , Please enter any key to end the program ~");
	getchar();

	return 0;
}

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-dQMnuqbj-1655886565007)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\image-20220622162644420.png)]

原网站

版权声明
本文为[I love to learn]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206250806469018.html