如何在OpenCV中访问矢量mat对象

时间:2015-08-13 07:17:08

标签: c++ opencv image-processing vector mat

我想将一些图片从文件加载到Mat-objects(OpenCV),并希望将它们存储在矢量中。进一步的OpenCV调用/对象需要向量(如:AlignMTB)作为参数。但是在用Mat-objects填充向量之后,我只能访问我添加到向量中的最后一个元素。

在示例中,我首先将图像加载到中间Mat对象并将其转换为CV_32FC3。然后我打印出一个样本像素的BGR值。打印出来是:

File 0: 13 13 157
File 1: 17 20 159
File 2: 8 8 152

然后我将这个中间Mat添加到Mat-vector图像。

之后我正在尝试打印出第一张和第二张图片的样本像素值,但总是得到第三张图片的值:

File 0: 8 8 152
File 1: 8 8 152

在访问矢量数据时我犯了什么错误?

我正在尝试这个例程:

vector<Mat> images;
images.reserve(3);

Mat img;
for (int i = 0; i < 3; i++)
{
    imread("F:/Test/file" + to_string(i) + ".jpg").convertTo(img, CV_32FC3);

    cout << "File " << i << ": " << img.at<Vec3f>(800, 800)[0] << " " << img.at<Vec3f>(800, 800)[1] << " " << img.at<Vec3f>(800, 800)[2] << endl;

    images.push_back(img);
}
cout << endl;

cout << "File " << 0 << ": " << images[0].at<Vec3f>(800, 800)[0] << " " << images[0].at<Vec3f>(800, 800)[1] << " " << images[0].at<Vec3f>(800, 800)[2] << endl;
cout << "File " << 1 << ": " << images[1].at<Vec3f>(800, 800)[0] << " " << images[1].at<Vec3f>(800, 800)[1] << " " << images[1].at<Vec3f>(800, 800)[2] << endl;

1 个答案:

答案 0 :(得分:2)

问题不是vector::push_back,因为它将构造给定元素的副本。但是,问题是Mat的复制构造函数,它不复制关联的数据:

  

这些构造函数不会复制任何数据。相反,构造指向m数据或其子数组的标题并与之关联。

解决问题的方法是显式Mat::clone操作,它也会复制数据或在for循环中移动矩阵声明。

vector<Mat> images;
images.reserve(3);

Mat img;
for (int i = 0; i < 3; i++)
{
    imread("F:/Test/file" + to_string(i) + ".jpg").convertTo(img, CV_32FC3);

    cout << "File " << i << ": " << img.at<Vec3f>(800, 800)[0] << " " << img.at<Vec3f>(800, 800)[1] << " " << img.at<Vec3f>(800, 800)[2] << endl;

    images.push_back(img.clone());
}
cout << endl;

cout << "File " << 0 << ": " << images[0].at<Vec3f>(800, 800)[0] << " " << images[0].at<Vec3f>(800, 800)[1] << " " << images[0].at<Vec3f>(800, 800)[2] << endl;
cout << "File " << 1 << ": " << images[1].at<Vec3f>(800, 800)[0] << " " << images[1].at<Vec3f>(800, 800)[1] << " " << images[1].at<Vec3f>(800, 800)[2] << endl;