Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

OK, try this code. This is a complete code to display a webcam still on screen with a spacebar push. (Not the best code in the world but it works for me!)

#include "opencv2/opencv.hpp"
#include <opencv2/imgcodecs.hpp>
#include <opencv2/videoio/videoio.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <iostream>
#include <stdio.h>

using namespace cv;
using namespace std;

int main(int, char**)
{

    VideoCapture cap(0); // Try with 0,1,2, etc. this is the number of your camera 
    if(!cap.isOpened())  // check if we succeeded
        return -1;

    int wow;
    Mat frame;
    for(;;) // Actually this is kind like while(1)
    {
        wow = waitKey(0); // (wait for a keyboard input)

        if(wow==0x1B) break; // This is when you press Esc
        else if(wow == 0x20) {  //When you press the Spacebar

            cap >> frame; // get a new frame from camera    
            imshow("Your Image", frame);
        }    
    }
    // the camera will be deinitialized automatically in VideoCapture destructor
    return 0;
}

So be cautious with the number of the VideoCapture cap(0), this could be a non existent camera. Yours could be VideoCapture(1)...