【问题标题】:Read from Txt file and convert to float mat opencv从 Txt 文件中读取并转换为 float mat opencv
【发布时间】:2013-06-06 07:25:08
【问题描述】:

我需要这方面的帮助。我正在从文本文件中读取数据。它有 3 列和 100 行。数据采用 (x,y,z) 格式。我想将 x 和 y 组合成一个 Mat 数据,并将 Z 组合成另一个。

对于 Z 这很简单,我创建了它的浮点矩阵。我正在分别读取 x 和 y,目前我将其存储为浮点向量。如下代码所示。

char buf[255];
float x, y;
float label;
vector<float> x_coord;
vector<float> y_coord;

Mat class_label(y_coord.size(), 1, CV_32FC1);

if(!inFile.eof())
{
    while (inFile.good())
    {
        inFile.getline(buf, 255);
        string line(buf);
        istringstream iss(line);
        iss >> x;
        x_coord.push_back(x);
        iss >> y;
        x_coord.push_back(y);
        y_coord.push_back(y);
        iss>> label;
        class_label.push_back(label);
    }
    inFile.close();
}

如何结合 x_coord 和 y_coord 来创建 Mat training_data(y_coord.size(), 2, CV_32FC1, train_data ); 类型的 Mat

即 2 列乘 100 行。我正在这样做,但它不起作用

float train_data[10938][2];

for (int j = 0; j < 2; j++)
{
    for (int i = 0; i < x_coord.size(); i++)
    {
        int index = j + i * x_coord.size();
        train_data[i][j] = x_coord.at(index);  
        //train_data[i][1] = x_coord.at(i);
    }
}

我真的卡在这里了,请帮帮我。

【问题讨论】:

  • 你真的想要 2 列的单浮点数据,还是 CV_32FC2 的单列?
  • 2 列单浮点数据

标签: opencv vector matrix


【解决方案1】:

不用辅助数组train_data可以直接填充Mat。

for (int j = 0; j < 2; j++)
{
    for (int i = 0; i < x_coord.size(); i++)
    {
        int index = j + i * x_coord.size();
        training_data.at<float>(i, j) = x_coord.at(index);
    }
}

您也可以在读取文件时执行相同的操作。更多信息请阅读Mat::at() documentation

【讨论】:

    猜你喜欢
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多