Skip to content

PiGear API Usage Examples:

PiGear API now fully supports the newer picamera2 python library under the hood for Raspberry Pi camera modules. Follow this guide ➶ for its installation.

Make sure to complete Raspberry Pi Camera Hardware-specific settings prior using this API, otherwise nothing will work.

After going through following Usage Examples, Checkout more of its advanced configurations here ➶

Bare-Minimum Usage

Following is the bare-minimum code you need to get started with PiGear API:

Under the hood, PiGear API (version 0.3.3 onwards) prioritizes the new picamera2 API backend.

However, PiGear API seamlessly switches to the legacy picamera backend, if the picamera2 library is unavailable or not installed.

It is advised to enable logging(logging=True) to see which backend is being used.

The picamera library is built on the legacy camera stack that is NOT (and never has been) supported on 64-bit OS builds.

You could also enforce the legacy picamera API backend in PiGear by using the enforce_legacy_picamera user-defined optional parameter boolean attribute.

Disabling common libcamera API messages in silent mode.

The picamera2 backend can be a bit verbose with logging messages from the underlying libcamera library, even when logging is disabled (logging=False) in the PiGear API.

  • To suppress these messages, you'll need to set LIBCAMERA_LOG_LEVELS=2 environment variable before running your application. This will disable common libcamera API messages, keeping your console output cleaner.
  • This can be done on various Operating Systems as follows:
export LIBCAMERA_LOG_LEVELS=2
$Env:LIBCAMERA_LOG_LEVELS=2
export LIBCAMERA_LOG_LEVELS=2
# import required libraries
from vidgear.gears import PiGear
import cv2

# open stream with default parameters
stream = PiGear().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()

 

Using PiGear with Variable Camera Properties

PiGear provides a user-friendly interface for the underlying picamera2 library, offering access to almost all of its important configurational parameters. It simplifies configuration for developers with even basic knowledge of Raspberry Pi camera modules, allowing them to easily configure and control the camera functionality with just a few lines of code.

This example doc showcases the capabilities of PiGear and demonstrates how it simplifies camera configuration with Picamera2 API backend.

All supported Picamera2 Library Configurational Parameters [IMPORTANT]

Following are the list of Picamera2 parameters, i.e. if supported, can be applied to the source stream in PiGear API through its options dictionary parameter by formatting them as its attributes.

Few Important points
  • These PiCamera2 parameters must be formatted as PiGear API's options dictionary parameter keys, and their values MUST strictly adhere to the specified data types (see table below). If the values do not follow the specified data types, they will be discarded.
  • PiGear API only defines the default main stream configuration that is delivered to the PiCamera2 API. You CANNOT define other streams (such as lores, raw) manually.
  • The FrameDuration and FrameDurationLimits properties of control configurational parameter are NOT supported and will be discarded, since camera FPS is handled by framerate parameter in PiGear API.
  • The resolution parameter will be OVERRIDDEN, if the user explicitly defines the output_size property of the sensor configurational parameter in PiGear API.
Parameters Datatype Description Supported Supported on USB Cameras Remarks
buffer_count int, >=1 number of sets of buffers to allocate for the camera system ✅ ❌ Read Docs here ➶
queue bool whether the system is allowed to queue up a frame ready for a capture request ✅ ❌ Read Docs here ➶
controls dict specify a set of runtime controls that can be regarded as part of the camera configuration ✅ ❌ Read Docs here ➶
sensor dict allow to select a particular mode of operation for the sensor ✅ ✅ Read Docs here ➶
format str Pixel formats ✅ ✅ Read Docs here ➶ and see Bonus example ➶
transform Transform1 The 2D plane transform that is applied to all images from all the configured streams. ✅ ❌ Read Docs here ➶
colour_space colour space of the output images ❌ 🚫 Handled by colorspace parameter of PiGear API
size A tuple of two values giving the width and height of the output image. (Both numbers should be no less than 64) ❌ 🚫 Handled by resolution parameter of PiGear API
display name of the stream that will be displayed in the preview window. ❌ 🚫 Not-Required
encode name of the stream that will be used for video recording. ❌ 🚫 Not-Required
Limited support for USB Cameras

This example also works with USB Cameras, However:

  • Users should assume that features such as: Camera controls ("controls"), Transformations ("transform"), Queue ("queue") , and Buffer Count ("buffer_count") that are supported on Raspberry Pi cameras, and so forth, are not available on USB Cameras.
  • Hot-plugging of USB cameras is also NOT supported - PiGear API should be completely shut down and restarted when cameras are added or removed.
Enabling verbose logs for backend PiCamera2 Library

The PiGear API allows you to enable more detailed logging from the picamera2 backend library using the enable_verbose_logs user-defined optional parameter attribute. This can be used in conjunction with enabling general logging (logging=True) in the PiGear API for even more granular control over logging output.

PiGear also support changing parameter at runtime. Checkout this bonus example here ➶

# import required libraries
from vidgear.gears import PiGear
from libcamera import Transform
import cv2

# formulate various Picamera2 API 
# configurational parameters
options = {
    "queue": True,
    "buffer_count": 4,
    "controls": {"Brightness": 0.5, "ExposureValue": 2.0},
    "transform": Transform(hflip=1),
    "sensor": {"output_size": (480, 320)},  # !!! will override `resolution` !!!
    "auto_align_output_size": True,  # auto-align output size
}

