当前位置:网站首页>[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 .....
List of articles
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;
}


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)]](/img/4e/7944e205c71246d0b0e3747eefca37.png)
边栏推荐
- The city chain technology platform is realizing the real value Internet reconstruction!
- C program termination problem clr20r3 solution
- Level 6 easy to mix words
- How can games copied from other people's libraries be displayed in their own libraries
- 【总结】1361- package.json 与 package-lock.json 的关系
- C # startup program loses double quotation marks for parameters passed. How to solve it?
- (翻译)采用字母间距提高全大写文本可读性的方式
- 《乔布斯传》英文原著重点词汇笔记(一)【 Introduction 】
- 某次比赛wp
- In Section 5 of bramble pie project practice, Nokia 5110 LCD is used to display Hello World
猜你喜欢

C # startup program loses double quotation marks for parameters passed. How to solve it?
![[operation tutorial] how does the tsingsee Qingxi video platform import the old database into the new database?](/img/21/08194ac26dec50c222b88f1f64f894.png)
[operation tutorial] how does the tsingsee Qingxi video platform import the old database into the new database?

Analysis of a video website m3u8 non perceptual encryption

¥3000 | 录「TBtools」视频,交个朋友&拿现金奖!

C#程序终止问题CLR20R3解决方法

4、 Convolution neural networks

城鏈科技平臺,正在實現真正意義上的價值互聯網重構!

A 35 year old Tencent employee was laid off and sighed: a suite in Beijing, with a deposit of more than 7 million, was anxious about unemployment

C language: count the number of characters, numbers and spaces

(翻译)采用字母间距提高全大写文本可读性的方式
随机推荐
WebGL谷歌提示内存不够(RuntimeError:memory access out of bounds,火狐提示索引超出界限(RuntimeError:index out of bounds)
Notes on key words in the original English work biography of jobs (VI) [chapter three]
matplotlib matplotlib中axvline()和axhline()函数
Is it really safe to pay new debts? Is it risky
某视频网站m3u8非感知加密分析
Fault: 0x800ccc1a error when outlook sends and receives mail
Check whether the point is within the polygon
对常用I/O模型进行比较说明
matplotlib matplotlib中决策边界绘制函数plot_decision_boundary和plt.contourf函数详解
行业春寒回暖,持续承压的酒店企业于何处破局?
LVS-DR模式多网段案例
Unity--Configurable Joint——简单教程,带你入门可配置关节
C language "recursive series": recursive implementation of 1+2+3++ n
How to increase the monthly salary of software testing from 10K to 30K? Only automated testing can do it
How to implement a system call
compiling stm32f4xx_it.c... “.\Objects\BH-F407.axf“ - 42 Error(s), 1 Warning(s).
Lvs-dr mode multi segment case
Unknown table 'column of MySQL_ STATISTICS‘ in information_ schema (1109)
[untitled] * * database course design: complete the student information management system in three days**
How to solve the 10061 error of MySQL in Linux