Catalog PyPI
PACKAGE EXPLORERView in registry

acmenra-cv

PyPI

Production-ready, backend-agnostic computer vision utilities for multi-object tracking and spatial reasoning

acmenra-cv
Versions collected1
Direct dependencies7From release 0.3.3.1
Last observed20 Oct, 18:18 UTC

README

Version 0.3.3.1 documentation

🚀 acmenra-cv

Production-ready, backend-agnostic computer vision utilities for ADAS, multi-object tracking, and embedded vision systems

PyPI Python License

# Install core library (lightweight, no heavy ML dependencies)
pip install acmenra-cv

# OR install with YOLO support (includes ultralytics, torch, etc.)
pip install "acmenra-cv[yolo]"

📦 Overview

acmenra-cv is a high-performance, type-safe computer vision library engineered for real-time applications on resource-constrained embedded systems (Raspberry Pi, Jetson, NPU, etc.). Built following Clean Architecture principles, it provides a strict, domain-agnostic interface for spatial reasoning and tracking, while delegating specific model inference to optional plugin packages (like acmenra-yolo).

ModulePurposeKey Features
instanceSpatial primitives for detection outputsNormalized coordinates, strict validation, immutable transformations, TaskType & DeviceType enums
inferenceBackend-agnostic result containerCollection-like API, timing metrics, absolute dimensions, JSON serialization
trackerMulti-object tracking with trajectoriesPersistent IDs, configurable history, clean separation from inference
renderType-safe visualization layerAlpha-blended overlays, embedded optimizations, graceful degradation
utilsFoundational CV helpersGrid-sampled illumination estimation, adaptive preprocessing

All spatial components operate in normalized coordinate space [0.0, 1.0] by default, ensuring resolution independence. The inference module stores absolute integer dimensions to serve as the ground truth for coordinate denormalization.


✨ Key Features

🔹 Unified & Backend-Agnostic Architecture

  • Strict type & range validation ([0.0, 1.0] with safe() clamping factory)
  • Seamless plugin integration (e.g., acmenra-yolo for Ultralytics, future OpenVINO/TensorRT plugins)
  • Immutable geometric transformations (scale, translate, smooth)
  • Full type safety with IDE autocomplete and consistent API across all primitives

🔹 Robust Result Handling

  • Universal Result container with collection-like API (len(), iteration, indexing)
  • Execution timing metrics with partial measurement support (None for unprofiled stages)
  • Absolute pixel dimensions (width, height, depth as int) for accurate denormalization
  • Full JSON serialization (to_dict/from_dict) optimized for Outbox persistence and analytics

🔹 Embedded-Ready Performance

  • Zero-crash OpenCV integration with @validate_frame decorator
  • Global show=False toggle to bypass all rendering for headless/embedded deployments
  • Memory-efficient trajectory queues with O(1) incremental average calculation
  • Grid-sampled utilities delivering 10-50× speedup on resource-constrained devices

🔹 ADAS & Safety-Critical Design

  • Trajectory history management for zone crossing and collision detection
  • Temporal metadata (TimedPoint) for velocity/direction estimation
  • Configurable thresholds (conf, iou, max_length) for dynamic adaptation
  • Graceful degradation on invalid inputs — no exceptions, just safe fallbacks

🧩 Module Documentation

🔷 instance — Spatial Primitives

Validated geometric containers for detection outputs

Classes

Point — Validated 3D normalized coordinates

  • __init__(): Initializes with X, Y, Z. Validates float type and [0.0, 1.0] range.
  • X, Y, Z: Properties with strict type and range validation.
  • get_distance(): Euclidean distance to another point (includes Z).
  • scale(), translate(): Immutable transformations returning new instances.
  • safe(): Class method factory with coordinate clamping — no exceptions.

Box — Axis-aligned 3D bounding box

  • __init__(): Six boundaries (left, right, top, bottom, front, back).
  • center, bottom_center: Computed properties for tracking.
  • width, height, depth: Dimension properties.
  • get_area(), get_volume(): Geometric calculations.
  • to_absolute_array(): Converts to pixel corners for OpenCV.
  • YOLO format conversions: to_xyxyn(), to_xywhn(), to_xyzxyzn(), to_xyzwhdn().

Polygon — Segmentation mask container

  • from_xyn(): Class factory from YOLO masks.xyn.
  • smooth(): Vertex smoothing via moving average.
  • get_area(): Shoelace formula for normalized area.
  • __getitem__(): Supports slicing — returns new Polygon.
  • __len__(), __iter__(): Collection-like behavior.