# open pi video stream with defined parameters
stream = PiGear(resolution=(640, 480), framerate=60, logging=True, **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()

PiGear API switches to the legacy picamerabackend if the picamera2 library is unavailable.

It is advised to enable logging(logging=True) to see which backend is being used.

The picamera library is built on the legacy camera stack that is NOT (and never has been) supported on 64-bit OS builds.

You could also enforce the legacy picamera API backend in PiGear by using the enforce_legacy_picamera user-defined optional parameter boolean attribute.

PiGear also supports almost every parameter available within picamera python library. These parameters can be easily applied to the source stream in PiGear API through its options dictionary parameter by formatting them as its attributes. The complete usage example is as follows:

All supported parameters are listed in PiCamera Docs ➶

PiGear also support changing parameter at runtime. Checkout this bonus example here ➶

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

# formulate various Picamera API 
# configurational parameters
options = {
    "hflip": True,
    "exposure_mode": "auto",
    "iso": 800,
    "exposure_compensation": 15,
    "awb_mode": "horizon",
    "sensor_mode": 0,
}

# open pi video stream with defined parameters
stream = PiGear(resolution=(640, 480), framerate=60, logging=True, **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()

 

Using PiGear with Direct Colorspace Manipulation

PiGear API also supports Direct Colorspace Manipulation, which is ideal for changing source colorspace on the run.

A more detailed information on colorspace manipulation can be found here ➶

In following example code, we will start with HSV as source colorspace, and then we will switch to GRAY colorspace when W key is pressed, and then LAB colorspace when E key is pressed, finally default colorspace (i.e. BGR) when S key is pressed. Also, quit when Q key is pressed:

Any incorrect or None-Type value will immediately revert the colorspace to default (i.e. BGR).

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

# open pi video stream with defined parameters and change colorspace to `HSV`
stream = PiGear(
    resolution=(640, 480),
    framerate=60,
    colorspace="COLOR_BGR2HSV",
    logging=True
).start()


# loop over
while True:

    # read HSV frames
    frame = stream.read()

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

    # {do something with the HSV frame here}

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

    # check for key if pressed
    key = cv2.waitKey(1) & 0xFF

    # check if 'w' key is pressed
    if key == ord("w"):
        # directly change colorspace at any instant
        stream.color_space = cv2.COLOR_BGR2GRAY  # Now colorspace is GRAY

    # check for 'e' key is pressed
    if key == ord("e"):
        stream.color_space = cv2.COLOR_BGR2LAB  # Now colorspace is CieLAB

    # check for 's' key is pressed
    if key == ord("s"):
        stream.color_space = None  # Now colorspace is default(ie BGR)

    # check for 'q' key is pressed
    if key == ord("q"):
        break

# close output window
cv2.destroyAllWindows()

# safely close video stream
stream.stop()

 

Using PiGear with WriteGear API

PiGear can be easily used with WriteGear API directly without any compatibility issues. The suitable example is as follows:

# import required libraries
from vidgear.gears import PiGear
from vidgear.gears import WriteGear
from libcamera import Transform
import cv2

# formulate various Picamera2 API 
# configurational parameters
options = {
    "queue": True,
    "buffer_count": 4,
    "controls": {"Brightness": 0.5, "ExposureValue": 2.0},
    "transform": Transform(hflip=1),
    "sensor": {"output_size": (480, 320)},  # will override `resolution`
    "auto_align_output_config": True,  # auto-align camera configuration
}

# open pi video stream with defined parameters
stream = PiGear(resolution=(640, 480), framerate=60, logging=True, **options).start()

# define suitable (Codec,CRF,preset) FFmpeg parameters for writer
output_params = {"-vcodec": "libx264", "-crf": 0, "-preset": "fast"}

# Define writer with defined parameters and suitable output filename for e.g. `Output.mp4`
writer = WriteGear(output="Output.mp4", logging=True, **output_params)

# 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}
    # lets convert frame to gray for this example
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # write gray frame to writer
    writer.write(gray)

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

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

# safely close writer
writer.close()
PiGear API switches to the legacy picamerabackend if the picamera2 library is unavailable.

It is advised to enable logging(logging=True) to see which backend is being used.

The picamera library is built on the legacy camera stack that is NOT (and never has been) supported on 64-bit OS builds.

You could also enforce the legacy picamera API backend in PiGear by using the enforce_legacy_picamera user-defined optional parameter boolean attribute.

# import required libraries
from vidgear.gears import PiGear
from vidgear.gears import WriteGear
import cv2

# formulate various Picamera API 
# configurational parameters
options = {
    "hflip": True,
    "exposure_mode": "auto",
    "iso": 800,
    "exposure_compensation": 15,
    "awb_mode": "horizon",
    "sensor_mode": 0,
}

# open pi video stream with defined parameters
stream = PiGear(resolution=(640, 480), framerate=60, logging=True, **options).start()

# define suitable (Codec,CRF,preset) FFmpeg parameters for writer
output_params = {"-vcodec": "libx264", "-crf": 0, "-preset": "fast"}

# Define writer with defined parameters and suitable output filename for e.g. `Output.mp4`
writer = WriteGear(output="Output.mp4", logging=True, **output_params)

# 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}
    # lets convert frame to gray for this example
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # write gray frame to writer
    writer.write(gray)

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

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

# safely close writer
writer.close()

 


  1. A custom libcamera API class. Must be imported as from libcamera import Transform