Search code examples
c++opencvvisual-studio-2015webcamopencv3.1

Webcam using Visual Studio 2015


I have VS-15 with OpenCV-3.1. On the output window I get a solid gray blank display. How do I solve it?

#include <opencv2\highgui\highgui.hpp>

int main() {
cvNamedWindow("Webcam Stream", CV_WINDOW_AUTOSIZE);
CvCapture* capture = cvCreateCameraCapture(0);
IplImage* frame;
while (1) {
    frame = cvQueryFrame(capture);
    if (!frame) break;
    cvShowImage("Streaming", frame);
    char c = cvWaitKey(33);
    if (c == 27) break;
}
cvReleaseCapture(&capture);
cvDestroyWindow("Example");
return 0;
}

Solution

  • Have no idea why it didn't work. But I managed to find another code from here. This new code does not display the mirror image so the view is laterally flipped. But it works.

    To edit it so that the image is not flipped replace the while loop with this:

        while (1)
    {
        Mat frame;
        Mat flipped; //***added new line
    
        bool bSuccess = cam.read(frame); // read a new frame from video
    
        if (!bSuccess) //if not success, break loop
        {
            cout << "Cannot read a frame from video stream" << endl;
            break;
        }
    
        cv::flip(frame, flipped, 1); //***added new line
    
        imshow("MyVideo", flipped); //***editted line
    
        if (waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
        {
            cout << "esc key is pressed by user" << endl;
            break;
        }
    }