C++(2) 從yml或者txt讀取和儲存資料

MKT-porter發表於2024-07-15

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

  

相關文章