OpenCV将相同的图像放置到容器中

OpenCV placing the same image into the container

本文关键字:图像 OpenCV      更新时间:2023-10-16

我正在尝试编写一个程序,从视频中捕获n帧,并将它们放入容器中进行进一步的工作(之后我将制作拼贴)。但我遇到了一个问题,当容器中的所有图像都相同时(它只填充了最后捕获的图像)。我已经检查了图像是否被正确捕获,因为我也在保存它们,并且可以清楚地看到它们是不同的。

这是我的代码:

std::vector<cv::Mat> MY_framelist; //container for captured frames
cv::VideoCapture myvid; 
cv::Mat MY_frame; //will capture frames here
myvid.open(pass_filename); //open video file(char* pass_filename=12.mp4)
if (!myvid.isOpened()) {
printf("Capture not open n");
}
double x_length = myvid.get(CV_CAP_PROP_FRAME_COUNT); //get maxlength of the video
uint each_frame = uint(x_length) / 16; //capture every 16 frames
for (uint j = 0, current_frame = 1; (current_frame < x_length) && (j < 16); current_frame += each_frame, j++)
{
myvid.set(CV_CAP_PROP_POS_FRAMES, current_frame); //set frame
myvid.read(MY_frame);  // then capture the next one
MY_framelist.push_back(MY_frame); //place it into the container

std::stringstream frameNum; //generating name for saved images
frameNum << j + 1;
if (j + 1 <= 9)
my_filename += "0";
my_filename += frameNum.str();
my_filename += ".jpg";
cv::imwrite(my_filename.c_str(), MY_frame); //saving images to prove that they are captured correctly
my_filename = "test";
printf(" and Image # ");
printf("%d", j + 1);
printf(" saved n");
}

结果,MY_framelist将包含上次捕获的16个相同的图像。我在这里做错了什么?我在这里看到了一些解决方法,但我并不急于这样做,因为这会导致不那么准确的结果。提前感谢!

OpenCVMat副本是浅副本,即只复制标头,不复制数据。所以这里:

MY_framelist.push_back(MY_frame); //place it into the container

您将得到一个始终具有相同图像的容器。

您还需要进行深度复制复制数据:

MY_framelist.push_back(MY_frame.clone()); //place it into the container