C ++ opencv在为Mat(矩阵)元素赋值时,先前分配的元素已更改

时间:2012-07-24 00:03:48

标签: c++ opencv

我正在尝试将数据文件(1000 x 5双打)读入Mat对象。 Mat对象初始化为Mat :: zeros(1000,5,CV_32F)。读取每行数据时,相应的行被分配给新值。代码如下所示:

void readNavFile(const char* filename, Mat& navdata) {

    ifstream infile(filename);
    string line;
    int x=0, y=0;

    if (infile.is_open()) {

        while (getline(infile, line)) {
            double value;
            stringstream converter(&line[0]);
            double* p = navdata.ptr<double>(x);
            while (converter >> value) {

                p[y++] = value;
                //DEBUGING
                cout << "Pointer value:" << p[y-1] << endl;
                cout << "Matrix value at:" << "row:" << x << " col:" << y-1 <<" is: "<< navdata.at<double>(x,y-1)<< endl;
                cout << navdata.at<double>(0,4) << endl;

            }
            y = 0;
            x++;
        }

        infile.close();
        //DEBUGING
        cout << "Final matrix first row, last element:" << navdata.at<double>(0,4) << endl;
    }
}

正如您所看到的,我尝试打印Mat(矩阵)元素的值,因为我们可以确保存储正确的值。奇怪的是,分配一切顺利,然而一些先前分配的元素将全部突然改变它们的价值。示例输出如下所示,在最后一行,在分配元素[1,2]之后,[0,4]处的值从其正确值18.1901变为3.31757e-190:

Pointer value:-35.1236
Matrix value at:row:0 col:0 is: -35.1236
Matrix element [0,4]: 0
Pointer value:150.735
Matrix value at:row:0 col:1 is: 150.735
Matrix element [0,4]: 0
Pointer value:360.094
Matrix value at:row:0 col:2 is: 360.094
Matrix element [0,4]: 0
Pointer value:3.46045
Matrix value at:row:0 col:3 is: 3.46045
Matrix element [0,4]: 0
Pointer value:18.1901
Matrix value at:row:0 col:4 is: 18.1901
Matrix element [0,4]: 18.1901
Pointer value:-35.1236
Matrix value at:row:1 col:0 is: -35.1236
Matrix element [0,4]: 18.1901
Pointer value:150.735
Matrix value at:row:1 col:1 is: 150.735
Matrix element [0,4]: 18.1901
Pointer value:360.096
Matrix value at:row:1 col:2 is: 360.096
Matrix element [0,4]: 3.31757e-190

有人可以帮我弄清楚发生了什么事吗?非常感谢你!

1 个答案:

答案 0 :(得分:1)

32F代表OpenCV中的float。 navdata.at<double>(0,4)不正确。您应该使用navdata.at<float>(0,4)或将数据类型更改为64F。此外,OpenCV应该为您的代码抛出异常。你确定没有吗?