从相机捕获视频

时间:2014-05-04 23:10:12

标签: c++ opencv osx-mavericks

我在OSX Mavericks上使用Macbook Air 2013。

#include <iostream>

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/video/tracking.hpp>

int main()
{
   cv::VideoCapture cap;
   cap.open(0);

   if( !cap.isOpened() )
   {
       std::cerr << "***Could not initialize capturing...***\n";
       return -1;
   }

   cv::Mat frame;

   while(1){
       cap >> frame;

       if(frame.empty()){
           std::cerr<<"frame is empty"<<std::endl;
           break;
       }

       cv::imshow("", frame);
       cv::waitKey(10);
   }

   return 1;
}

摄像机正确初始化(isOpened返回true),但它会一直返回空帧。但是,从文件而不是相机中检索帧可以正常工作。

此外,使用C API的cvQueryFrame似乎工作正常!

关于如何调试我的问题的任何想法?

编辑:下面的代码似乎让相机正常工作。谁知道为什么?

#include <iostream>

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/video/tracking.hpp>

using namespace cv;
using namespace std;

int main()
{
    VideoCapture cap;
    cap.open(0);
    namedWindow("Window");

    if( !cap.isOpened() )
    {
        std::cerr << "***Could not initialize capturing...***\n";
        return -1;
    }

    cv::Mat frame;

    while(1){
        cap >> frame;

        if(!(frame.empty())){
            imshow("Window", frame);
        }

        waitKey(10);
    }

    return 1;
}

2 个答案:

答案 0 :(得分:0)

这与我在笔记本电脑上使用OpenCv时遇到的问题相同。

只需在cvWaitKey(6700);循环之前添加while即可。

代码:

#include <iostream>

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/video/tracking.hpp>

using namespace cv;
using namespace std;

int main()
{
    VideoCapture cap;
    cap.open(0);
    namedWindow("Window");

    if( !cap.isOpened() )
    {
        std::cerr << "***Could not initialize capturing...***\n";
        return -1;
    }

    cv::Mat frame;

    waitKey(6700);

    while(1){
        cap >> frame;

        if(!(frame.empty())){
            imshow("Window", frame);
        }

        waitKey(25);
    }

    return 1;
}

希望它应该有用。

答案 1 :(得分:0)

尝试

while(cap.grab()){

        cap.retrieve(frame);
        waitKey(25);
    }

它不会给你空框架。

相关问题