从 opencv c++ 中的矢量中检索固定的帧数

Retrieve fix number of frames from vector in opencv c++

本文关键字:检索 opencv c++      更新时间:2023-10-16

我读取了一个视频并将所有帧存储在一个向量中。现在我想拼接存储在矢量中的前 50 帧并保存结果,然后拼接接下来的 50 帧并保存结果,依此类推。这是因为 opencv 的拼接类不会一次处理大量帧,并给出错误:内存不足。我无法实现正确的逻辑。请帮我更正代码。谢谢。我的代码如下:

int main(int argc, char const *argv[])
{
std::string video_file;
// Read video file
if (argc > 1)
{
video_file = argv[1];
}
else
{
video_file = "vid/xyz.mp4";
}
VideoCapture inputVideo(video_file);
if (!inputVideo.isOpened())
cerr << "Error opening video filen";
double totalFrames(inputVideo.get(CV_CAP_PROP_FRAME_COUNT));
double frameRate(inputVideo.get(CV_CAP_PROP_FPS));
double timeInterval = 0.5; // in sec
int sizeReduction = 4;
int num = 1;

vector<Mat> frames;
vector<Mat> frames1;
Mat frame;
for (int num = 0; num < totalFrames; num++)
{
num = num + round(frameRate * timeInterval);
inputVideo.set(1, num);
inputVideo >> frame;
if (frame.empty())
continue;
cv::Size sz = frame.size();
cv::resize(frame, frame, sz / sizeReduction);
frames.push_back(frame);   // vector 'frames' have all the frames to be processed
}
Stitcher::Mode mode = Stitcher::SCANS;
string result_name = "xyz.jpg";
vector<Mat> pano1;
Mat pano;
Ptr<Stitcher> stitcher = Stitcher::create(mode);
int f1, f2 = 0;
// need help to correct the code below: 
for (f1 = f2; f1 <= frames.size(); f1++) {
int count = 0;
while (count < 50) {
frames1.push_back(frames[f1]);  // I want to save first 10 frames in vector 'frames1'
count++;
}
Stitcher::Status status = stitcher->stitch(frames1, pano);
pano1.push_back(pano);
f2 = f2 + count;            
}
Stitcher::Status status = stitcher->stitch(pano1, pano); 
imwrite(result_name, pano);
cout << "stitching completed successfullyn" << result_name << " saved!";
return EXIT_SUCCESS;
} 

您首先将所有帧存储在vector中,并且仅在运行算法将它们拼接在一起之后。这浪费了很多内存。

更好的方法是阅读前两帧并将它们拼接在一起以创建全景图。然后阅读第三帧并将其拼接到现有的全景图上。然后阅读第四个并缝合它,然后是第五个...等等。

没有必要将所有这些帧存储在矢量中。