【问题标题】:How to get access to vector mat object in OpenCV如何在 OpenCV 中访问矢量垫对象
【发布时间】:2015-08-13 07:17:08
【问题描述】:

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

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

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

然后我将这个中间垫添加到垫矢量图像中。

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

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;

【问题讨论】:

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


    【解决方案1】:

    问题不在于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;
    

    【讨论】:

    • 是的,这就是解决方案。我正在尝试使用 copyTo 但没有成功。谢谢
    • 很高兴听到我的回答有效 :-) @user5068404,您也可以通过单击赞成/反对票正下方的勾号/复选标记向其他人展示。
    猜你喜欢
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    相关资源
    最近更新 更多