Core library#

QCamera#

Abstract base class for all QVideo camera backends.

class QVideo.lib.QCamera.QCamera(*args, **kwargs)[source]#

Bases: QObject

Abstract base class for camera devices.

Provides a unified interface for camera control and image acquisition, including thread-safe frame reading, a registration-based property system, and context-manager support.

Subclasses implement _initialize(), _deinitialize(), and read(), then call registerProperty() and registerMethod() to expose their adjustable parameters and executable actions. Properties may be registered at any time — including inside _initialize() — which allows cameras whose feature sets are only known after connecting to hardware (e.g. GenICam devices) to discover and publish their parameters at run-time.

Registered properties are accessible both through the explicit get() / set() API and as ordinary Python attributes — reads (camera.fps) and writes (camera.fps = 30) are both routed through the registered getter and setter.

Parameters:
  • *args – Positional arguments forwarded to QObject.

  • **kwargs – Keyword arguments forwarded to QObject.

  • Signals

  • ——-

  • shapeChanged(QSize) – Emitted by subclasses when the image dimensions change.

  • propertyValue(str, object) – Emitted by get() with the property name and current value.

  • Type Aliases

  • ————

  • PropertyValue (bool | int | float | str) – Common type for scalar camera property values.

  • Settings (dict[str, PropertyValue]) – Mapping of property name to value, as returned by settings().

  • Image (NDArray[np.uint8]) – A single camera frame.

  • CameraData (tuple[bool, Image | None]) – Return type of read().

Notes

QCamera holds a single non-recursive mutex. set(), get(), execute(), and saferead() all acquire it, so subclass read() implementations must not call back into any of those methods or a deadlock will result. Pause and resume control is the responsibility of the enclosing QVideoSource.

PropertyValue = bool | int | float | str#
Settings#

alias of dict[str, bool | int | float | str]

CameraData#

alias of tuple[bool, ndarray[tuple[Any, …], dtype[uint8]] | None]

shapeChanged#

Emitted by subclasses when the image dimensions change.

propertyValue#

Emitted by get() with the property name and current value.

registerProperty(name, getter=<QVideo.lib.QCamera._Auto object>, setter=<QVideo.lib.QCamera._Auto object>, ptype=<class 'float'>, **meta)[source]#

Register a named camera property.

By default both getter and setter are auto-generated from the _name backing-attribute convention: the getter reads self._name and the setter writes ptype(value) back to self._name. Pass an explicit callable to override either, or pass setter=None to make the property read-only.

Parameters:
  • name (str) – Property name used with get(), set(), and attribute access.

  • getter (callable, optional) – Zero-argument callable returning the current value. Defaults to lambda: getattr(self, f'_{name}').

  • setter (callable or None, optional) – Single-argument callable applying a new value. None marks the property read-only. Defaults to lambda v: setattr(self, f'_{name}', ptype(v)).

  • ptype (type) – Python type of the property value (int, float, bool, str). Drives the default setter coercion and is stored for use by UI generators such as QCameraTree.

  • **meta – Additional metadata (e.g. minimum, maximum, step).

Return type:

None

registerMethod(name, method)[source]#

Register a named callable method.

Parameters:
  • name (str) – Method name used with execute().

  • method (callable) – Zero-argument callable to invoke.

Return type:

None

open(*args, **kwargs)[source]#

Open the camera device.

Calls _initialize() only if the device is not already open.

Return type:

QCamera

Returns:

QCameraself, to allow chaining.

close()[source]#

Close the camera device.

Safe to call on an already-closed device.

Return type:

None

isOpen()[source]#

Return whether the device is currently open.

Return type:

bool

property properties: list[str]#

Names of all registered properties.

property methods: list[str]#

Names of all registered methods.

property settings: dict[str, bool | int | float | str]#

All registered property values as a name→value dict.

Uses registered getters directly to avoid emitting propertyValue for each property.

set(key, value)[source]#

Set a registered property to the given value.

Parameters:
  • key (str) – Property name.

  • value (PropertyValue) – New value to assign.

Return type:

None

get(key)[source]#

Return the current value of a registered property.

Emits propertyValue with the name and value.

Parameters:

key (str) – Property name.

Return type:

bool | int | float | str | None

Returns:

PropertyValue or None – Current value, or None if the property is unknown.

execute(key)[source]#

Call a registered method by name.

Parameters:

key (str) – Method name.

Return type:

None

abstractmethod read()[source]#

Read one frame from the camera.

Return type:

tuple[bool, ndarray[tuple[Any, ...], dtype[ubyte]] | None]

Returns:

tuple[bool, Image or None](True, frame) on success, (False, None) on failure.

Notes

Must not call set(), get(), execute(), or saferead() — those methods acquire the same non-recursive mutex that saferead() holds while invoking read().

saferead()[source]#

Read one frame under the camera mutex.

