Core library#
QCamera#
Abstract base class for all QVideo camera backends.
- class QVideo.lib.QCamera.QCamera(*args, **kwargs)[source]#
Bases:
QObjectAbstract 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(), andread(), then callregisterProperty()andregisterMethod()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
QCameraholds a single non-recursivemutex.set(),get(),execute(), andsaferead()all acquire it, so subclassread()implementations must not call back into any of those methods or a deadlock will result. Pause and resume control is the responsibility of the enclosingQVideoSource.- PropertyValue = bool | int | float | str#
- shapeChanged#
Emitted by subclasses when the image dimensions change.
- 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
_namebacking-attribute convention: the getter readsself._nameand the setter writesptype(value)back toself._name. Pass an explicit callable to override either, or passsetter=Noneto 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.
Nonemarks the property read-only. Defaults tolambda 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 asQCameraTree.**meta – Additional metadata (e.g.
minimum,maximum,step).
- Return type:
- open(*args, **kwargs)[source]#
Open the camera device.
Calls
_initialize()only if the device is not already open.- Return type:
- Returns:
QCamera –
self, to allow chaining.
- property settings: dict[str, bool | int | float | str]#
All registered property values as a name→value dict.
Uses registered getters directly to avoid emitting
propertyValuefor 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:
- get(key)[source]#
Return the current value of a registered property.
Emits
propertyValuewith the name and value.
- execute(key)[source]#
Call a registered method by name.
- Parameters:
key (str) – Method name.
- Return type:
- abstractmethod read()[source]#
Read one frame from the camera.
- Return type:
- Returns:
tuple[bool, Image or None] –
(True, frame)on success,(False, None)on failure.
Notes
Must not call
set(),get(),execute(), orsaferead()— those methods acquire the same non-recursive mutex thatsaferead()holds while invokingread().
- saferead()[source]#
Read one frame under the camera mutex.
Blocks any concurrent call to
set(),get(), orexecute()until the frame transfer completes.
- property shape: QSize#
Image dimensions as
QSize(width, height).Returns
QSize(0, 0)ifwidthorheightare not registered.
QVideoSource#
QThread wrapper that drives a QCamera and emits newFrame signals.
- class QVideo.lib.QVideoSource.QVideoSource(source)[source]#
Bases:
QThreadA 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).
- start() QVideoSource[source]#
Start the video source thread.
Notes
The source is moved to this thread via
moveToThreadso that its slots are delivered in the capture thread rather than the main thread. State variables_runningand_pausedare protected bymutex;waitconditionis used to block the capture loop while paused and to wake it onresume()orstop().- newFrame#
Emitted when a new video frame is available.
- property source: QCamera | QVideoReader#
The underlying QCamera or QVideoReader.
- 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 emittingnewFramefor each successful frame. The loop blocks whenpause()is called and resumes whenresume()orstop()is called.This method is invoked automatically by
start()in a new thread and should not be called directly in production code.- Return type:
- 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:
- Returns:
QVideoSource –
self, to allow chaining e.g.src = QVideoSource(cam).start().
- stop()[source]#
Stop the capture thread.
Sets
_runningtoFalseand wakes any thread blocked inpause(), so thatrun()exits cleanly at the next loop iteration.- Return type:
QCameraTree#
Auto-building pyqtgraph parameter tree for QCamera property inspection.
- class QVideo.lib.QCameraTree.QCameraTree(source, description=None, *args, **kwargs)[source]#
Bases:
ParameterTreeA parameter tree widget for controlling
QCameraproperties.Wraps a
QVideoSource(or a bareQCamera) and presents its settings as an editableParameterTree. 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
Nonea default description is generated fromsettings.*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.
- set(key, value)[source]#
Set a camera property and update the tree.
- Parameters:
key (str) – Property name.
value (QCamera.PropertyValue) – New value.
- Return type:
- property source: QVideoSource#
The underlying
QVideoSource.
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:
GraphicsLayoutWidgetVideo display widget.
Displays frames from a
QVideoSourcein real time, with optional frame-rate throttling and image filtering viaQFilterBank.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.
Nonemeans 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].
Nonewhen no source is connected. Read-only.composite (bool) – Controls what
newFrameemits. WhenFalse(default),newFramecarries the filtered video frame. WhenTrue, 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 toNone(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.
Nonefor 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
Noneto 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
filterbefore 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.newFrameis emitted with the filtered frame, or with the rendered composite scene whencompositeisTrue.- Parameters:
image (Image) – The frame to display.
- Return type:
- property fps: float | None#
Effective display frame rate [frames per second].
Returns
frameratewhen display throttling is active, otherwise delegates to the source frame rate. This is the rate at whichnewFramefires, and therefore the correct value to use when the screen is used as the source for a recorder. ReturnsNonewhen no source is connected.
- 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:
- removeOverlay(item)[source]#
Remove a previously added graphics item from the view.
- Parameters:
item (pyqtgraph.GraphicsObject) – The overlay item to remove.
- Return type:
- heightForWidth(width)[source]#
Return the height that preserves the source aspect ratio.
- Return type:
- updateShape(shape)[source]#
Resize the display to match the video frame dimensions.
Ignores shapes with zero width or height, which
QCameraemits as a sentinel beforewidth/heightare registered as camera properties.- Parameters:
shape (QtCore.QSize) – New frame dimensions.
- Return type:
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:
QGroupBoxA vertical stack of
QVideoFilterwidgets.Applies a sequence of video filters to each frame in order. Filters are added and removed at runtime via
register()andderegister(), and may also be looked up by name from theQVideo.filterspackage usingregisterByName().- Parameters:
parent (QtWidgets.QWidget or None) – Parent widget.
- property filters: list[QVideoFilter]#
Read-only view of the registered filters.
- 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:
- registerByName(name)[source]#
Instantiate a filter by class name and add it to the pipeline.
Looks up name in the
QVideo.filterspackage and registers an instance if found.- Parameters:
name (str) – Name of a
QVideoFiltersubclass exported byQVideo.filters.- Raises:
ValueError – If name is not found in
QVideo.filtersor does not refer to aQVideoFiltersubclass.- Return type:
Base classes for image-processing filters in the QVideo filter pipeline.
- class QVideo.lib.QVideoFilter.FilterCode(imports, lines, comment='')[source]#
Bases:
objectCode fragment emitted by a filter’s
to_code()method.- lines#
Source lines (no leading indentation) that implement one filter step. The variable
imageholds the current frame on entry and must hold the result on exit.
- comment#
Optional one-line description included as a comment above the generated code block.
- Type:
- class QVideo.lib.QVideoFilter.VideoFilter[source]#
Bases:
QObjectBase class for video filters.
Provides a two-stage
add/getinterface so that subclasses can accumulate state across frames (e.g. running averages) before returning a result. The default implementation is a passthrough:addstores the frame andgetreturns it unchanged.The
__call__()operator chainsadd()andget()so that filters can be used as plain callables.- add(data)[source]#
Incorporate a new frame into the filter state.
- Parameters:
data (Image) – Input frame.
- Return type:
- 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:
- to_code()[source]#
Return a
FilterCodefragment for pipeline export.Stateless filters implement this to enable
exportPipeline(). Stateful filters (those that accumulate state across frames) returnNoneto indicate they cannot be expressed as a single-frame pure function.- Return type:
- Returns:
FilterCode or None – Code fragment, or
Noneif export is not supported.
- class QVideo.lib.QVideoFilter.QVideoFilter(parent, title, videoFilter)[source]#
Bases:
QGroupBoxWidget wrapper for a
VideoFilterwith 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 callsuper()._setupUi()first, then add widgets toself._layout.Subclasses should set
display_nameto a short human-readable label.QFilterRackuses 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.
- property filter: VideoFilter#
The
VideoFilterapplied 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 onQVideoFilterdirectly.- Return type:
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:
VideoFilterVideoFilter base for computationally expensive operations.
Runs
process()in a dedicated backgroundQThreadso that heavy computation does not block the GUI event loop. The standardadd()/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 completedprocess()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 ofadd()/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.
- 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:
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
QVideoFiltersubclasses exported byQVideo.filters, grouped by theirdisplay_categoryclass 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 adisplay_categoryappear 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 afilter(image: np.ndarray) -> np.ndarrayfunction. Filters that returnNonefromto_code— typically stateful accumulators such asForegroundEstimator— 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:
QWidgetA dynamic, reorderable pipeline of
QVideoFilterwidgets.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, wheneditableisTrue, 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,QFilterRackis 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.
- 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
QVideoFilterinstance.- Return type:
- addByName(name)[source]#
Instantiate a filter by display name and add it to the rack.
- Parameters:
name (str) –
display_nameof the filter to add.- Raises:
ValueError – If name does not match any registered filter.
- Return type:
- classmethod availableFilters()[source]#
Return display names of all available filters, sorted.
- Return type:
- Returns:
list[str] – Sorted list of
display_namevalues 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 aFilterCodecontributes one code block to the generated function. Filters that are unchecked or whoseto_codereturnsNoneare silently skipped with a comment.- Return type:
- Returns:
str – Source of a
filter.pymodule definingfilter(image: np.ndarray) -> np.ndarray.
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:
- 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
QNoiseTreeif 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:
- Returns:
QCameraTree – The chosen camera tree widget.
QVideoReader#
Abstract base class for video file readers.
- class QVideo.lib.QVideoReader.QVideoReader(filename)[source]#
Bases:
QObjectAbstract 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 enclosingQVideoSource.Subclasses implement
_initialize(),_deinitialize(),read(), and the abstract propertiesfps,width,height,framenumber, andlength, as well as theseek()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 sleepingdelaymilliseconds 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. EmitsshapeChangedon success and logs a warning on failure.- Return type:
- Returns:
QVideoReader –
self, to allow chaining.
- saferead()[source]#
Read one frame, pacing delivery to the file’s native frame rate.
Blocks for
delaymilliseconds before each read so that callers receive frames at approximately the correct playback rate.
Current frame index (zero-based).
- property shape: QSize#
Frame dimensions as
QSize(width, height).
QVideoWriter#
Abstract base class for video file writers.
- class QVideo.lib.QVideoWriter.QVideoWriter(filename, fps=24, nframes=10000, nskip=1, **kwargs)[source]#
Bases:
QObjectAbstract 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:
- Returns:
bool –
Trueif the file was opened successfully.
QFPSMeter#
Sliding-window frame-rate meter emitted as a Qt signal.
- class QVideo.lib.QFPSMeter.QFPSMeter(window=10)[source]#
Bases:
QObjectMeasures 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 andfpsReadyis 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.
- 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:
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 directoryCtrl+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:
QObjectSave still frames from a live video stream.
Connect any signal that emits an
ImagetonewFrame()so that the most recent frame is always cached. Callsnap()(or press the hotkey) to write the cached frame to disk. CallsnapAs()to choose the save path via a file dialog.The source determines what is captured:
QVideoSource.newFrame— raw camera frames, no filtersQVideoScreen.newFrame— post-filter framesQVideoScreen.newFramewithcomposite=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.
QListCameras#
Abstract base for QComboBox widgets that enumerate available cameras.
- class QVideo.lib.QListCameras.QListCameras(*args, **kwargs)[source]#
Bases:
ComboBoxBase 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.
modelis the camera class returned by_model()andindexis the device index stored as the item’s data.
- cameraSelected#
Emitted when a camera entry is selected.
- cameraSelection(row)[source]#
Emit
cameraSelectedfor 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:
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:
QWidgetA widget combining a video screen, camera controls, and DVR.
Lays out a
QVideoScreenalongside aQDVRWidgetand an arbitraryQCameraTreecontrol 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
QSnapshotis wired to the screen’snewFramesignal, enabling still-frame capture via two hotkeys:Ctrl+Shift+S— save a timestamped PNG to the home directoryCtrl+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.
- 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’snewFramesignal is connected instead; the camera controls are disabled. When playback ends the connections are reversed and the controls are re-enabled.- Parameters:
playback (bool) –
Truewhen DVR playback begins,Falsewhen it ends.- Return type:
- property source: QVideoSource#
The
QVideoSourcefrom the camera widget.