Skip to content

CamGear

Abhishek Thakur edited this page Apr 23, 2020 · 73 revisions

VidGear Logo

CamGear API

CamGear supports a diverse range of video streams which can handle/control video stream almost any IP/USB Cameras, multimedia video file format (upto 4k tested), any network stream URL such as http(s), rtp, rstp, rtmp, mms, etc. In addition to this, it also supports live Gstreamer's RAW pipelines and YouTube video/livestreams URLs.

To implement these tasks, CamGear API provides a flexible, high-level multi-threaded wrapper around OpenCV's VideoCapture API with direct access to almost all of its available parameters and also internally employs pafy with youtube-dl backend for seamless live YouTube streaming.

Furthermore, CamGear relies exclusively on Threaded Queue mode for ultra-fast, error-free and synchronized frame handling.

 

Important 💡

  • ⚠️ CamGear API will throw RuntimeError if source provided is invalid!

  • It is advised to enable logging (logging = True) on the first run, to easily identify any runtime errors.

  • You can use framerate class variable to retrieve framerate of the input video stream.

 

 

Table of Contents:

 

 

Importing:

You can import CamGear as follows:

from vidgear.gears import CamGear

 

 

Usage: 🔨

1. Bare-Minimum Example:

# import required libraries
from vidgear.gears import CamGear
import cv2


# open any valid video stream(for e.g `myvideo.avi` file)
stream = CamGear(source='myvideo.avi').start() 

# loop over
while True:

    # read frames from stream
    frame = stream.read()

    # check for frame if Nonetype
    if frame is None:
        break


    # {do something with the frame here}


    # Show output window
    cv2.imshow("Output Frame", frame)

    # check for 'q' key if pressed
    key = cv2.waitKey(1) & 0xFF
    if key == ord("q"):
        break

# close output window
cv2.destroyAllWindows()

# safely close video stream
stream.stop()

 

2. Camgear API with Live Youtube Pipelining using Video URL:

CamGear API provide complete support for Live Youtube Video Streaming.

Just provide the YouTube Video's URL as a string to its source parameter and enable y_tube parameter and enjoy direct YouTube Video frame Pipelining. Here's how you simply do it:


⚠️ Due to a bug, If you're using PyPi installed opencv-python, instead of official OpenCV Binaries, then you must need to install the latest opencv-python or opencv-contrib-python binaries (v4.1.1.26 or above) on your machine to run this code without any errors as follows:

sudo pip3 install -U opencv-python       #or install opencv-contrib-python similarly

# import required libraries
from vidgear.gears import CamGear
import cv2


# Add YouTube Video URL as input source of your choice
stream = CamGear(source='https://youtu.be/dQw4w9WgXcQ', y_tube=True, logging=True).start() 

# loop over
while True:

    # read frames from stream
    frame = stream.read()

    # check for frame if Nonetype
    if frame is None:
        break


    # {do something with the frame here}


    # Show output window
    cv2.imshow("Output Frame", frame)

    # check for 'q' key if pressed
    key = cv2.waitKey(1) & 0xFF
    if key == ord("q"):
        break

# close output window
cv2.destroyAllWindows()

# safely close video stream
stream.stop()

 

3. CamGear API with Variable Properties:

CamGear API supports various source tweak parameters available within OpenCV's VideoCapture API properties.

These source tweak parameters can be applied to stream when it's being initiated through its **option dictionary parameter. The complete example is as follows:


Important Note: ⚠️

  • Remember, not all of the OpenCV parameters are supported by all cameras. Each camera type, from android cameras to USB cameras to professional ones offers a different interface to modify its parameters. Therefore there are many branches in OpenCV code to support as many of them, but of course, not all possible devices are covered and therefore works.

  • Therefore, To check parameter values supported by your webcam, you can hook your camera to a Linux machine and use command v4l2-ctl -d 0 --list-formats-ext (where 0 is the index of the given camera) to list the supported video parameters and their values OR directly refer to the device corresponding datasheet, if available.

  • 💡 All the supported parameters can be found in this Wiki.


