当前位置:网站首页>[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)
边栏推荐
- 检测点是否在多边形内
- 5、 Project practice --- identifying man and horse
- Summary of hardfault problem in RTOS multithreading
- LVS-DR模式单网段案例
- 首期Techo Day腾讯技术开放日,628等你!
- Analysis of a video website m3u8 non perceptual encryption
- Object.defineProperty也能监听数组变化?
- Chinese solution cannot be entered after webgl is published
- C language "recursive series": recursive implementation of 1+2+3++ n
- matplotlib matplotlib中决策边界绘制函数plot_decision_boundary和plt.contourf函数详解
猜你喜欢

二、训练fashion_mnist数据集

View all listening events on the current page by browser

RMB 3000 | record "tbtools" video, make a friend and get a cash prize!

C language: bubble sort

Lvs-dr mode multi segment case

对常用I/O模型进行比较说明

UEFI: repair efi/gpt bootloader

声纹技术(六):声纹技术的其他应用

Emergency administrative suspension order issued Juul can continue to sell electronic cigarette products in the United States for the time being

Jmeter接口测试,关联接口实现步骤(token)
随机推荐
Notes on key vocabulary of the original English work biography of jobs (I) [introduction]
备战2022年金九银十必问的1000道Android面试题及答案整理,彻底解决面试的烦恼
Notes on key words in the original English work biography of jobs (VI) [chapter three]
matplotlib matplotlib中决策边界绘制函数plot_decision_boundary和plt.contourf函数详解
Sharepoint:sharepoint server 2013 and adrms Integration Guide
106. simple chat room 9: use socket to transfer audio
atguigu----17-生命周期
紧急行政中止令下达 Juul暂时可以继续在美国销售电子烟产品
通过客户经理的开户二维码开股票账户安全吗?还是去证券公司开户安全?
How to become a software testing expert? From 3K to 17k a month, what have I done?
compiling stm32f4xx_ it. c... “.\Objects\BH-F407.axf“ - 42 Error(s), 1 Warning(s).
How can games copied from other people's libraries be displayed in their own libraries
2、 Training fashion_ MNIST dataset
C language: find all integers that can divide y and are odd numbers, and put them in the array indicated by B in the order from small to large
Is it safe to open a stock account through the account opening QR code of the account manager? Or is it safe to open an account in a securities company?
检测点是否在多边形内
声纹技术(一):声纹技术的前世今生
五、项目实战---识别人和马
Unity--Configurable Joint——简单教程,带你入门可配置关节
[untitled] * * database course design: complete the student information management system in three days**