首页 > 编程语言 >C++(2) 从yml或者txt读取和保存数据

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

时间:2024-07-15 22:32:16浏览次数:8  
标签:name FileStorage C++ yaml fs2 path txt data yml

 

 

%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

#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;
}

  

标签:name,FileStorage,C++,yaml,fs2,path,txt,data,yml
From: https://www.cnblogs.com/gooutlook/p/18304137

相关文章

  • C++ 类和对象(A)
    一、类与对象的初步认识1.类是对象的抽象,而对象是类的具体实例。类是抽象的,不占用内存;而对象是具体的,占用存储空间。2.面向过程与面向对象C语言是面向过程的,关注的是过程中的数据与方法。C++是面向对象的,关注的是对象’的属性与功能。二、类的定义1、类定义格式1.cl......
  • C++(1) gps转换为enu
      步骤一:安装GeographicLib首先,确保你的系统中已安装GeographicLib库。可以通过以下命令在Ubuntu中安装:sudoapt-getinstallgeographiclib-*#安装GeographicLib的库sudoapt-getinstalllibgeographic-*#安装GeographicLib的依赖库步骤二:配置C++项目在......
  • 高质量C/C++编程指南总结(五)—— 常量
    尽量使用含义直观的常量来表示那些将在程序中多次出现的数字或字符串。在C++程序中只使用const常量而不使用宏常量,即const常量完全取代宏常量。需要对外公开的常量放在头文件中,不需要对外公开的常量放在定义文件的头部。为便于管理,可以把不同模块的常量集中存放在一个公共......
  • C++分类
    //ps:学习自存,暂未整理。知识点算法:思维,STL,模拟,排序,枚举,查找,递推与递归,贪心,二分,双指针,前缀和、差分与离散化丨常见优化技巧,分治与倍增〔倍增Floyd〕,位运算丨三分,01分数规划字符串:基础丨kmp,字典树,AC自动机,最小表示法,后缀数组,后缀自动机数据结构:栈,队列,线性表,链表,二叉树,集合,图的基......
  • C++程序设计最细教程
    1.类与对象(重点)1.1概念类:类是一个抽象的概念,描述同一类对象的特征。对象:符合类特性特性的实体。对象需要按照类的定义进行创建,因此先编写类才能创建对象。1.2类的内容类中最基础的内容包括两部分:属性(成员变量、数据成员)用来描述类对象的数据段,通常是名词变量,例......
  • Windows下C++动态链接库的生成以及使用
    目录一.前言二.生成动态链接库三.使用动态链接库四.其他一.前言这篇文章简单讨论一下Windows下如何使用VS生成和使用C++动态链接库,示例使用VS2022环境。二.生成动态链接库先创建C++项目-动态链接库(DLL)然后将默认生成的.h和.cpp文件清理干净,当然你也可以选择保......
  • 【C/C++】结构体内存对齐
    结构体内存对齐详解1、第一个成员在与结构体变量偏移量为0的地址处2、其他成员变量要偏移到对齐数的整数倍的地址处,注意偏移是从结构体首地址处开始的。对齐数取的是编译器默认的一个对齐数与该成员大小 这个俩个数中的最小值。【VS中默认的值为8、Linu......
  • kimi写代码:c++ 线程池
    https://kimi.moonshot.cn/share/cqaberkdvond1bljn8sg在这个示例中:线程池创建了固定数量的工作线程。enqueue方法用于将任务添加到队列,并返回一个std::future对象,可用于获取任务的结果。每个工作线程在循环中等待任务分配,并在接收到任务后执行它。当线程完成分配的任务后......
  • 面试算法(排序)附带c++/python实现
            排序算法是面试中会经常会被问到的一类问题,如果可以掌握较多的排序算法,在面试过程中才更有机会被面试官看重哦,下面我们准备了一些常见的面试算法,并分别给出了c++和python的代码实现,小伙伴们一起学起来吧!冒泡排序(BubbleSort)        基于交换的排序,......
  • C++ STL is_sorted用法
    一:功能   检查一个区间内的元素是否有序,按升序(或降序)排列二:用法#include<algorithm>#include<iostream>intmain(){std::vector<int>data1={1,2,3,4,5};booltest1=std::is_sorted(data1.begin(),data1.end());std::cout<<std::boo......