# import required libraries
from vidgear.gears import CamGear
import cv2


# define suitable tweak parameters for your stream.
options = {"CAP_PROP_FRAME_WIDTH ":320, "CAP_PROP_FRAME_HEIGHT":240, "CAP_PROP_FPS ":60}

# To open live video stream on webcam at first index(i.e. 0) device and apply source tweak parameters
stream = CamGear(source=0, **options).start() 

# loop over
while True:

    # read frames from stream
    frame = stream.read()

    # check for frame if Nonetype
    if frame is None:
        break


    # {do something with the frame here}


    # Show output window
    cv2.imshow("Output Frame", frame)

    # check for 'q' key if pressed
    key = cv2.waitKey(1) & 0xFF
    if key == ord("q"):
        break

# close output window
cv2.destroyAllWindows()

# safely close video stream
stream.stop()

 

4. Camgear API with Colorspace Manipulation for Video Source:

CamGear API also supports direct Source ColorSpace conversion/manipulation.

See its Wiki-page for details and usage examples ➶

 

 

Parameters and Attributes: 🔧

  • source: defines the source for the stream and its default value is 0. Its valid input can be one of the following:

    • Index (integer): Valid index of the connected video device, for e.g 0, or 1, or 2 etc. as follows:

      stream = CamGear(source=0).start()
    • Filepath (string): Valid path of the video file, for e.g "/home/foo.mp4" as follows:

      stream = CamGear(source='/home/foo.mp4').start()
    • YouTube Video's URL (string): Valid Youtube video URL as input when YouTube Mode is enabled(i.e. y_tube=True), for e.g "https://youtu.be/dQw4w9WgXcQ" as follows:

      stream = CamGear(source='https://youtu.be/dQw4w9WgXcQ', y_tube =True).start()

      👀 See example code above

    • Network Address (string): Valid (http(s), rtp, rstp, rtmp, mms, etc.) incoming network stream address such as 'rtsp://192.168.31.163:554/' as input:

       stream = CamGear(source='rtsp://192.168.31.163:554/').start()
    • GStreamer Pipeline:

      CamGear API also supports GStreamer Pipeline.

      ⚠️ Important: It needs your OpenCV to be built with GStreamer support. You can easily check it by running print(cv2.getBuildInformation()) python command and see if output contains something similar as follows:

      Video I/O:
       ...
           GStreamer:                   
             base:                      YES (ver 1.8.3)
             video:                     YES (ver 1.8.3)
             app:                       YES (ver 1.8.3)
      ...

      Also finally, be sure convert video output into BGR format, for example as follows:

      stream = CamGear(source='udpsrc port=5000 ! application/x-rtp,media=video,payload=96,clock-rate=90000,encoding-name=H264, ! rtph264depay ! decodebin ! videoconvert ! video/x-raw, format=BGR ! appsink').start()
  • y_tube (boolean) : controls the YouTube Mode. If this parameter is enabled(i.e. y_tube=True), CamGear will interpret the given source input as YouTube URL address. Its default value is False.

  • colorspace (string) : set the colorspace of the source stream. Its default value is None. Check out its detailed Usage here ➶.

  • backend (int) : set the backend of the OpenCV's VideoCapture class (only if specified). Its value can be for e.g. backend = cv2.CAP_DSHOW in case of Direct Show input. Its default value is 0

    💡 All supported backends are listed here ➶.

  • **options (dict) : provides the ability to tweak parameters to given input source stream directly. All the supported parameters can be passed to CamGear API using this parameter, as follows:

      options = {"CAP_PROP_FRAME_WIDTH ":320, "CAP_PROP_FRAME_HEIGHT":240, "CAP_PROP_FPS ":60} 

    💡 All supported parameters are listed here ➶.

  • logging (boolean) : set this flag to enable/disable logging, essential for debugging. Its default value is False.

  • time_delay (integer) : set the time delay (in seconds) before start reading the frames. This delay is essentially required if the source required warm-up delay before starting up. Its default value is 0.

 

Clone this wiki locally