Blocks any concurrent call to set(), get(), or execute() until the frame transfer completes.

Return type:

tuple[bool, ndarray[tuple[Any, ...], dtype[ubyte]] | None]

Returns:

tuple[bool, Image or None] – Result of read().

property name: str#

Camera name, derived from the concrete class name.

property shape: QSize#

Image dimensions as QSize(width, height).

Returns QSize(0, 0) if width or height are not registered.

classmethod example()[source]#

Print camera settings and read a few frames.

Return type:

None

QVideoSource#

QThread wrapper that drives a QCamera and emits newFrame signals.

class QVideo.lib.QVideoSource.QVideoSource(source)[source]#

Bases: QThread

A threaded video source that reads frames from a camera or video file in a separate thread.

Parameters:
  • source (QCamera | QVideoReader) – The video source to read frames from.

  • Signals

  • ——-

  • newFrame(Image) – Emitted when a new video frame is available.

  • Properties

  • ———-

  • source (QCamera | QVideoReader) – The video source object.

  • fps (float) – Frame rate of the video source [frames per second].

  • shape (QSize) – The shape of the video frames (width, height).

isOpen() bool[source]#

Check if the video source is open.

start() QVideoSource[source]#

Start the video source thread.

stop() None[source]#

Stop the video source thread.

pause() None[source]#

Pause video readout.

resume() None[source]#

Resume video readout after pause().

isPaused() bool[source]#

Check if video readout is paused.

example(*args) None[source]#

Demonstrate basic operation of a threaded video source.

Notes

The source is moved to this thread via moveToThread so that its slots are delivered in the capture thread rather than the main thread. State variables _running and _paused are protected by mutex; waitcondition is used to block the capture loop while paused and to wake it on resume() or stop().

newFrame#

Emitted when a new video frame is available.

property source: QCamera | QVideoReader#

The underlying QCamera or QVideoReader.

isOpen()[source]#

Return whether the source is open.

Return type:

bool

property fps: float#

Frame rate of the video source [frames per second].

property shape: QSize#

Shape of the video frames as QSize(width, height).

run()[source]#

Capture loop: open the source, read frames, emit newFrame.

Opens the source via its context manager, then loops calling saferead() and emitting newFrame for each successful frame. The loop blocks when pause() is called and resumes when resume() or stop() is called.

This method is invoked automatically by start() in a new thread and should not be called directly in production code.

Return type:

None

start()[source]#

Start the capture thread.

Safe to call after stop() / wait() to restart the source. Resets internal running state before launching the thread so that a previously-stopped source can be started again.

Return type:

QVideoSource

Returns:

QVideoSourceself, to allow chaining e.g. src = QVideoSource(cam).start().

stop()[source]#

Stop the capture thread.

Sets _running to False and wakes any thread blocked in pause(), so that run() exits cleanly at the next loop iteration.

Return type:

None

pause()[source]#

Pause frame readout.

The capture loop will block after the current frame completes. Has no effect if the thread is not running. Call resume() to continue.

Return type:

None

resume()[source]#

Resume frame readout after pause().

Return type:

None

isPaused()[source]#

Return True if the capture loop is currently paused.

Return type:

bool

classmethod example(*args)[source]#

Demonstrate basic operation of a threaded video source.

Return type:

None

QCameraTree#

Auto-building pyqtgraph parameter tree for QCamera property inspection.

class QVideo.lib.QCameraTree.QCameraTree(source, description=None, *args, **kwargs)[source]#

Bases: ParameterTree

A parameter tree widget for controlling QCamera properties.

Wraps a QVideoSource (or a bare QCamera) and presents its settings as an editable ParameterTree. Changes made in the tree are pushed to the camera; camera-side changes are reflected back into the tree.

Parameters:
  • source (QCamera or QVideoSource) – The video source to control. Must already be open.

  • description (list[dict] or None) – Parameter-tree description of the camera properties to expose. If None a default description is generated from settings.

  • *args – Additional positional arguments forwarded to ParameterTree.

  • **kwargs – Additional keyword arguments forwarded to ParameterTree.

Raises:

RuntimeError – If source is not open when the tree is created.

closeEvent(event)[source]#

Stop the video source when the widget is closed.

Return type:

None

set(key, value)[source]#

Set a camera property and update the tree.

Parameters:
  • key (str) – Property name.

  • value (QCamera.PropertyValue) – New value.

Return type:

None

get(key)[source]#

Get a camera property value from the tree.

Parameters:

key (str) – Property name.

Return type:

bool | int | float | str | None

Returns:

QCamera.PropertyValue or None – Current value, or None if key is not in the tree.

property source: QVideoSource#

The underlying QVideoSource.

property camera: QCamera#

The QCamera driven by this tree.

start()[source]#

Start the video source.

Return type:

QCameraTree

Returns:

