将视频转换为 PNG 序列时出现 OpenCV 分段错误

OpenCV segmentation fault when converting video to PNG sequence

首先转换为 webm 导致分段错误的帧移动到帧 1308,而不是 1301。

我的代码:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>

using namespace std;
using namespace cv;

void conv_vid_png(string input_path, string output_path){

  VideoCapture cap(input_path);
  int count = 0;
  if(!cap.isOpened()){
       cout << "Error opening video stream or file" << endl;
      }
  while(1) {
    Mat frame;
    //Why the fuck does this use the stream insertion operator?
    // >> appears to both increment and store
    cap >> frame;
    //Break the loop when there are no more frames to capture
    if (frame.empty())
          break;

    imwrite(output_path+"frame"+to_string(count)+".png", frame);
    cout << "frame " + to_string(count) + " processed" << endl; 
    count++;
  }
}

int main()
{
  string in_path = "./movie_type_files/vert_beach_short.mp4";
  string out_path = "./tmp_png/";

  conv_vid_png(in_path, out_path); //First, convert the video file to png sequence
  return 0;
}

它使用 OpenCV VideoCapture 对象将视频的每一帧写入 PNG。对于 python,我在 OpenCV 中使用相同的函数没有问题。分段错误发生在同一帧 (1301),尽管该帧表面上没有任何异常。

有解决方案吗?我目前正在使用 ffmpeg 将 .mp4 转换为 webm 以查看问题是否仍然存在。这是我的第一个 C++ 程序,所以我正在努力自我诊断我的问题。我遵循了有关诊断分段错误的指南,并将我收集到的结果包含在下面。

段错误实际上发生在以下函数中。我以为我在这个渲染中正好有 1340 帧,但结果在我做的一些处理中丢失了一些,所以原始问题中的代码是 100% 正确的。分段错误是由读取文件失败引起的(我忘记在帧索引之前填充零)。由于框架是空的,当我使用指针访问不存在的数据时出现分段错误。