c++ – Why can’t my program find the data file when I run it from Visual Studio?


I want to extract frames of a video file in c++ in visual studio. Below is the code that I am using.

The vidfile.mp4 video file is in the same folder with the source file. The code compiles. But when I run the solution I get an error saying that can not open the video file. I am guessing that there may be a problem with the filename in VideoCapture cap("vidfile.mp4");. But I do not know the true cause of this error. How can I solve this problem?

#include <iostream>
#include "opencv2/opencv.hpp"
#include "opencv2/video.hpp"
#include "opencv2/core.hpp"
#include "opencv2/videoio.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <vector>
#include <opencv2/imgcodecs.hpp>
#include "opencv2/highgui/highgui.hpp"
#include <highlevelmonitorconfigurationapi.h>

using std::cout; using std::cerr; using std::endl;

using namespace cv;
using namespace std;


int main()
{
    int i = 0;
    string str;
    VideoCapture cap("vidfile.mp4");
    // cap is the object of class video capture that tries to capture Bumpy.mp4
    if (!cap.isOpened())  // isOpened() returns true if capturing has been initialized.
    {
        cout << "Cannot open the video file. \n";
        return -1;
    }

    //double fps = cap.get(CV_CAP_PROP_FPS); //get the frames per seconds of the video
    // The function get is used to derive a property from the element.
    // Example:
    // CV_CAP_PROP_POS_MSEC :  Current Video capture timestamp.
    // CV_CAP_PROP_POS_FRAMES : Index of the next frame.

    //namedWindow("A_good_name", CV_WINDOW_AUTOSIZE); //create a window called "MyVideo"
    // first argument: name of the window.
    // second argument: flag- types: 
    // WINDOW_NORMAL : The user can resize the window.
    // WINDOW_AUTOSIZE : The window size is automatically adjusted to fit the displayed image() ), and you cannot change the window size manually.
    // WINDOW_OPENGL : The window will be created with OpenGL support.

    while (1)
    {
        Mat frame;
        // Mat object is a basic image container. frame is an object of Mat.

        if (!cap.read(frame)) // if not success, break loop
            // read() decodes and captures the next frame.
        {
            cout << "\n Cannot read the video file. \n";
            break;
        }

        i = i + 1;
        str = "MyImage" + std::to_string(i) + ".jpg";
        //imshow("A_good_name", frame);
        imwrite(str, frame);
        // first argument: name of the window.
        // second argument: image to be shown(Mat object).

        if (waitKey(30) == 27) // Wait for 'esc' key press to exit
        {
            break;
        }
    }

    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *