How to read the text file and create Mat object in C++

假如想象 提交于 2019-12-01 06:16:00

it's probably far easier, to use the opencv FileStorage:

// write:
Mat m;
FileStorage fs("myfile.txt",FileStorage::WRITE);
fs << "mat1" << m;

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

You got your inner loops in the wrong location: You'd need to keep the counter around for each iteration reading a line. It can be done a lot simpler, though:

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");
            }
        }
    }
}

try something like this:

initialize these two outside the while loop

int k=0;
int l=0;

and instead of using the for loop

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++;

I wrote a method for reading a Mat from an .asc that should work for .txt too.

Maybe there are more stylish and efficient ways to do that, but this method works and is easy to understand.

Head

int Load_From_Path_Text(Mat *pMA_Out, string path)

Variables

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;

Get Size

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();

Create Image

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

Read Data

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();

Example

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

turns to this (after beeing converted to CV_8UC1 using normalize with CV_MINMAX to be displayed).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!