Capture image from webcam and display it - OpenCV - Eclipse - Windows

我怕爱的太早我们不能终老 提交于 2019-12-08 08:17:06

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/21336497/capture-image-from-webcam-and-display-it-opencv-eclipse-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!