Obb — Oriented (rotated) bounding box

  • from_xywhrn(): Class factory from YOLO OBB format.
  • yaw, pitch, roll: Rotation angles with tolerance-based equality.
  • width, height, depth: Dimension properties.
  • Full 3D support with canonical state management.

Instance — Unified detection container

  • Combines id, class_id, label, conf, box, polygon, obb.
  • Important: Instance.label holds a specific enum member (e.g., CocoClass.PERSON), while Backend.category holds the enum class.
  • Strict validation on all properties.

TaskType & DeviceType — Enumerations

  • TaskType: DETECT, SEGMENT, CLASSIFY, POSE, OBB, TRACK, etc.
  • DeviceType: AUTO, CPU, CUDA, MPS, NPU, TPU, TENSORRT, etc.

🔷 inference — Result Container & Contracts

Backend-agnostic output format with collection-like API

Classes

Backend — Abstract base class

  • Defines the contract for all inference backends (predict, track).
  • Enforces unified interface for detection and optional tracking.
  • Properties: device, category (Enum class), task_type, threshold.

Timing — Pipeline stage duration tracking

  • __init__(): Initializes with preprocess, prediction, postprocess (all Optional[float]).
  • total: Computed property returning sum of non-None stages.
  • to_dict(), from_dict(): Full JSON serialization with None support.

Result — Universal result container

  • __init__(): Accepts instances, timing, width, height, depth, device, category.
  • __len__(): Returns number of detected instances.
  • __iter__(): Enables for instance in result: iteration.
  • __getitem__(): Supports result[0] and result[-1] indexing.
  • width, height, depth: Absolute pixel dimensions (int, strictly > 0).

💡 Note: Concrete backend implementations (like YOLOBackend) are provided by separate plugin packages such as acmenra-yolo.


🔷 tracker — Multi-Object Tracking

Persistent IDs, trajectory management, ADAS integration

Classes

Tracker — Main tracking engine

  • __init__(): Configurable with id, backend (Backend instance), and max_length.
  • track(): Main entry point — processes frame and returns List[TrackedObject] with persistent IDs.
  • remove(), clear(): State management for track lifecycle.

TrackedObject — Single tracked entity

  • id: Tracking identifier (int).
  • instance: Latest Instance detection data (access semantic label via instance.label).
  • trajectory: TimedPointQueue with historical positions.

TimedPointQueue — Fixed-length trajectory history

  • enqueue(), dequeue(): FIFO with auto-eviction.
  • average_x, average_y, average_z: O(1) incremental centroid calculation.
  • get_values(): Deep-copy snapshot for safe external access.
  • __len__(), __iter__(), getitem__(): Collection-like behavior.

TimedPoint — Time-stamped spatial point

  • Extends Point with timestamp: Optional[datetime].
  • to_point(): Discards temporal metadata for geometry-only ops.

🔷 render — Visualization Layer

Type-safe drawing operations for embedded systems

Classes

Drawer — Main rendering engine

  • draw_instances(): Renders multiple objects with alpha-blended overlays 🔥
  • draw_box_fill(), draw_box_stroke(): Axis-aligned boxes with firmware-style corners.
  • draw_obb_fill(), draw_obb_stroke(): Oriented boxes with rotated corners.
  • draw_polygon_fill(), draw_polygon_stroke(): Segmentation masks with smoothing.
  • draw_trajectory(): Movement paths with None filtering.
  • draw_text(): Absolute pixel coordinate text rendering.
  • @validate_frame decorator on all public methods — zero-crash guarantee.

Style — Centralized visualization config

  • palette: Unique RGB tuples with [0, 255] validation.
  • stroke, fill, font: Granular styling components with strict validation.
  • rounding, smooth, alpha: All range-validated.
  • label: LabelPosition enum (TOP, BOTTOM, LEFT, RIGHT, CENTER, OFF) for badge placement.
  • show: Global toggle — False bypasses all rendering for headless mode.

🔷 utils — Foundational Helpers

High-performance, resource-aware operations

Functions

get_frame_illumination()

  • Calculates frame illumination using grid sampling for efficient processing on embedded devices.
  • Supports BGR (fastest, ITU-R BT.601), GRAY (balanced), and LAB (most accurate) methods.
  • Delivers 10-50× speedup on Raspberry Pi and similar devices.

💡 Quick Start

from enum import Enum
import numpy as np

# 1. Import core components
from acmenra_cv.instance import DeviceType, TaskType
from acmenra_cv.inference import Result, Timing
from acmenra_cv.tracker import Tracker
from acmenra_cv.render import Drawer, Style, Font, Stroke, Fill

