C++(2) 从yml或者txt读取和保存数据


%YAML:1.0 --- gps: "2132312"
CMakeLists.txt
cmake_minimum_required(VERSION 3.5)
set(CMAKE_CXX_STANDARD 11)
# 设置项目名称和语言
project(run_node LANGUAGES CXX)
#设置opencv安装路径
#set(CMAKE_PREFIX_PATH "/home/r9000k/v1_software/opencv/opencv349/install")
#set(CMAKE_PREFIX_PATH "/home/r9000k/v1_software/opencv/opencv455/install")
find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
# 设置输出的可执行文件
add_executable(${PROJECT_NAME} main.cpp)
#可执行文件绑定库
target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS})
main.cpp
测试1
输出
%YAML:1.0
---
Time: "Thu Nov 28 14:02:31 2019\n"
imageSize: [ 1280, 800 ]
cameraMatrix: !!opencv-matrix
rows: 3
cols: 3
dt: d
data: [ 190., 0., 640., 0., 190., 400., 0., 0., 1. ]
distCoeffs: !!opencv-matrix
rows: 5
cols: 1
dt: d
data: [ 1.0000000000000001e-01, 1.0000000000000000e-02,
-1.0000000000000000e-03, 0., 0. ]
保存代码
#include <opencv2/opencv.hpp>
#include <time.h>
#include <iostream>
int main(int argc, char** argv)
{
//write a yaml file
cv::FileStorage fs_write("./test.yaml", cv::FileStorage::WRITE);
time_t rawtime;
time(&rawtime);
fs_write << "Time" << asctime(localtime(&rawtime));
std::vector<int> image_size = {1280, 800};
fs_write << "imageSize" << image_size;
cv::Mat camera_matrix = (cv::Mat_<double>(3, 3) << 190, 0, 640,
0, 190, 400,
0, 0, 1);
cv::Mat distort_coefficient = (cv::Mat_<double>(5, 1) << 0.1, 0.01, -0.001, 0, 0);
fs_write << "cameraMatrix" << camera_matrix << "distCoeffs" << distort_coefficient;
fs_write.release();
return 0;
}
读取代码
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
int main(int argc, char **argv)
{
//read a yaml file
cv::FileStorage fs_read("./test.yaml", cv::FileStorage::READ);
std::string time;
//second method:use FileNode::operator >>
fs_read["Time"] >> time;
std::vector<int> image_size;
fs_read["imageSize"] >> image_size;
cv::Mat camera_matrix, distort_coefficient;
fs_read["cameraMatrix"] >> camera_matrix;
fs_read["distCoeffs"] >> distort_coefficient;
std::cout << "Time: " << time << std::endl
<< "cameraMatrix: " << camera_matrix << std::endl
<< "distCoeffs: " << distort_coefficient << std::endl;
fs_read.release();
return 0;
}
测试2
#include <iostream>
#include "opencv2/core.hpp"
#include <time.h>
using namespace cv;
using namespace std;
/*
保存结果 YAML 文件中需要在首行定义 %YAML:1.0 或 %YAML:1.1,否则将会报错。
%YAML:1.0
---
frameCount: 5
calibrationDate: "Mon Jul 15 21:25:25 2024\n"
cameraMatrix: !!opencv-matrix
rows: 3
cols: 3
dt: d
data: [ 1000., 0., 320., 0., 1000., 240., 0., 0., 1. ]
distCoeffs: !!opencv-matrix
rows: 5
cols: 1
dt: d
data: [ 1.0000000000000001e-01, 1.0000000000000000e-02,
-1.0000000000000000e-03, 0., 0. ]
features:
- { x:103, y:166, lbp:[ 1, 0, 0, 1, 0, 1, 1, 0 ] }
- { x:115, y:113, lbp:[ 1, 1, 1, 1, 1, 1, 1, 1 ] }
- { x:586, y:12, lbp:[ 1, 0, 0, 1, 0, 1, 0, 0 ] }
*/
bool API_WriteFromYaml_Test(String path_yaml){
//创建文件
FileStorage fs(path_yaml, FileStorage::WRITE);
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.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();
return 0;
}
bool API_WriteFromYaml_name_value(String path_yaml,String name,String data){
//创建文件
FileStorage fs(path_yaml, FileStorage::WRITE);
fs << name << data;
fs.release();
return 0;
}
bool API_ReadFromYaml_Test(String path_yaml){
FileStorage fs2(path_yaml, FileStorage::READ);
//注意数据格式转换
// first method: use (type) operator on FileNode.
int frameCount = (int)fs2["frameCount"];
String date;
// second method: use FileNode::operator >>
if (!fs2["calibrationDate"].isNone() && !fs2["calibrationDate"].empty()) {
fs2["calibrationDate"] >> date;
}
Mat cameraMatrix2, distCoeffs2;
fs2["cameraMatrix"] >> cameraMatrix2;
fs2["distCoeffs"] >> distCoeffs2;
std::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;
std::vector<uchar> lbpval;
// iterate through a sequence using FileNodeIterator
for( ; it != it_end; ++it, idx++ )
{
cout << "feature #" << idx << ": ";
cout << "x=" << (int)(*it)["x"] << ", y=" << (int)(*it)["y"] << ", lbp: (";
// you can also easily read numerical arrays using FileNode >> std::vector operator.
(*it)["lbp"] >> lbpval;
for( int i = 0; i < (int)lbpval.size(); i++ )
cout << " " << (int)lbpval[i];
cout << ")" << endl;
}
fs2.release();
return 0;
}
//从指定文件读取 指定名字的数据
string API_ReadFromYaml_name_data(string path_yaml,string name,string *data){
/*
写入(FileStorage::WRITE,覆盖写)
追加(FileStorage::APPEND,追加写)
读取(FileStorage::READ)
*/
FileStorage fs2(path_yaml, FileStorage::READ);
if (!fs2.isOpened()) {
std::cerr << "Failed to open FileStorage" << std::endl;
*data="error";
return "error";
}
//注意数据格式转换 to_string()
// second method: use FileNode::operator >>
if (!fs2[name].isNone() && !fs2[name].empty()) {
fs2[name] >> *data;
}
else{ *data="error"; }
fs2.release();
return *data;
}
//从指定文件读取 指定名字的数据
string API_ChangeYaml_name_data(string path_yaml,string name,string *data){
/*
写入(FileStorage::WRITE,覆盖写)
追加(FileStorage::APPEND,追加写)
读取(FileStorage::READ)
*/
FileStorage fs2(path_yaml, cv::FileStorage::READ + cv::FileStorage::MEMORY);
if (!fs2.isOpened()) {
std::cerr << "Failed to open FileStorage" << std::endl;
return "error";
}
//注意数据格式转换 to_string()
// second method: use FileNode::operator >>
if (!fs2[name].isNone() && !fs2[name].empty()) {
fs2[name] >> *data;
}
else{ *data="-1"; }
fs2.release();
return *data;
}
int main(int, char** argv)
{
//创建文件
string path_yaml="../config/my_config.yaml";
string path_txt="../config/my_config.txt";
//API_WriteFromYaml_Test(path_yaml);
//API_ReadFromYaml_Test(path_yaml);
API_WriteFromYaml_name_value(path_yaml,"gps","2132312");// 写入一个数据
string yaml_str_data; // 函数内部获取数值
string yaml_str_data_out=API_ReadFromYaml_name_data(path_yaml,"gps", &yaml_str_data);// 读取一个数据
cout<< "yaml_str_data "<< yaml_str_data<< " "<< yaml_str_data_out<<endl;
return 0;
}