简体   繁体   中英

OpenCV Video Capture

I am using OpenCV 2.4.8 and Visual Studio 2013 to run the following simple VideoCapture program. The program is intended to capture the video from the webcam and display it. However, the program works fine only for the FIRST TIME (after signing in windows), and doesn't work second time. The problem I get on debugging is : After executing this line - "bool bSuccess = cap.read(frame);" frame variable is still NULL.

#include "stdafx.h"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>

using namespace cv;
using namespace std;
char key;
int main(int argc, char* argv[])
{
   VideoCapture cap(0); // open the video camera no. 0

    if(!cap.isOpened())  // if not success, exit program
    {
        cout << "Cannot open the video file" << endl;
        return -1;
    }

    double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video
    double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video

    cout << "Frame size : " << dWidth << " x " << dHeight << endl;

    namedWindow("MyVideo",CV_WINDOW_AUTOSIZE); //create a window called "MyVideo"
    Mat frame;
    while(1)
    {


        bool bSuccess = cap.read(frame); // read a new frame from video

        if (!bSuccess) //if not success, break loop
        {
            cout << "Cannot read a frame from video file" << endl;
            break;
        }

        imshow("MyVideo", frame); //show the frame in "MyVideo" window

        if(waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
        {
            cout << "esc key is pressed by user" << endl;
            break; 
        }
    }
    return 0;

}

This happen because the camera is not correctly closed after first instance of program. You should try to close the console by esc button and not by clicking X.

Could you try and read more than a single frame before breaking the loop? This may be similar to this problem, where a corrupted first frame / slow camera set up was the only problem.

Unable to read frames from VideoCapture from secondary webcam with OpenCV

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM