C++ much slower than Python when displaying a USB Camera stream

I ran the following python code and the resulting video stream was buttery smooth and fast:

import cv2 as cv
cap = cv.VideoCapture(2)
while True:
    ret, frame = cap.read()
    if not ret:
    cv.imshow('frame', frame)
    if cv.waitKey(1) == ord('q'):

However, after running the code given here (and changing deviceID to 2), and building with the following CMakeLists.txt:

cmake_minimum_required(VERSION 3.21)


find_package(OpenCV REQUIRED)


add_executable(cppStreamer cppStreamer.cpp)
target_link_libraries(cppStreamer ${OpenCV_LIBS})

, the video stream became very laggy (about 1 second between frame updates) and the frame was about 2.5x bigger (on each axis, so about 6.25x the area) than the Python window:

Resizing by 0.25 on the x and y axes didn’t help the speed at all. Furthermore, the following was printed to the terminal upon running the C++ code but wasn’t printed when running the Python code:

[ WARN:0] global …/modules/videoio/src/cap_gstreamer.cpp (935) open OpenCV | GStreamer warning: Cannot query video position: status=0, value=-1, duration=-1

What could be causing the slowness?
I would put a picture of the python 's resulting window but new users are limited to 1 embedded media.

OS: Ubuntu 20.04.4 LTS x86_64
Kernel: 5.4.0-113-generic

i guess, the python version is using V4L, and as it looks, the c++ one gstreamer.

try to:

  • set the OPENCV_VIDEOIO_DEBUG=ON env variable for debug output. rerun prog, and show output here, please

  • explicitly set the backend: VideoCapture(2, CAP_V4L)

1 Like

Thanks berak. I tried setting OPENCV_VIDEOIO_DEBUG=ON but that was an invalid parameter so instead, I set it to 1. Here was the resulting output of the same program:

It was still slow.

But once I also set the backend:
cap.open(deviceID, CAP_V4L);

The video is buttery smooth just like python! thanks!!!

Now out of curiosity, why would V4L vs gstremer make such a big difference?