OpenCV - 创建一个Mat对象数组 [英] OpenCV - Creating an Array of Mat Objects

查看:2724
本文介绍了OpenCV - 创建一个Mat对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想把一个视频文件读入内存并存储在一个数组。我希望数组是指向Mat对象的指针。



这是我使用的代码:

  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 frameArray [num] = new cv :: Mat;
vidCap>> *(frameArray [num]);
}

但是,当我显示图像时(例如,数组),则会显示最后一个框。我在哪里错了?这是显示图片的代码:

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

我想象的是,由于它显示最后一个图像,数组中的所有指针都是相同的因此,它正在修改相同的内存。



预先感谢您的帮助。

解决方案

代码中有更多的缺陷。其中至少有两个是:


  1. vidCap.get(CV_CAP_PROP_FRAME_COUNT); 不返回正确的帧数,大部分时间。就是这样,ffmpeg不能做得更好。对于一些编解码器,它的工作,对于一些,在不。


  2. Mat矩阵有一个有趣的行为。它们实际上是指向矩阵数据的指针,而不是对象。当你说 new Mat 时,你只是创建一个新的指针。并结合事实,videoCap返回所有的时间相同的内存区域,只是与新的数据,你acutually将有一个指针的向量指向最后一帧。


您必须在单独的图片中捕捉框架并复制到预留位置:

  cap>>帧; 
vector [i] = new Mat;
frame.copyTo(vector [i]);


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.

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.

Thanks in advance for your help.

解决方案

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. 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. 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.

You have to capture the frame in a separate image and copy to the reserved location:

cap >> frame;
vector[i] = new Mat;
frame.copyTo(vector[i]);

这篇关于OpenCV - 创建一个Mat对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