OpenCV -- 抓取帧的函数

标签 opencv video-capture

我正在尝试创建一个函数,该函数在调用该函数时提供框架。所以当我调用该函数时,它应该给出调用该函数时相机前面的物体的图片。

我已经尝试了几个小时,但我无法成功。有人吗?

主文件:

#include "camera.h"
#include <iostream>
#include <unistd.h>
int main(int argc, const char *argv[])
{
    Camera cam;

    cam.setVideoSource(0);

    cv::Mat image;
    cv::Mat image2;

    cam.openCamera();

    cam.grabFrame(image);  // grap first frame
    sleep(5);              // wait 5 seconds
    cam.grabFrame(image2); // capture seconds frame

    cv::namedWindow("1",CV_WINDOW_KEEPRATIO);
    cv::imshow("1",image);

    cv::namedWindow("2",CV_WINDOW_KEEPRATIO);
    cv::imshow("2",image2);

    cv::waitKey();
    return 0;
}

camera.h文件

#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>

class Camera{
  private:
    int videoSource;    //video source
    cv::VideoCapture cap;   //capture of camera


  public:
    //constructor default videoSourceNumber 
    Camera() : videoSource(0) {};

    //Setter: videoSourceNumber
    void setVideoSource(int sourceNumber){
        videoSource = sourceNumber;
    }


    //function OPEN CAMERA
    //opens the video capture
    //returns true if successfull
    bool openCamera() {
        cap.open(videoSource);

        if (!cap.isOpened()){
            std::cout << "---- Error ----" << std::endl;
            return false;
        }

        return true;
    }


    //function GRAB FRAME
    //grabs the frame of the video capture
    //returns true if successfull
    bool grabFrame(cv::Mat& cameraFrame){
        cap >> cameraFrame;

        if (cameraFrame.empty()){
            std::cout << "---- Error ----" << std::endl;
            return false;
        }   

        return true;
    }
};

最佳答案

一个不太令人满意的解决方案:

//function GRAB FRAME
//grabs the frame of the video capture
//returns true if successfull
bool grabFrame(cv::Mat& cameraFrame){
    int attempts = 0;
    do {
        cap >> cameraFrame;
        attempts++;
    } while (cameraFrame.empty() && attempts < 10);

    if (cameraFrame.empty()){
        std::cout << "---- Error ----" << std::endl;
        return false;
    }   

    return true;
}

我也玩了一段时间,没找到解决办法。我的直觉是在请求第一帧之前给相机更多的“预热”时间。 sleep 10 秒似乎可以做到这一点,但这是 Not Acceptable 。如果我在第一次调用 grabFrame() 之前不让它休眠,我添加的 while 循环似乎只运行了两次。

归功于:https://stackoverflow.com/a/9285151/2518451

关于OpenCV -- 抓取帧的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18992644/

相关文章:

OpenCV-3.0.0-beta 无法在 32 位和 64 位 Ubuntu12.04 上构建 - IPP 符号未定义

python - 在 Linux (Fedora 15 Beta) 上使用 OpenCV 2.2 和 Python 捕获图像

opencv - findFundamentalMat 的掩码输出参数是什么?

image-processing - 霍夫变换以确定线条及其宽度

python - opencv 视频捕获的 tqdm 进度条超过 100%

video - 选择用于屏幕录制的视频编解码器

ios - 检测相机何时自动对焦

从网络摄像头捕获图像并显示它 - OpenCV - Eclipse - Windows

python - Ubuntu : error using cv2. imshow() 与 pyplot.plot()

c - 需要明确 OpenCV 中 cvCaptureFromFile 的用法