My Python code shows webcam, buy my C++ does not.

asked 2018-07-13 20:26:48 -0500

masterenol gravatar image

Here is my Python 3 code that properly displays my webcam:

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

ret, last_frame = cap.read()
row, col, ch = last_frame.shape

if last_frame is None:
    exit()

while(cap.isOpened()):
    ret, frame = cap.read()

    if frame is None:
        exit()

    cv2.imshow('frame', frame)

    if cv2.waitKey(33) == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

Below is a C++ code that does not display my webcam. This code only displays a grey frame:

#include "opencv2/opencv.hpp"
#include <iostream>

using namespace std;
using namespace cv;

int main() {
    //In this block,we create a video capture object and 
    //read a input video file.
    // Create a VideoCapture object and open the input file
    // If the input is the web camera, pass 0 instead of the video file name
    VideoCapture cap(0);
    // Check if camera opened successfully and read a frame from the object cap
    if (!cap.isOpened()) {
        cout << "Error opening video stream or file" << endl;
        return -1;
    }

    //Read and display video frames until video is completed or 
    //user quits by pressing ESC
    while (1) {

        Mat frame;
        // Capture frame-by-frame
        cap >> frame;

        // If the frame is empty, break immediately
        if (frame.empty())
            break;

        // Display the resulting frame
        imshow("Frame", frame);
        // Press  ESC on keyboard to exit
        char c = (char)waitKey(25);
        if (c == 27)
            break;
    }

    // When everything done, release the video capture object
    cap.release();

    // Closes all the frames
    destroyAllWindows();

    return 0;
}

Can someone please help me with this issue? I tried modifying my C++ to VideoCapture cap(1), VideoCapture cap(2), VideoCapture cap(3), and VideoCapture cap but I still get no live video from my webcam.

edit retag flag offensive close merge delete

Comments

if you're using 3.4.2, you could try to set a debug environment variable:

set OPENCV_VIDEOIO_DEBUG=1

(this would show you, which backends are tried, and which one is finally used)

you can also try to specify a certain backend, e.g.:

cap.open(0, CAP_MSMF);

berak gravatar imageberak ( 2018-07-14 01:36:13 -0500 )edit

Thanks for your response berak. My Visual Studio did not recognize the keyword 'set', but I did get the webcam to show by using Visual Studio 2015, changing my OpenCV to OpenCV 3.4.2, and making the appropriate changes to Path and Visual Studio project properties.

masterenol gravatar imagemasterenol ( 2018-07-14 20:34:38 -0500 )edit