meyelens.camera
camera.py
A small OpenCV-based camera wrapper with:
Optional calibration loading from a TOML file.
Optional frame undistortion (requires calibration).
Fixed resolution / framerate configuration.
Auto-exposure or manual exposure control.
Interactive ROI selection and optional cropping.
A simple preview window for quick diagnostics.
This module is written to be friendly to Sphinx autodoc. If you use NumPy-style
docstrings, enable sphinx.ext.napoleon in your conf.py.
Notes
OpenCV camera properties (auto-exposure, exposure units, gain, FPS) can behave differently across operating systems, backends (DirectShow/MSMF/V4L2), and camera drivers. The setters in this class attempt to apply requested values, but your hardware may ignore some properties.
Dependencies
opencv-python
numpy
toml
Example
>>> from camera import Camera
>>> with Camera(camera_index=0, resolution=(640, 480), auto_exposure=True) as cam:
... frame = cam.get_frame()
... if frame is not None:
... cam.show(frame, "One frame")
... cv2.waitKey(0)
... cv2.destroyAllWindows()
- class meyelens.camera.Camera(camera_index: int = 0, calibration_file: str | Path = 'camera_calibration.toml', undistort: bool = False, exposure: float = 0, framerate: float = 30, resolution: Tuple[int, int] = (640, 480), auto_exposure: bool = True, crop: Tuple[int, int, int, int] | None = None)[source]
Bases:
objectHigh-level wrapper around
cv2.VideoCapture.- Parameters:
camera_index – Index passed to
cv2.VideoCapture. Common values are0or1. Some systems support special values (e.g.-1) but this is backend-dependent.calibration_file – Path to a TOML file containing camera calibration parameters. Expected keys: -
camera_matrix: 3x3 array-like -distortion_coefficients: array-like (e.g. 1x5, 1x8)undistort – If
Trueand calibration parameters are available, frames are undistorted on read.exposure – Manual exposure value passed to OpenCV when auto-exposure is disabled. The numeric meaning is backend/driver-dependent.
framerate – Requested camera FPS. Note: many cameras ignore this, or it depends on resolution/exposure.
resolution – Requested camera resolution as
(width, height).auto_exposure – If
Trueattempt to enable auto-exposure; ifFalseattempt to disable auto-exposure and apply manual exposure/gain settings.crop – Optional crop rectangle stored as
(top, left, height, width). If provided, frames returned byget_frame()are cropped accordingly.
- cap
The underlying
cv2.VideoCapture.
- camera_matrix
Loaded camera intrinsic matrix (or
Noneif not available).
- dist_coeffs
Loaded distortion coefficients (or
Noneif not available).
- crop
Crop rectangle in
(top, left, height, width)format, orNone.
- Raises:
RuntimeError – If the camera cannot be opened.
- load_calibration(calibration_file: str | Path) None[source]
Load camera calibration from a TOML file.
- Parameters:
calibration_file – TOML file path. Must contain at least
camera_matrixanddistortion_coefficientskeys.
Notes
If loading fails for any reason, the camera continues operating without calibration.
- set_resolution(resolution: Tuple[int, int]) None[source]
Attempt to set the capture resolution.
- Parameters:
resolution –
(width, height).
- set_framerate(framerate: float) None[source]
Attempt to set the capture framerate.
- Parameters:
framerate – Requested FPS.
- set_auto_exposure(enabled: bool) None[source]
Attempt to enable/disable auto-exposure.
- Parameters:
enabled – If
True, attempt to enable auto-exposure. IfFalse, attempt to disable auto-exposure and apply manual exposure settings.
Notes
OpenCV uses different conventions depending on backend:
Some backends expect
CAP_PROP_AUTO_EXPOSUREto be 0.25 for manual and 0.75 for auto (common on V4L2).Others accept 0/1.
Here we try a reasonable approach while keeping original intent.
- set_exposure(exposure: float) bool[source]
Attempt to set manual exposure.
- Parameters:
exposure – Manual exposure value passed to OpenCV.
- Returns:
Trueif the camera is open and we attempted to set the property,Falseotherwise.- Return type:
bool
Notes
Many drivers require auto-exposure to be disabled for this to take effect.
- get_frame(flip_vertical: bool = True, apply_crop: bool = True) numpy.ndarray | None[source]
Capture a frame.
- Parameters:
flip_vertical – If
True, flip the frame vertically (OpenCV flipCode=0), matching the original behavior.apply_crop – If
Trueandcropis set, crop the returned frame.
- Returns:
BGR image (H x W x 3) if successful, otherwise
None.- Return type:
Optional[numpy.ndarray]
- static show(frame: numpy.ndarray, name: str = 'Frame') None[source]
Display a frame in an OpenCV window.
- Parameters:
frame – Frame to display.
name – Window name.
- wait_key(key: str = 'q', delay_ms: int = 1) bool[source]
Check whether a given key was pressed in the last OpenCV event loop iteration.
- Parameters:
key – Single character key to detect (e.g.
"q").delay_ms – Delay in milliseconds passed to
cv2.waitKey().
- Returns:
Trueif the key was pressed, elseFalse.- Return type:
bool
- preview(window_name: str = 'Camera Preview') None[source]
Open a live preview window with a framerate readout.
Controls
ESC: exit preview
‘o’: increase exposure by +1 (only meaningful if manual exposure is supported)
‘p’: decrease exposure by -1
- param window_name:
Name of the OpenCV window.
- close() None[source]
Release camera resources and close OpenCV windows.
Notes
Calling
cv2.destroyAllWindows()is global (it closes all OpenCV windows), so if you manage multiple windows externally you may prefer to destroy specific windows yourself.
- select_roi(window_name: str = 'Select ROI') None[source]
Interactively select a rectangular ROI and store it in
crop.Workflow
Drag with left mouse button to draw a rectangle.
Press ‘s’ to save the selection.
Press ‘r’ to reset the selection.
Press ESC to exit without changing
crop.
The selection is stored as
(top, left, height, width)and will be applied byget_frame()whenapply_crop=True.- param window_name:
OpenCV window name used for ROI selection.