保存数据(矩阵或ndarray),然后将其加载到C++ (作为OpenCV垫子)

发布于 2025-02-09 22:26:50 字数 263 浏览 1 评论 0原文

我已经在numpy中创建了一些我想在单独的C ++程序中使用的数据。因此,我需要使用Python保存数据,然后将其加载到C ++中。这样做的最好方法是什么?

我的numpy ndarray是浮动32,形状[10000 x 18 x 5]。例如,我可以保存它,例如使用

numpy.save(filename, data)

C ++中加载此类数据的简便方法吗?目标结构可以是eigen :: matrix

I've created some data in numpy that I would like to use in a separate C++ program. Therefore I need to save the data using python and later load it in C++. What is the best way of doing this?

My numpy ndarray is float 32 and of shape [10000 x 18 x 5]. I can save it for example using

numpy.save(filename, data)

Is there an easy way to load such data in C++? Target structure could be an Eigen::Matrix for example.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不再让梦枯萎 2025-02-16 22:26:50

搜索几个小时后,我找到了我一年过去了的示例文件。

警告:

  • 2D矩阵
  • 解决方案仅覆盖不适合3维或通用ndarrays的

,将numpy数组写入ASCII文件,并用标头指定nrows,ncols,ncols:

def write_matrix2D_to_ascii(filename, matrix2D):
    
    nrows, ncols = matrix2D.shape
    
    with open(filename, "w") as file:
        
        # write header [rows x cols]
        nrows, ncols = matrix2D.shape
        file.write(f"{nrows} {ncols}")
        file.write("\n")
        
        # write values 
        for row in range(nrows):
            for col in range(ncols):
                value = matrix2D[row, col]

                file.write(str(value))
                file.write(" ")
            file.write("\n")

示例输出data-file.txt,看起来像这样(第一行是header指定NROWS和NCOLS):

2 3
1.0 2.0 3.0
4.0 5.0 6.0

CPP):CPP ):CPP):CPP):CPP函数将ASCII文件中的矩阵读取到OPENCV矩阵:

#include <iostream>
#include <fstream>
#include <iomanip> // set precision of output string

#include <opencv2/core/core.hpp> // OpenCV matrices for storing data

using namespace std;
using namespace cv;

void readMatAsciiWithHeader( const string& filename, Mat& matData)
{
    cout << "Create matrix from file :" << filename << endl;

    ifstream inFileStream(filename.c_str());
    if(!inFileStream){
        cout << "File cannot be found" << endl;
        exit(-1);
    }

    int rows, cols;
    inFileStream >> rows;
    inFileStream >> cols;
    matData.create(rows,cols,CV_32F);
    cout << "numRows: " << rows << "\t numCols: " << cols << endl;

    matData.setTo(0);  // init all values to 0
    float *dptr;
    for(int ridx=0; ridx < matData.rows; ++ridx){
        dptr = matData.ptr<float>(ridx);
        for(int cidx=0; cidx < matData.cols; ++cidx, ++dptr){
            inFileStream >> *dptr;
        }
    }
    inFileStream.close();

}

在CPP程序中使用上述函数的驱动程序代码:

Mat myMatrix;
readMatAsciiWithHeader("path/to/data-file.txt", myMatrix);

完整性,一些代码使用C ++保存数据:

int saveMatAsciiWithHeader( const string& filename, Mat& matData)
{
    if (matData.empty()){
       cout << "File could not be saved. MatData is empty" << endl;
       return 0;
    }
    ofstream oStream(filename.c_str());

    // Create header
    oStream << matData.rows << " " << matData.cols << endl;
    
    // Write data
    for(int ridx=0; ridx < matData.rows; ridx++)
    {
        for(int cidx=0; cidx < matData.cols; cidx++)
        {
            oStream << setprecision(9) << matData.at<float>(ridx,cidx) << " ";
        }
        oStream << endl;
    }
    oStream.close();
    cout << "Saved " << filename.c_str() << endl;

    return 1;
}

未来工作:未来的工作:

  • 的解决方案
  • 3D矩阵转换为EIGEN :: MATRIX

After searching for hours I found my year-old example files.

Caveat:

  • solution only covers 2D matrices
  • not suited for 3 dimensional or generic ndarrays

Write numpy array to ascii file with header specifying nrows, ncols:

def write_matrix2D_to_ascii(filename, matrix2D):
    
    nrows, ncols = matrix2D.shape
    
    with open(filename, "w") as file:
        
        # write header [rows x cols]
        nrows, ncols = matrix2D.shape
        file.write(f"{nrows} {ncols}")
        file.write("\n")
        
        # write values 
        for row in range(nrows):
            for col in range(ncols):
                value = matrix2D[row, col]

                file.write(str(value))
                file.write(" ")
            file.write("\n")

Example output data-file.txt looks like this (first row is header specifying nrows and ncols):

2 3
1.0 2.0 3.0
4.0 5.0 6.0

Cpp function to read matrix from ascii file into OpenCV matrix:

#include <iostream>
#include <fstream>
#include <iomanip> // set precision of output string

#include <opencv2/core/core.hpp> // OpenCV matrices for storing data

using namespace std;
using namespace cv;

void readMatAsciiWithHeader( const string& filename, Mat& matData)
{
    cout << "Create matrix from file :" << filename << endl;

    ifstream inFileStream(filename.c_str());
    if(!inFileStream){
        cout << "File cannot be found" << endl;
        exit(-1);
    }

    int rows, cols;
    inFileStream >> rows;
    inFileStream >> cols;
    matData.create(rows,cols,CV_32F);
    cout << "numRows: " << rows << "\t numCols: " << cols << endl;

    matData.setTo(0);  // init all values to 0
    float *dptr;
    for(int ridx=0; ridx < matData.rows; ++ridx){
        dptr = matData.ptr<float>(ridx);
        for(int cidx=0; cidx < matData.cols; ++cidx, ++dptr){
            inFileStream >> *dptr;
        }
    }
    inFileStream.close();

}

Driver code to use above mentioned function in cpp program:

Mat myMatrix;
readMatAsciiWithHeader("path/to/data-file.txt", myMatrix);

For completeness, some code to save the data using C++:

int saveMatAsciiWithHeader( const string& filename, Mat& matData)
{
    if (matData.empty()){
       cout << "File could not be saved. MatData is empty" << endl;
       return 0;
    }
    ofstream oStream(filename.c_str());

    // Create header
    oStream << matData.rows << " " << matData.cols << endl;
    
    // Write data
    for(int ridx=0; ridx < matData.rows; ridx++)
    {
        for(int cidx=0; cidx < matData.cols; cidx++)
        {
            oStream << setprecision(9) << matData.at<float>(ridx,cidx) << " ";
        }
        oStream << endl;
    }
    oStream.close();
    cout << "Saved " << filename.c_str() << endl;

    return 1;
}

Future work:

  • solution for 3D matrices
  • conversion to Eigen::Matrix
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文