Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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

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

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

ret, last_frame =
row, col, ch = last_frame.shape

if last_frame is None:

    ret, frame =

    if frame is None:

    cv2.imshow('frame', frame)

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


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())

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

    // When everything done, release the video capture object

    // Closes all the frames

    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.