vector元素被覆盖

std::vector elements are overwritten

本文关键字:覆盖 元素 vector      更新时间:2023-10-16

我有一个函数ReadMatFromTxt,它从文本文件中读取一些数字并将它们存储在vector<Mat>中。该函数跳过一些包含标题的行,并将两个标题行之间的值作为Mat保存到向量M_vec中。当遇到标题行时,在Mat M中累积的值将被添加到向量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;
}

然而,当我在main中使用这个函数时,我看到vector的所有元素都是相同的(尽管文本文件包含不同的值)。

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

在做push_backMat添加到向量时,我做错了什么吗?为什么要这样写?

opencv类Mat赋值操作符和复制构造函数只修改引用计数器。Mat::zeros(rows/2, cols, CV_32FC2)创建的深度数据保持不变。

使用

拥有多个数据实例
M_vec.push_back(M.clone());