当前位置:网站首页>[opencv] opencv from introduction to mastery -- detailed explanation of input and output XML and yaml files
[opencv] opencv from introduction to mastery -- detailed explanation of input and output XML and yaml files
2022-06-25 20:37:00 【SophiaCV】
1、XML and YAML File info
XML A document is a kind of Meta markup language , That is, developers can define their own tags according to their own needs . It is a semantic and structural language , Describes the... Of the document Semantics and structure .
YAML Data centric , Is a high readability , The format used to express a sequence of data ..yml and .yaml by YAML The suffix of the file .
YAML Try to compare XML A more agile way to accomplish XML The task accomplished .
2、FileStorage Class operation file
The following procedure is generally used to write or read data to XML or YAML In file
(1) Instantiate a FileStorage Class object , use Default with parameters The constructor for completes initialization , Or use FileStorage::open() Member function assisted initialization
(2) Use the flow operator << Document in progress Write operation , perhaps >> Document in progress Read operation
(3) Use FileStorage::release() Function destructs FileStorage Class object , Close the file at the same time
Right below 2 The three steps in
【 First step 】XML、YAML Opening of files
(1) Prepare file write operation
FileStorage yes OpenCV in XML and YAML Of documents Storage class , Encapsulates all relevant information . yes OpenCV From file Reading data or Write data to file A class that must be used when .
Constructor is FileStorage::FIleStorage, There are two overloads :
FIleStorage::FileStorage()
FIleStorage::FileStorage(const string& source, int flags, const string& encoding=string())For the first constructor without parameters , You can use member functions FileStorage::open Write data :
FileStorage fs;
fs.open("abc.xml", FileStorage::WRITE);
For the second constructor with parameters , Write operation :
fs.open("abc.xml", FileStorage::WRITE);(2) Prepare file read operation
use FileStorage::READ Read the identifier :
The first way :
fs.open("abc.xml", FileStorage::READ);The second way :
FileStorage fs;
fs.open("abc.xml", FileStorage::READ);The above operation is based on XML File as an example , about YAML The same applies to documents .
【 The second step 】 Read and write files
(1) Input and output of text and numbers
Well defined FileStorage After class object , write file have access to “<<” Operator , Such as
fs<<“iterationNr”<<100Read the file , Use “>>” Operator , Such as :
int inNr;
fs["iterationNr"]>>itNr;
itNr = (int)fs["iterationNr"];(2)OpenCV Input and output of data structure
OpenCV The input and output of data structure and basic C++ In the same form , Such as :
// Initialization of manual data structure
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
about vector structure Input and output of , Note that you need to add... Before an element “[”, Add... Before the last element “]”, Such as :
fs << "string" << "["; // Start reading in string Text sequence
fs << "imagel.jpg" << "Awesomeness" << "baboon.jpg";
fs << "]"; // Close the sequence about maps structure The operation of , The symbol used is “{” and “}”, Such as :
fs << "mapping"; // Start reading in mapping Text
fs << "{" << "One" << 1;
fs << "Two" << 2 << "}";When reading these structures , use FileNode and FileNodeIterator data structure .FileStorage Class “[”、“]” The operator returns FileNode data type ; For a series of node, have access to FileNoelIterator structure , Such as :
FileNode n = fs["strings"]; // Read the string sequence to get the node
if(n.type() != FileNode::SEQ)
{
cerr << " An error occurred ! The string is not a sequence !" << endl;
return 1;
}
FileNodeIterator it = n.begin(), it_end = n.end(); // Traversal node
for(; it != it_end; ++it)
cout << (string)*it << endl;【 Fourth parts 】 File close
File closing will FileStorage Class is automatically closed when it is destroyed , However, it is also possible to show that it is called Destructor FileStorage::release() Realization .
Destructor FileStorage::release() Will deconstruct FileStorage Class object , Close the file at the same time .
Call the process :
fs.release();The sample program
【1】 The sample program :XML and YAML Writing files
//---------------------------------【 The header file 、 The namespace contains some 】-------------------------------
// describe : Contains the header file and namespace used by the program
//------------------------------------------------------------------------------------------------
#include "opencv2/opencv.hpp"
#include <time.h>
using namespace cv;
//-----------------------------------【main( ) function 】--------------------------------------------
// describe : The entry function of the console application , Our program starts here
//-----------------------------------------------------------------------------------------------
int main()
{
// initialization
FileStorage fs("test.yaml", FileStorage::WRITE);
// Start file writing
fs << "frameCount" << 5;
time_t rawtime; time(&rawtime);
fs << "calibrationDate" << asctime(localtime(&rawtime)); // Write the current system time
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.001, 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("\n The file is read and written , Please view the generated files in the project directory ~");
getchar();
return 0;
}The running result is :


【2】 The sample program :XML and YAML File reading
//---------------------------------【 The header file 、 The namespace contains some 】-------------------------------
// describe : Contains the header file and namespace used by the program
//------------------------------------------------------------------------------------------------
#include "opencv2/opencv.hpp"
#include <time.h>
# include <string>
using namespace cv;
using namespace std;
int main()
{
// initialization
FileStorage fs2("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;
}The running result is :

边栏推荐
- [data recovery in North Asia] a data recovery case in which the upper virtual machine data is lost due to the hard disk failure and disconnection of raid6 disk array
- K-fold cross validation
- Several methods of obtaining function annotation text on pycharm
- Besides using hackbar, how can I make post requests
- <C>. tic-tac-toe
- CSDN sign in cash reward
- Log4j2 vulnerability detection tool list
- SaaS privatization deployment scheme
- Interview records
- JS forest leaf node non recursive depth first postorder traversal
猜你喜欢
Uncover n core 'black magic' of Presto + alluxio
Boomfilter learning

How does pycharm create multiple console windows for debugging in different environments?

206. reverse linked list (insert, iteration and recursion)

<C>. function
Online yaml to XML tool
How does zhiting home cloud and home assistant access homekit respectively? What is the difference between them?

Short video is just the time. How can you quickly build your video creation ability in your app?
Understand the offline mixing technology in the industry

String since I can perform performance tuning, I can call an expert directly
随机推荐
Huawei HMS core launched a new member conversion & retention prediction model
Modifying routes without refreshing the interface
hashlib. Md5() function to filter out duplicate system files and remove them
Intra domain information collection for intranet penetration
Transunet reading notes
Huawei fast application access advertising service development guide
Cloud native 04: use envoy + open policy agent as the pre agent
Great changes in the interaction between people and the digital world
Swin UNET reading notes
Huawei in application review test requirements
Yanjiehua, editor in chief of Business Review: how to view the management trend of business in the future?
very good
App battery historian master
R language quantile autoregressive QAR analysis pain index: time series of unemployment rate and inflation rate
CiteSpace download installation tutorial
Baidu AI Financing Innovation workshop enrollment!
Local variables and global variables in C language
Dice、Sensitivity、ppv、miou
Leaflet modify popup style
[distributed system design profile (1)] raft