QCameraTreeself, to allow chaining (e.g. tree = QCameraTree(...).start()).

stop()[source]#

Stop and join the video source thread.

Return type:

None

classmethod example()[source]#

Demonstrate the widget with a default camera source.

Return type:

None

QVideoScreen#

Live video display widget with mouse-aware graphical overlay support.

class QVideo.lib.QVideoScreen.QVideoScreen(*args, size=(640, 480), framerate=None, **kwargs)[source]#

Bases: GraphicsLayoutWidget

Video display widget.

Displays frames from a QVideoSource in real time, with optional frame-rate throttling and image filtering via QFilterBank.

Inherits from pyqtgraph.GraphicsLayoutWidget.

Parameters:
  • size (tuple[int, int]) – Initial widget dimensions in pixels. Default: (640, 480).

  • framerate (int | None) – Maximum display frame rate in frames per second. None means no throttling. Default: None.

  • *args – Forwarded to pyqtgraph.GraphicsLayoutWidget.

  • **kwargs – Forwarded to pyqtgraph.GraphicsLayoutWidget.

  • Properties

  • ———-

  • framerate (int | None) – Maximum display frame rate [fps]. Setting this updates the throttle interval.

  • source (QVideoSource) – The video source. Setting this connects the source to the display.

  • fps (float | None) – Frame rate of the connected source [fps]. None when no source is connected. Read-only.

  • composite (bool) – Controls what newFrame emits. When False (default), newFrame carries the filtered video frame. When True, it carries the rendered ViewBox scene (video + overlays) as an (H, W, 4) RGBA uint8 array.

  • colormap (str | None) – Colormap name for false-color display of grayscale frames. Accepts any matplotlib colormap name (e.g. 'inferno', 'viridis') or a pyqtgraph built-in name. Set to None (default) to display in grayscale. Has no effect on color (3-channel) frames.

  • Signals

  • ——-

  • newFrame(numpy.ndarray) – Emitted after each displayed frame. Carries either the filtered video frame or the rendered composite scene, depending on composite.

newFrame#

str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL

types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.

Type:

