简体   繁体   English

OpenCV - 创建一个 Mat 对象数组

[英]OpenCV - Creating an Array of Mat Objects

I would have thought this is trivial, but I'm having some trouble with it.我本以为这是微不足道的,但我遇到了一些麻烦。

I want to read a video file into memory and store it in an array.我想将视频文件读入内存并将其存储在数组中。 I want the array to be of pointers to Mat objects.我希望数组是指向 Mat 对象的指针。

This is the code I'm using:这是我正在使用的代码:

cv::VideoCapture vidCap = cv::VideoCapture("file.avi");
int frames = (int)vidCap.get(CV_CAP_PROP_FRAME_COUNT);
cv::Mat** frameArray = new cv::Mat*[frames];
for (int num = 0; num < frames; num++) {
     frameArray[num] = new cv::Mat;
     vidCap >> *(frameArray[num]);
}

However, when I display an image (for example, the first image in the array), it displays the last frame.但是,当我显示图像(例如,数组中的第一张图像)时,它会显示最后一帧。 Where am I going wrong?我哪里错了? This is the code for displaying the image:这是显示图像的代码:

cv::namedWindow("Movie", 1);
cv::imshow("Movie", *(frameArray[0]));
cv::waitKey(0);

I would imagine that, since it's displaying the last image, all the pointers in the array are the same and, therefore, it is modifying the same memory.我想,由于它显示的是最后一张图像,数组中的所有指针都是相同的,因此,它正在修改相同的内存。 However, when I printf the pointers, they are different.但是,当我打印指针时,它们是不同的。

There are more flaws in your code.您的代码中存在更多缺陷。 At least two of them are:其中至少有两个是:

  1. vidCap.get(CV_CAP_PROP_FRAME_COUNT); does not return the correct number of frames, most of the time.大多数情况下不会返回正确的帧数。 That's it, ffmpeg can't do better.就是这样,ffmpeg 不能做得更好。 For some codecs it works, for some, in doesn't.对于某些编解码器,它可以工作,而对于某些编解码器,则不能。

  2. Mat matrices have an interesting behaviour.矩阵有一个有趣的行为。 They are actually pointers to the matrix data, not objects.它们实际上是指向矩阵数据的指针,而不是对象。 When you say new Mat you just create a new pointer.当你说new Mat你只是创建了一个新的指针。 And combined with the fact that videoCap returns all the time the same memory area, just with new data, you acutually will have a vector of pointers pointing to the last frame.结合 videoCap 始终返回相同内存区域的事实,仅使用新数据,您实际上将拥有一个指向最后一帧的指针向量。

You have to capture the frame in a separate image and copy to the reserved location:您必须在单独的图像中捕获帧并复制到保留位置:

std::vector<cv::Mat> frames;
cap >> frame;
frames.push_back(frame.clone());

Please note the change from array of pointers to a vector of objects.请注意从指针数组到对象向量的变化。 This avoids the need for reading the number of frames beforehand, and also makes the code safer.这避免了事先读取帧数的需要,也使代码更安全。

But is there actually a way of creating Mat arrays?但实际上有没有办法创建 Mat 数组? I really don't see other options in my case but trying to access an item in the array considers the array as a single Mat and thinks I'm trying to access its data.在我的情况下,我真的没有看到其他选项,但是尝试访问数组中的项目会将数组视为单个 Mat 并认为我正在尝试访问其数据。

Edit: Found a workaround using a pointer:编辑:找到一个使用指针的解决方法:

Mat* array = new Mat[arraySize];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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