Skip to content

CamGear

Abhishek Thakur edited this page Jan 1, 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 this, CamGear API provides a flexible, high-level multi-threaded wrapper around OpenCV's VideoCapture API with access almost all of its available parameters and also employs pafy API for seamless YouTube streaming. Furthermore, CamGear relies exclusively on Threaded Queue mode for ultra-fast, error-free and synchronized frame handling.  

Tips: 💡

  • It is advised to turn logging parameter ON (i.e logging = True) on the first run, to easily identify run-time errors!

  • Threaded Queue Mode is enabled by default for any Videocapture stream - including Network Streams (except any Live Hardware Camera Feed/devices).

  • Use framerate class variable to retrieve framerate of the input video stream.

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

 

Importing:

You can import CamGear as follows:

from vidgear.gears import CamGear

 

Usage: 🔨

1. Bare-Minimum Example:

# import libraries
from vidgear.gears import CamGear
import cv2

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

# infinite loop
while True:
	frame = stream.read()
	# read frames

	# check if frame is None
	if frame is None:
		#if True break the infinite loop
		break
	
	# do something with frame here
	
	cv2.imshow("Output Frame", frame)
	# Show output window

	key = cv2.waitKey(1) & 0xFF
	# check for 'q' key-press
	if key == ord("q"):
		#if 'q' key-pressed break out
		break
# close output window
cv2.destroyAllWindows()
# safely close video stream.
stream.stop()

 

2. CamGear API with Variable Properties:

CamGear API supports various tweak parameters and attributes available within OpenCV's VideoCapture API properties. These can be applied to stream when it's being initiated. 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 your 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.


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

# import libraries
from vidgear.gears import CamGear
import cv2

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

stream = CamGear(source=0, logging = True, **options).start() # To open video stream on first index(i.e. 0) device

# infinite loop
while True:
	
	frame = stream.read()
	# read frames

	# check if frame is None
	if frame is None:
		#if True break the infinite loop
		break
	
	# do something with frame here
	
	cv2.imshow("Output Frame", frame)
	# Show output window

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

cv2.destroyAllWindows()
# close output window

stream.stop()
# safely close video stream.

 

3. Camgear API with Live Youtube Piplineing using Video URL:

CamGear API also supports Live Youtube Streaming with y_tube flag. Just provide the YouTube Video's URL as a string to the source attribute, enable y_tube parameter and enjoy direct YouTube Video Pipelining. Here's how you simply do it:


⚠️ Due to a recent bug, If you're using opencv-python instead of official OpenCV, 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. Install/Update using pip as follows:

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

For more info., see issue #14 ⚠️


# import libraries
from vidgear.gears import CamGear
import cv2

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

# infinite loop
while True:
	
	frame = stream.read()
	# read frames

	# check if frame is None
	if frame is None:
		#if True break the infinite loop
		break
	
	# do something with frame here
	
	cv2.imshow("Output Frame", frame)
	# Show output window

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

cv2.destroyAllWindows()
# close output window

stream.stop()
# safely close video stream.

 

4. Camgear API with Colorspace Manipulation for Video Source:

CamGear API supports On-the-fly Video Source ColorSpace conversion/manipulation.

 

Parameters and Attributes: 🔧

1. source: take the source value. Its default value is 0. This attribute can be used to directly input the path of the video. Valid Input can be one of the following:

⚠️ RuntimeError will be thrown if the source value is invalid!

  • 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()
  • File_path(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 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_Stream_Address(string): Valid incoming network stream URL such as http(s), rtp, rstp, rtmp, mms, etc.. For e.g 'rtsp://192.168.31.163:554/'as follows:

     stream = CamGear(source='rtsp://192.168.31.163:554/').start()
  • GStreamer Support: CamGear API also supports GStreamer Pipeline. Note that needs your OpenCV to have been built with GStreamer support, you can check this with print(cv2.getBuildInformation()) python command and check output if 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 videoconvert outputs 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()

2. y_tube (boolean) : enables YouTube Mode, i.e If enabled(y_tube=True) API will interpret the given source string as YouTube URL. Its default value is False.

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

4. 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

5. **options (dict) : provides the ability to tweak properties supported by OpenCV's VideoCapture API properties for any given input video stream directly. All the supported parameters can be passed to CamGear API using this dict as follows:

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

💡 All supported parameters are listed here.

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

7. time_delay (integer) : set the time delay(in seconds) before start reading the frames. This delay is essentially required for the camera to warm-up. Its default value is 0.

 

Clone this wiki locally