pyqtSignal(*types, name

property source: QVideoSource | None#

The video source providing frames to display.

property framerate: int | None#

Maximum display frame rate [fps].

Accommodate high-speed cameras by throttling the rate at which frames are displayed. None for no throttling.

property colormap: str | None#

Colormap name for false-color display of grayscale frames.

Set to a colormap name (matplotlib or pyqtgraph built-in) to apply false-color mapping. Set to None to restore grayscale. Has no effect on color (3-channel) frames.

setImage(image)[source]#

Display a new video frame and emit newFrame.

Passes the frame through filter before display. If the throttle interval has not yet elapsed, the frame is buffered as the most recent pending frame; when the interval expires the buffered frame is displayed immediately so no extra latency accumulates.

newFrame is emitted with the filtered frame, or with the rendered composite scene when composite is True.

Parameters:

image (Image) – The frame to display.

Return type:

None

property fps: float | None#

Effective display frame rate [frames per second].

Returns framerate when display throttling is active, otherwise delegates to the source frame rate. This is the rate at which newFrame fires, and therefore the correct value to use when the screen is used as the source for a recorder. Returns None when no source is connected.

property composite: bool#

Emit the rendered scene via newFrame instead of the raw frame.

addOverlay(item)[source]#

Add a graphics item to the view

Register overlays for visibility control.

Parameters:

item (pyqtgraph.GraphicsObject) – The overlay item to add.

Return type:

None

removeOverlay(item)[source]#

Remove a previously added graphics item from the view.

Parameters:

item (pyqtgraph.GraphicsObject) – The overlay item to remove.

Return type:

None

property overlaysVisible: bool#

Whether any registered overlay is currently visible.

sizeHint()[source]#

Return the source frame size as the preferred widget size.

Return type:

QSize

hasHeightForWidth()[source]#

Return True once a video frame shape is known.

Return type:

bool

heightForWidth(width)[source]#

Return the height that preserves the source aspect ratio.

Return type:

int

updateShape(shape)[source]#

Resize the display to match the video frame dimensions.

Ignores shapes with zero width or height, which QCamera emits as a sentinel before width / height are registered as camera properties.

Parameters:

shape (QtCore.QSize) – New frame dimensions.

Return type:

None

resizeEvent(event)[source]#

Update the ViewBox range to match the video after the viewport is resized.

Return type:

None

classmethod example()[source]#

Demonstrate the video screen with a noise source.

Return type:

None

QFilterBank and VideoFilter#

VideoFilter is the base class for all image-processing filters. Its add / get interface separates frame ingestion from result production, supporting both stateless transforms (override get only) and stateful accumulators (override both add and get).

Stateless filters can also implement to_code(), which returns a FilterCode fragment describing the OpenCV and NumPy calls the filter makes. exportPipeline() collects these fragments to produce a standalone filter.py file. See Supporting pipeline export for how to add export support to a custom filter.

Composable pipeline of VideoFilter stages between a source and a display.

class QVideo.lib.QFilterBank.QFilterBank(parent=None)[source]#

Bases: QGroupBox

A vertical stack of QVideoFilter widgets.

Applies a sequence of video filters to each frame in order. Filters are added and removed at runtime via register() and deregister(), and may also be looked up by name from the QVideo.filters package using registerByName().

Parameters:

parent (QtWidgets.QWidget or None) – Parent widget.

property filters: list[QVideoFilter]#

Read-only view of the registered filters.

register(video_filter)[source]#

Add a filter to the end of the pipeline.

Parameters:

video_filter (QVideoFilter) – Filter widget to add.

Raises:

TypeError – If video_filter is not a QVideoFilter.

Return type:

None

deregister(video_filter)[source]#

Remove a filter from the pipeline.

Parameters:

video_filter (QVideoFilter) – Filter widget to remove.

Raises:

ValueError – If video_filter is not currently registered.

Return type:

None

registerByName(name)[source]#

Instantiate a filter by class name and add it to the pipeline.

Looks up name in the QVideo.filters package and registers an instance if found.

Parameters:

name (str) – Name of a QVideoFilter subclass exported by QVideo.filters.

Raises:

ValueError – If name is not found in QVideo.filters or does not refer to a QVideoFilter subclass.

Return type:

None

Base classes for image-processing filters in the QVideo filter pipeline.

class QVideo.lib.QVideoFilter.FilterCode(imports, lines, comment='')[source]#

Bases: object

Code fragment emitted by a filter’s to_code() method.

imports#

Complete import lines required by lines, e.g. 'import cv2'.

Type:

frozenset[str]

lines#

Source lines (no leading indentation) that implement one filter step. The variable image holds the current frame on entry and must hold the result on exit.

Type:

list[str]

comment#

Optional one-line description included as a comment above the generated code block.

Type:

str

imports: frozenset[str]#
lines: list[str]#
comment: str = ''#
class QVideo.lib.QVideoFilter.VideoFilter[source]#

Bases: QObject

Base class for video filters.

Provides a two-stage add/get interface so that subclasses can accumulate state across frames (e.g. running averages) before returning a result. The default implementation is a passthrough: add stores the frame and get returns it unchanged.

The __call__() operator chains add() and get() so that filters can be used as plain callables.

data: ndarray[tuple[Any, ...], dtype[uint8]] | None#
add(data)[source]#

Incorporate a new frame into the filter state.

Parameters:

data (Image) – Input frame.

Return type:

None

get()[source]#

Return the current filter output.

Return type:

ndarray[tuple[Any, ...], dtype[ubyte]] | None

Returns:

Image – Filtered frame.

Raises:

RuntimeError – If called before the first add().

shutdown()[source]#

Release background resources held by this filter.

Called by the pipeline when the filter is removed. The default is a no-op; subclasses that own background threads override this.

Return type:

None

to_code()[source]#

Return a FilterCode fragment for pipeline export.

Stateless filters implement this to enable exportPipeline(). Stateful filters (those that accumulate state across frames) return None to indicate they cannot be expressed as a single-frame pure function.

Return type:

FilterCode | None

Returns:

FilterCode or None – Code fragment, or None if export is not supported.

class QVideo.lib.QVideoFilter.QVideoFilter(parent, title, videoFilter)[source]#

Bases: QGroupBox

Widget wrapper for a VideoFilter with an enable checkbox.

Displays the filter as a checkable QGroupBox. When checked the filter is applied to incoming frames; when unchecked frames pass through unchanged.

Subclasses can extend the UI by overriding _setupUi(). The override should call super()._setupUi() first, then add widgets to self._layout.

Subclasses should set display_name to a short human-readable label. QFilterRack uses this to populate the “Add filter…” picker.

Parameters:
  • parent (QtWidgets.QWidget) – Parent widget.

  • title (str) – Label displayed in the group box border.

  • videoFilter (VideoFilter) – The filter to apply when enabled.

  • Class Attributes

  • —————-

  • display_name (str) – Human-readable name shown in the filter picker. Empty string means the filter will not appear in the picker.

  • display_category (str) – Category label used to group filters in the picker tree. Defaults to 'Other' in the picker when empty.

display_name: str = ''#
display_category: str = ''#
property filter: VideoFilter#

The VideoFilter applied when this widget is enabled.

classmethod example()[source]#

Demonstrate the filter widget.

Intended to be called on a concrete subclass that supplies its own __init__ defaults, not on QVideoFilter directly.

Return type:

None

AsyncVideoFilter#

AsyncVideoFilter is a base class for filters that run heavy computation in a background QThread so the GUI remains responsive even when inference is slower than the camera frame rate. Frames are dropped rather than queued when the worker is busy, preventing latency build-up.

Subclasses override process() (called in the background thread) and inherit add() / get() / __call__() from the base.

Async VideoFilter base for computationally expensive operations.

class QVideo.lib.AsyncVideoFilter.AsyncVideoFilter[source]#

Bases: VideoFilter

VideoFilter base for computationally expensive operations.

Runs process() in a dedicated background QThread so that heavy computation does not block the GUI event loop. The standard add() / get() interface is preserved with two behavioural differences:

  • Drop-frame strategy: add() submits a frame to the worker only when the worker is idle. If the worker is still processing the previous frame the incoming frame is discarded rather than queued, preventing unbounded latency build-up.

  • Cached result: get() returns the result of the last completed process() call. Before any result is ready it returns the raw input frame as a passthrough so the pipeline always has something to display.

Subclasses override process() instead of add() / get(). process() runs on the worker thread; it may read instance attributes freely (the GIL makes Python reads safe) but must not write to them.

Parameters:
  • None. Subclass constructors should call ``super().__init__()``

  • after initialising any attributes that :meth:`process` will read,

  • so the worker thread starts with a fully initialised object.

process(image)[source]#

Perform the heavy computation on image.

Called in the background thread. The default implementation is a passthrough; subclasses should override this method.

Parameters:

image (Image) – Input frame.

Return type:

ndarray[tuple[Any, ...], dtype[ubyte]]

Returns:

Image – Processed frame.

add(image)[source]#

Cache image and submit it to the worker if idle.

If the worker is busy the frame is dropped to prevent unbounded queue growth.

Parameters:

image (Image) – Input frame.

Return type:

None

get()[source]#

Return the most recently processed frame.

Returns the cached result of the last completed process() call. If no result is available yet (before the first process() completes), returns the raw input frame so the pipeline has something to display immediately.

Return type:

ndarray[tuple[Any, ...], dtype[ubyte]] | None

Returns:

Image or None – Processed frame, raw input frame, or None if add() has never been called.

shutdown()[source]#

Stop the background thread synchronously.

Called by the pipeline when this filter is removed. Safe to call multiple times.

Return type:

None

QFilterRack#

QFilterRack is a dynamic, user-editable alternative to QFilterBank. It wraps each filter in a slot that carries a ⋮ drag handle for reordering and a × button for removal. Set editable to False to hide all editing controls while keeping the pipeline callable.

The toolbar provides two buttons:

Add filter…

Opens a tree dialog listing all QVideoFilter subclasses exported by QVideo.filters, grouped by their display_category class attribute. Category headers are not selectable; clicking a leaf item and pressing OK (or double-clicking it) adds the filter to the rack. Filters without a display_category appear under Other.

Export…

Saves the current pipeline as a standalone Python source file. Only enabled (checked) filters are included. Each filter’s to_code() method provides the code fragment and import set; the rack assembles them into a module with a filter(image: np.ndarray) -> np.ndarray function. Filters that return None from to_code — typically stateful accumulators such as ForegroundEstimator — are skipped and noted in a comment. The generated file is valid, immediately importable Python.

A typical exported file looks like this:

'''Image-processing pipeline generated by QVideo.'''

import cv2
import numpy as np


def filter(image: np.ndarray) -> np.ndarray:
    # Gaussian smoothing, k=5
    image = cv2.GaussianBlur(image, (5, 5), 0)

    # Otsu threshold
    if image.ndim == 3:
        image = image.mean(axis=2).astype(np.uint8)
    image = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

    return image

Dynamic, reorderable pipeline of QVideoFilter widgets.

class QVideo.lib.QFilterRack.QFilterRack(parent=None, editable=True)[source]#

Bases: QWidget

A dynamic, reorderable pipeline of QVideoFilter widgets.

Filters are added interactively via an “Add filter…” toolbar button or programmatically via add() / addByName(). Each slot carries a × button to remove the filter and, when editable is True, a ⋮ drag handle to reorder it. The rack applies each filter in pipeline order, honoring each widget’s own enabled checkbox.

Unlike QFilterBank, which is configured programmatically and holds a fixed set of filters, QFilterRack is designed for interactive use where the pipeline should be discoverable and adjustable at runtime.

Parameters:
  • parent (QtWidgets.QWidget or None) – Parent widget. Default: None.

  • editable (bool) – If False, the toolbar, drag handles, and close buttons are all hidden. Default: True.

property filters: list[QVideoFilter]#

Read-only list of registered filter widgets in pipeline order.

property editable: bool#

whether the user can add, remove, or reorder filters.

Type:

bool

add(video_filter)[source]#

Add a filter widget to the end of the rack.

Parameters:

video_filter (QVideoFilter) – Filter widget to add.

Raises:

TypeError – If video_filter is not a QVideoFilter instance.

Return type:

None

addByName(name)[source]#

Instantiate a filter by display name and add it to the rack.

Parameters:

name (str) – display_name of the filter to add.

Raises:

ValueError – If name does not match any registered filter.

Return type:

None

classmethod availableFilters()[source]#

Return display names of all available filters, sorted.

Return type:

list[str]

Returns:

list[str] – Sorted list of display_name values for every exported filter with a non-empty display name.

exportPipeline()[source]#

Generate Python source that implements the current enabled pipeline.

Each enabled filter whose to_code() returns a FilterCode contributes one code block to the generated function. Filters that are unchecked or whose to_code returns None are silently skipped with a comment.

Return type:

str

Returns:

str – Source of a filter.py module defining filter(image: np.ndarray) -> np.ndarray.

classmethod example()[source]#

Display an empty, editable filter rack.

Return type:

None

Camera chooser#

Command-line camera selection utility for QVideo applications.

QVideo.lib.chooser.camera_parser(parser=None)[source]#

Returns a command-line argument parser with camera selection options.

Adds a mutually exclusive group of camera flags and an optional positional cameraID argument to the parser. If the parser already defines any of these arguments, they are left as-is.

Parameters:

parser (ArgumentParser | None) – An optional ArgumentParser to extend with camera options. If None, a new ArgumentParser is created.

Return type:

ArgumentParser

Returns:

ArgumentParser

Parser with mutually exclusive flags:

-b -> Basler (pylon)
-c -> OpenCV
-f -> Flir
-i -> IDS Imaging
-m -> MATRIX VISION mvGenTLProducer (universal GenICam)
-p -> Raspberry Pi camera module
-v -> Allied Vision VimbaX

The flag can be followed by an optional positional cameraID argument.

QVideo.lib.chooser.choose_camera(parser=None)[source]#

Chooses and returns a camera tree based on command-line arguments.

Tries to import and instantiate the camera backend selected by the command-line flags. Falls back to QNoiseTree if the requested backend cannot be imported or instantiated.

Parameters:

parser (ArgumentParser | None) – An optional ArgumentParser to parse command-line arguments. If provided, camera options will be added to it. If None, a new ArgumentParser is created.

Return type:

QCameraTree

Returns:

QCameraTree – The chosen camera tree widget.

QVideoReader#

Abstract base class for video file readers.

class QVideo.lib.QVideoReader.QVideoReader(filename)[source]#

Bases: QObject

Abstract base class for video-file readers.

Provides a unified interface for reading frames from a video file, including rate-limited frame delivery and random access via seek(). Pause/resume control is the responsibility of the enclosing QVideoSource.

Subclasses implement _initialize(), _deinitialize(), read(), and the abstract properties fps, width, height, framenumber, and length, as well as the seek() method.

Parameters:
  • filename (str) – Path to the video file to open.

  • Signals

  • ——-

  • shapeChanged(QSize) – Emitted when the file is opened and the frame dimensions are known.

Notes

saferead() paces frame delivery by sleeping delay milliseconds between reads so that callers receive frames at approximately the correct playback rate.

shapeChanged#

Emitted when the file is opened and the frame dimensions are known.

open()[source]#

Open the video file.

Calls _initialize() only if not already open. Emits shapeChanged on success and logs a warning on failure.

Return type:

QVideoReader

Returns:

QVideoReaderself, to allow chaining.

close()[source]#

Close the video file.

Safe to call on an already-closed reader.

Return type:

None

isOpen()[source]#

Return whether the file is currently open.

Return type:

bool

abstractmethod read()[source]#

Read the next frame from the video file.

Return type:

tuple[bool, ndarray[tuple[Any, ...], dtype[ubyte]] | None]

Returns:

tuple[bool, ndarray or None](True, frame) on success, (False, None) at end-of-file or on error.

saferead()[source]#

Read one frame, pacing delivery to the file’s native frame rate.

Blocks for delay milliseconds before each read so that callers receive frames at approximately the correct playback rate.

Return type:

tuple[bool, ndarray[tuple[Any, ...], dtype[ubyte]] | None]

Returns:

tuple[bool, ndarray or None] – Result of read().

abstract property fps: float#

Frame rate of the video file [frames per second].

abstract property length: int#

Total number of frames in the video file.

abstract property framenumber: int#

Current frame index (zero-based).

abstract property width: int#

Frame width in pixels.

abstract property height: int#

Frame height in pixels.

property delay: int#

Inter-frame delay in milliseconds, derived from fps.

property shape: QSize#

Frame dimensions as QSize(width, height).

abstractmethod seek(framenumber)[source]#

Seek to the specified frame.

Parameters:

framenumber (int) – Target frame index (zero-based).

Return type:

None

rewind()[source]#

Seek to the first frame.

Return type:

None

static examplevideo()[source]#

Return the path to the bundled example video file.

Return type:

str

classmethod example()[source]#

Print file metadata and read a few frames.

Return type:

None

QVideoWriter#

Abstract base class for video file writers.

class QVideo.lib.QVideoWriter.QVideoWriter(filename, fps=24, nframes=10000, nskip=1, **kwargs)[source]#

Bases: QObject

Abstract base class for saving videos to files

Parameters:
  • filename (str) – The output video filename.

  • fps (int) – The frame rate of the output video [frames per second].

  • nframes (int) – The maximum number of frames to write.

  • nskip (int) – The number of frames to skip between writes.

  • kwargs (dict) – Additional keyword arguments to pass to the QObject constructor.

Returns:

  • QVideoWriter (QObject) – The video writer object.

  • Signals

  • ——-

  • frameNumber(int) – Emitted when a new frame is written, providing the current frame number.

  • finished() – Emitted when the video writing is finished.

  • Slots

  • —–

  • write(frame (Image) -> None) – Write a video frame to the file.

  • close() -> None – Close the video file.

  • Properties

  • ———-

  • filename (str) – The output video filename.

  • fps (int) – The frame rate of the output video [frames per second].

  • nskip (int) – The number of frames to skip between writes.

  • nframes (int) – The maximum number of frames to write.

  • Abstract Methods

  • —————-

  • open(frame (Image) -> bool) – Open the video file for writing.

  • isOpen() -> bool – Check if the video file is open.

  • _write(frame (Image) -> None) – Write a video frame to the file.

  • close() -> None – Close the video file.

frameNumber#

Emitted when a new frame is written, with the current frame number.

finished#

Emitted when video writing is complete.

abstractmethod open(frame)[source]#

Open the output file using frame dimensions from the first frame.

Called automatically by write() on the first frame.

Parameters:

frame (Image) – The first video frame; dimensions and color mode are read from this array.

Return type:

bool

Returns:

boolTrue if the file was opened successfully.

abstractmethod isOpen()[source]#

Return True if the output file is currently open.

Return type:

bool

write(frame)[source]#

Write a video frame.

Opens the file on the first call, skips frames according to nskip, and emits finished when nframes have been written or when the file cannot be opened.

Parameters:

frame (Image) – Video frame to write.

Return type:

None

abstractmethod close()[source]#
Return type:

None

QFPSMeter#

Sliding-window frame-rate meter emitted as a Qt signal.

class QVideo.lib.QFPSMeter.QFPSMeter(window=10)[source]#

Bases: QObject

Measures frame rate over a sliding window of frame timestamps.

On every tick() a timestamp is appended to a circular buffer of length window. Once the buffer is full, FPS is computed from the span of the buffered timestamps and fpsReady is emitted. Because the buffer slides forward one frame at a time, the reading updates on every tick rather than in discrete batches.

Parameters:
  • window (int) – Number of timestamps retained. Larger values give smoother estimates at the cost of slower response to rate changes. Values less than 2 are clamped to 2.

  • Signals

  • ——-

  • fpsReady(float) – Emitted on every tick() once the buffer is full.

  • Properties

  • ———-

  • value (float) – Most recently measured frame rate [frames per second]. Zero until the buffer fills for the first time.

  • Slots

  • —–

  • tick() -> None – Record one frame arrival and update the FPS estimate.

  • reset() -> None – Clear the timestamp buffer and cached value.

fpsReady#

Emitted on every tick() once the buffer is full.

tick()[source]#

Record one frame arrival and update the FPS estimate.

Appends the current time to the circular buffer. Once the buffer holds window timestamps, computes:

fps = (window - 1) / (newest_timestamp - oldest_timestamp)

and emits fpsReady.

Return type:

None

reset()[source]#

Reset the meter to its initial state.

Clears the timestamp buffer and cached value so that the next tick() begins a fresh measurement. Useful when the video source stops and restarts.

Return type:

None

property value: float#

Most recently measured frame rate [frames per second].

QSnapshot#

QSnapshot captures the most recent frame from any newFrame signal and saves it to disk on demand. It has no visual presence — drop it into any application as a QObject and two keyboard shortcuts become available:

  • Ctrl+Shift+S — save a timestamped PNG to the user’s home directory

  • Ctrl+Shift+Alt+S — open a file dialog pre-filled with the same name

The source connected to newFrame() determines what is captured: raw frames (QVideoSource.newFrame), filtered frames (QVideoScreen.newFrame), or the fully rendered scene with overlays (QVideoScreen.newFrame with composite=True).

Still-frame capture from a live video stream.

class QVideo.lib.QSnapshot.QSnapshot(parent, key='Ctrl+Shift+S', key_as='Ctrl+Shift+Alt+S')[source]#

Bases: QObject

Save still frames from a live video stream.

Connect any signal that emits an Image to newFrame() so that the most recent frame is always cached. Call snap() (or press the hotkey) to write the cached frame to disk. Call snapAs() to choose the save path via a file dialog.

The source determines what is captured:

  • QVideoSource.newFrame — raw camera frames, no filters

  • QVideoScreen.newFrame — post-filter frames

  • QVideoScreen.newFrame with composite=True — filtered + overlaid

Frames are saved as-is; no channel reordering is applied. For cameras that deliver BGR data (e.g. OpenCV), the saved PNG will have swapped red and blue channels compared to the on-screen display.

Parameters:
  • parent (QWidget) – Parent widget. Shortcuts are registered on this widget.

  • key (str) – Keyboard shortcut that triggers snap() (auto-timestamp save). Default: 'Ctrl+Shift+S'.

  • key_as (str) – Keyboard shortcut that triggers snapAs() (file-dialog save). Default: 'Ctrl+Shift+Alt+S'.

  • Slots

  • —–

  • newFrame(Image) – Cache the most recent frame.

  • snap() – Save the cached frame to a timestamped PNG in the user’s home directory.

  • snapAs() – Prompt for a filename pre-filled with the auto-generated name, then save.

newFrame(frame)[source]#

Cache the most recent frame.

Return type:

None

snap()[source]#

Save the cached frame to a timestamped PNG in the home directory.

Return type:

None

snapAs()[source]#

Prompt for a filename pre-filled with the auto-generated name, then save.

Return type:

None

classmethod example()[source]#

Demonstrate QSnapshot with a noise source.

Return type:

None

QListCameras#

Abstract base for QComboBox widgets that enumerate available cameras.

class QVideo.lib.QListCameras.QListCameras(*args, **kwargs)[source]#

Bases: ComboBox

Base class for a combo box that lists available cameras.

Subclasses should override _listCameras() to populate the combo box with available camera entries, and _model() to return the camera class associated with entries.

Inherits#

pyqtgraph.ComboBox

Signals#

cameraSelected(model: type, index: int)

Emitted when a camera entry is selected. model is the camera class returned by _model() and index is the device index stored as the item’s data.

refresh()[source]#

Clear and repopulate the list of available cameras.

cameraSelected#

Emitted when a camera entry is selected.

refresh()[source]#

Clear and repopulate the list of available cameras.

Return type:

None

cameraSelection(row)[source]#

Emit cameraSelected for the current combo box entry.

The placeholder “Select Camera” entry (row 0) and an empty combo box (row -1) are ignored and do not emit the signal.

Parameters:

row (int) – The combo box row index of the newly selected item.

Return type:

None

classmethod example()[source]#

QCamcorder#

Composite camcorder widget combining a video screen, camera controls, and DVR.

Run directly to launch a full camcorder application with camera selection:

python -m QVideo.QCamcorder [-b|-c|-f|-i|-m|-p|-r|-v] [cameraID]

Camera flags (mutually exclusive):

-b [cameraID]   Basler camera (requires pylon SDK)
-c [cameraID]   OpenCV camera
-f [cameraID]   FLIR camera (requires Spinnaker SDK)
-i [cameraID]   IDS Imaging camera (requires IDS peak SDK)
-m [cameraID]   MATRIX VISION mvGenTLProducer (universal GenICam, not FLIR)
-p [cameraID]   Raspberry Pi camera module (requires picamera2)
-r [cameraID]   OpenCV camera with resolution drop-down selector
-v [cameraID]   Allied Vision VimbaX camera
-h              Show help and exit

If no flag is given, a noise camera is used as a fallback.

class QVideo.QCamcorder.QCamcorder(cameraWidget, *args, **kwargs)[source]#

Bases: QWidget

A widget combining a video screen, camera controls, and DVR.

Lays out a QVideoScreen alongside a QDVRWidget and an arbitrary QCameraTree control panel. Live frames from the camera source are routed to the screen; when the DVR starts playback the screen is switched to the playback stream and the camera controls are disabled until playback ends.

A QSnapshot is wired to the screen’s newFrame signal, enabling still-frame capture via two hotkeys:

  • Ctrl+Shift+S — save a timestamped PNG to the home directory

  • Ctrl+Shift+Alt+S — open a file dialog pre-filled with the same name

Parameters:
  • cameraWidget (QCameraTree) – Camera control tree to embed in the controls panel.

  • *args – Additional positional arguments forwarded to QWidget.

  • **kwargs – Additional keyword arguments forwarded to QWidget.

closeEvent(event)[source]#

Stop the camera source when the widget is closed.

Return type:

None

dvrPlayback(playback)[source]#

Switch the screen source between live camera and DVR playback.

Connected to playing. When playback starts the camera source is disconnected from the screen and the DVR’s newFrame signal is connected instead; the camera controls are disabled. When playback ends the connections are reversed and the controls are re-enabled.

Parameters:

playback (bool) – True when DVR playback begins, False when it ends.

Return type:

None

property source: QVideoSource#

The QVideoSource from the camera widget.