如何读取文本文件并在C ++中创建Mat对象

时间:2013-10-05 17:48:10

标签: c++ opencv mat

您好我能够将Mat对象写入文本文件。如下,

std::fstream outputFile;
    outputFile.open( "myFile.txt", std::ios::out ) ;

    outputFile << des_object.rows << std::endl;
    outputFile << des_object.cols << std::endl;

    for(int i=0; i<des_object.rows; i++)
    {
        for(int j=0; j<des_object.cols; j++)
        {
            outputFile << des_object.at<float>(i,j) << std::endl;
        }

    }
    outputFile.close( );

在前两行的代码中,我打印行数和列数,以便在阅读时使用。 但我无法读取文本文件并再次创建Mat对象。

以下是我试过的代码。不确定我的代码是否正确。

Mat des_object1;
    std::ifstream file("myFile.txt");
    std::string str; 
    int rows;
    int cols;
    int a = 0;
    while (std::getline(file, str))
    {
        int i = 0;
        int j = 0;

        if(a == 0){
            rows = std::stoi( str );
        }else if(a == 1){
            cols = std::stoi( str );
        }else{

            for(i; i< rows; i++)
            {
                for(j; j<cols; j++)
                {
                     des_object1.at<float>(i,j) = ::atof(str.c_str());
                     break;
                }
            }

        }
        ++a;
    }

4 个答案:

答案 0 :(得分:10)

使用opencv FileStorage

可能要容易得多
// write:
Mat m;
FileStorage fs("myfile.txt",FileStorage::WRITE);
fs << "mat1" << m;

// read:
FileStorage fs("myfile.txt",FileStorage::READ);
fs["mat1"] >> m;

答案 1 :(得分:0)

你的内部循环位于错误的位置:你需要在每次迭代读取一条线时保持计数器。不过,它可以做得更简单:

if (in >> rows >> cols) {
    // resize the matrix to its proper size
    for (int r(0); r!= rows; ++r) {
        for (int c(0); c != cols; ++c) {
            if (!(in >> mat[r][c])) {
                throw std:: runtime_error("failed to read matrix");
            }
        }
    }
}

答案 2 :(得分:0)

尝试这样的事情:

while循环

之外初始化这两个
int k=0;
int l=0;

而不是使用for循环

if(j<cols){
    des_object1.at<float>(k,l) = ::atof(str.c_str());
}else{
    k=0;
    l++;
    des_object1.at<float>(k,l) = ::atof(str.c_str());
}
j++;

答案 3 :(得分:0)

我编写了一种从Mat读取.asc的方法,该方法也应适用于.txt

也许有更时尚,更有效的方法可以做到这一点,但是这种方法有效且易于理解。

int Load_From_Path_Text(Mat *pMA_Out, string path)

变量

ifstream        IS_File;
string          ST_Line;
stringstream    SS_Line;
unsigned int    rows        = 0;
unsigned int    cols        = 0;
unsigned int    y           = 0;
unsigned int    x           = 0;
float           F_Value;

获取尺寸

IS_File.open(path);
while(getline(IS_File, ST_Line))
{
    if(cols == 0)
    {
        SS_Line << ST_Line;
        while(SS_Line >> F_Value)
            cols++;
    }

    rows++;
}
IS_File.close();

创建图片

*pMA_Out = Mat(rows, cols, CV_32FC1);

读取数据

IS_File.open(path);
while(getline(IS_File, ST_Line))
{
    SS_Line.clear();
    SS_Line << ST_Line;
    x = 0;

    while(SS_Line >> F_Value)
    {
        pMA_Out->at<float>(y, x) = F_Value;
        x++;
    }

    y++;
}
IS_File.close();

示例

1 1 1 -2
1 2 1 0.5
1 1 3 2.1
1 1 1 1.5

转向 this (在将CV_8UC1normalize一起转换为CV_MINMAX并显示出来之后)。