opencv 如何定义数组_OpenCV - 创建一个Mat对象数组

bd96500e110b49cbb3cd949968f18be7.png

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:

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.

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]);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值