简体   繁体   中英

std::vector elements are overwritten

I have a function ReadMatFromTxt that reads some numbers from a text file and stores them in a vector<Mat> . The function skips some lines, that contain headers, and saves the values between two header lines as Mat into the vector M_vec . When a header line is encountered, the values accumulated in Mat M until then are added to the vector M_vec .

vector<Mat> ReadMatFromTxt(string filename, int rows, int cols)
{
    double m;
    Mat M = Mat::zeros(rows/2, cols, CV_32FC2); //Matrix to store values
    vector<Mat> M_vec;

    ifstream in(filename.c_str());
    int lineNo = 0;
    int cnt = 0;        //index starts from 0
    string line;

    while(getline(in, line))
    {
        istringstream iss(line);
        if(((lineNo % (rows+1)) == 0) && lineNo != 0)
        // header found, add Mat to vector<Mat>
        {
            cout << M << endl;
            M_vec.push_back(M);

            cnt = 0;
            lineNo++;
        }
        else
        {
            while (iss >> m)
            {
                int temprow = cnt / cols;
                int tempcol = cnt % cols;
                if(cnt < (rows*cols)/2) {
                    M.at<Vec2f>(temprow, tempcol)[0] = m;
                } else {
                    M.at<Vec2f>(temprow - rows/2 , tempcol)[1] = m;
                }
                cnt++;
            }
        lineNo++;
        }
    }

    return M_vec;
}

However, when I use this function in the main, I see that all elements of the vector are the same (although the text file contains different values).

vector<Mat> M_vec;
M_vec = ReadMatFromTxt(txt_path.string(), rows, cols);

for(int i=0; i<M_vec.size(); i++)
   {
       cout << "M_vec[" << i << "] = " << M_vec[i] << endl;
   }

Am I doing something wrong while doing push_back to add Mat to the vector. Why is it overwritten like that?

The opencv class Mat assignment operators and copy constructor only modify a reference counter. The deep data created by Mat::zeros(rows/2, cols, CV_32FC2) remains the same.

To have several instance of data use

M_vec.push_back(M.clone());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM