Question

I'm new to OpenCV and I want to display what my webcam sees with OpenCV. I'm using the C Coding Language.

I've tried with this code:

#include <stdio.h>

#include <cv.h> // Include the OpenCV library
#include <highgui.h> // Include interfaces for video capturing

int main()
{
    cvNamedWindow("Window", CV_WINDOW_AUTOSIZE);
    CvCapture* capture =cvCreateCameraCapture(-1);
    if (!capture){
        printf("Error. Cannot capture.");
    }
    else{
        cvNamedWindow("Window", CV_WINDOW_AUTOSIZE);

        while (1){
            IplImage* frame = cvQueryFrame(capture);
            if(!frame){
                printf("Error. Cannot get the frame.");
                break;
            }
        cvShowImage("Window",frame);
        }
        cvReleaseCapture(&capture);
        cvDestroyWindow("Window");
    }
    return 0;
}

My webcam's light turns on, but the result is a completely grey window, with no image.

Can you help me?

Was it helpful?

Solution

You need to add

cvWaitKey(30);

to the end of while-loop.


cvWaitKey(x) / cv::waitKey(x) does two things:

  1. It waits for x milliseconds for a key press. If a key was pressed during that time, it returns the key's ASCII code. Otherwise, it returns -1.
  2. It handles any windowing events, such as creating windows with cvNamedWindow(), or showing images with cvShowImage().

A common mistake for opencv newcomers is to call cvShowImage() in a loop through video frames, without following up each draw with cvWaitKey(30). In this case, nothing appears on screen, because highgui is never given time to process the draw requests from cvShowImage().

See What does OpenCV's cvWaitKey( ) function do? for more info.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top