OpenCV视频捕获

时间:2015-10-11 18:14:38

标签: c++ opencv visual-studio-2013

我正在使用OpenCV 2.4.8和Visual Studio 2013来运行以下简单的VideoCapture程序。该程序旨在从网络摄像头捕获视频并显示它。 但是,该程序仅在第一时间(在Windows中登录后)正常工作,并且第二次不起作用。 我调试的问题是: 执行此行后 - “bool bSuccess = cap.read(frame);”帧变量仍为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;

}

2 个答案:

答案 0 :(得分:1)

这是因为在第一个程序实例后相机未正确关闭。您应该尝试通过esc按钮关闭控制台,而不是单击X.

答案 1 :(得分:0)

你可以尝试在打破循环之前读取多个帧吗?这可能与此问题类似,其中损坏的第一帧/慢速摄像机设置是唯一的问题。

Unable to read frames from VideoCapture from secondary webcam with OpenCV