title: OpenCV -- Function to grab frame
body: <p>I'm trying to create a function that gives the frame at the moment the function is called. So when i call the function, it should give the picture of the object that is in front of the camera at the moment the function is called.</p>
  
  <p>I have been trying for hours, but i can't succeed. Anyone?</p>
  
  <p>main file:</p>
  
  <pre><code>#include "camera.h"
  #include &lt;iostream&gt;
  #include &lt;unistd.h&gt;
  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;
  }
  </code></pre>
  
  <p>camera.h file</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;opencv2/highgui/highgui.hpp&gt;
  #include &lt;opencv2/imgproc/imgproc.hpp&gt;
  #include &lt;opencv2/core/core.hpp&gt;
  
  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 &lt;&lt; "---- Error ----" &lt;&lt; std::endl;
              return false;
          }
  
          return true;
      }
  
  
      //function GRAB FRAME
      //grabs the frame of the video capture
      //returns true if successfull
      bool grabFrame(cv::Mat&amp; cameraFrame){
          cap &gt;&gt; cameraFrame;
  
          if (cameraFrame.empty()){
              std::cout &lt;&lt; "---- Error ----" &lt;&lt; std::endl;
              return false;
          }   
  
          return true;
      }
  };
  </code></pre>