# 2. Import YOLO plugin (requires: pip install "acmenra-cv[yolo]")
from acmenra_yolo import YOLOBackend
from ultralytics import YOLO

# 3. Define your categories
class CocoClass(Enum):
    PERSON = 0
    CAR = 2

# 4. Initialize components
model = YOLO("yolov8n.pt")

# Backend-agnostic inference engine (provided by acmenra-yolo plugin)
backend = YOLOBackend(
    model=model,
    device=DeviceType.CPU,
    category=CocoClass,          # Enum CLASS
    task_type=TaskType.DETECT,
    threshold=0.5,
    iou=0.7,
    imgsz=640,
    half=False,
    refined=False
)

# Visualization styling
style = Style(
    palette=[(255, 0, 0), (0, 255, 0), (0, 0, 255)],
    font=Font(color=(255, 255, 255)),
    stroke=Stroke(thickness=2, segment=0.1, alpha=0.8),
    fill=Fill(alpha=0.3),
    show=True
)

# Tracker receives the backend, decoupling inference from tracking logic
tracker = Tracker(id=0, backend=backend, max_length=50)
drawer = Drawer(style=style)

# 5. Process a frame
frame = np.zeros((1080, 1920, 3), dtype=np.uint8)  # Replace with your BGR frame
tracked_objects = tracker.track(frame, enable_tracking=True)

# 6. Create Result container (optional, for serialization/analytics)
timing = Timing(preprocess=1.5, prediction=15.2, postprocess=2.1)
result = Result(
    instances=[obj.instance for obj in tracked_objects],
    timing=timing,
    width=frame.shape[1],
    height=frame.shape[0],
    depth=1,
    device=DeviceType.CPU,
    category=CocoClass
)

# 7. Render results
output = drawer.draw_instances(
    frame=frame,
    tracked_objects=tracked_objects,
    is_box=True,
    is_trajectory=True
)

# 8. Use Result collection-like API
print(f"Detected {len(result)} objects")
for instance in result:
    # Note: use instance.label (Enum member), not instance.category
    print(f"  - {instance.label.name}: {instance.conf:.2f}")

# 9. Serialize for Outbox/Analytics
result_dict = result.to_dict()

# 10. Use spatial data for business logic
for obj in tracked_objects:
    if obj.trajectory.count >= 5:
        if obj.instance.label == CocoClass.CAR:
            pass # trigger_alert(obj)

📋 Requirements

Core dependencies (installed with pip install acmenra-cv):

numpy>=1.21.0
opencv-python>=4.5.0

Optional dependencies (installed with pip install "acmenra-cv[yolo]"):

acmenra-yolo>=0.1.0.0
ultralytics>=8.0.0
torch>=1.8.0

Development dependencies:

pytest>=7.0.0
ddt>=1.6.0
black>=23.0.0
mypy>=1.0.0

🧪 Testing

The library includes comprehensive test suites with DDT (Data-Driven Testing) and extensive mocks:

# Run all tests
pytest tests/

# Run specific module tests
pytest tests/inference/
pytest tests/instance/
pytest tests/tracker/
pytest tests/render/

Test coverage includes:

  • ✅ Type validation (positive and negative paths)
  • ✅ Range validation (boundary conditions)
  • ✅ Serialization round-trips (to_dict ↔ from_dict)
  • ✅ Edge cases (empty collections, None values, extreme values)
  • ✅ Collection-like behavior (__len__, __iter__, __getitem__)

🔐 License

This project is licensed under the GNU Affero General Public License v3 or later (AGPL-3.0-or-later).
See the LICENSE file for details.



acmenra.studio — Building reliable vision systems for the edge.
Every millisecond and frame buffer counts. 🚀

Downloads & popularity

Awaiting observations

No metric observations yet

Download counts and popularity will appear here as the collector receives them.

Versions 1

Collected releases
VersionPublishedDirect dependenciesOpen version
0.3.3.120 Oct 20267

Package advisories

0
No matching advisories collected

This describes our collected data; it is not a security assessment.

Repository

PENDING
acmenra/acmenra-cv

Shared repository data · GitHub

License detected in repository
Not collected

Metadata history

Meaningful changes
Current collected state Current

Observed since 20 Oct, 18:18 UTC

No superseded metadata states collected. Unchanged observations do not create new revisions.

Record identity

package:7f752584f839a00e99e30c3c8653ca4f9152ab19907df9bb12277431dc30a710