Metadata-Version: 2.4
Name: acmenra-cv
Version: 0.1.7.9
Summary: Production-ready computer vision utilities for multi-object tracking
Author-email: "acmenra.studio" <hello@acmenra.ru>
Project-URL: Homepage, https://acmenra.studio
Project-URL: Documentation, https://github.com/Acmenra/acmenra-cv#readme
Project-URL: Repository, https://github.com/Acmenra/acmenra-cv
Keywords: acmenra-cv
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Image Recognition
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: numpy>=1.21.0
Requires-Dist: opencv-python>=4.5.0
Requires-Dist: ultralytics>=8.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"

# 🚀 acmenra-cv

> **Production-ready computer vision utilities for ADAS, multi-object tracking, and embedded vision systems**

[![PyPI](https://img.shields.io/pypi/v/acmenra-cv.svg)](https://pypi.org/project/acmenra-cv/)
[![Python](https://img.shields.io/pypi/pyversions/acmenra-cv.svg)](https://pypi.org/project/acmenra-cv/)
[![License](https://img.shields.io/pypi/l/acmenra-cv.svg)](LICENSE)

```bash
pip install acmenra-cv
```

---

## 📦 Overview

**acmenra-cv** is a high-performance, type-safe computer vision library engineered for **real-time applications on resource-constrained embedded systems** (Raspberry Pi 5, Jetson, NPU, etc.). Built following Clean Architecture principles, it provides four cohesive modules:

| Module | Purpose | Key Features |
|--------|---------|-------------|
| **`instance`** | Spatial primitives for detection outputs | Normalized coordinates, strict validation, immutable transformations |
| **`tracker`** | Multi-object tracking with trajectories | Persistent IDs, configurable history, BoT-SORT integration |
| **`render`** | Type-safe visualization layer | Alpha-blended overlays, embedded optimizations, graceful degradation |
| **`inference`** | Backend-agnostic result container | Collection-like API, timing metrics, JSON serialization |

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

---

## ✨ Key Features

### 🔹 Unified Architecture
- **Strict type & range validation** (`[0.0, 1.0]` with `safe()` clamping factory)
- **Seamless YOLO integration** (`boxes`, `masks.xyn`, `obb.xyxyxyxyn`)
- **Immutable geometric transformations** (`scale`, `translate`, `smooth`)
- **Full type safety** with IDE autocomplete and consistent API across all primitives

### 🔹 Backend-Agnostic Results
- **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

### 🔹 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) average calculation
- **Alpha-blended compositing** (`cv2.addWeighted`) and anti-aliased geometry (`LINE_AA`)

### 🔹 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](#instance) — Spatial Primitives
> Validated geometric containers for detection outputs

<details><summary><strong>Classes</strong></summary>

#### `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()`: Static 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()`: Static 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`, `category`, `conf`, `box`, `polygon`, `obb`.
* Strict validation on all properties.
* Designed for safe pipeline integration.

</details>

---

### 🔷 [inference](#inference) — Result Container
> Backend-agnostic output format with collection-like API

<details><summary><strong>Classes</strong></summary>

#### `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.
* Gracefully handles partial profiling data.

#### `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`).
* `device`: Hardware backend (`DeviceType` enum).
* `category`: Semantic category enumeration (`Optional[EnumType]`).
* `to_dict()`, `from_dict()`: JSON serialization (instances omitted, metadata only).

</details>

---

### 🔷 [tracker](#tracker) — Multi-Object Tracking
> Persistent IDs, trajectory management, ADAS integration

<details><summary><strong>Classes</strong></summary>

#### `Tracker` — Main tracking engine
* `__init__()`: Configurable with YOLO model, device, thresholds, `max_length`.
* `track()`: Main entry point — returns `List[TrackedObject]` with persistent IDs.
* `predict()`: Detection mode with optional tracking.
* Properties: `model`, `device`, `conf`, `iou`, `max_length` — all validated.

#### `TrackedObject` — Single tracked entity
* `id`: Tracking identifier (`Optional[int]`).
* `instance`: Latest `Instance` detection data.
* `trajectory`: `TimedPointQueue` with historical positions.

#### `TimedPointQueue` — Fixed-length trajectory history
* `enqueue()`, `dequeue()`: FIFO with auto-eviction.
* `average_x/y/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.
* `safe()`, `_from_raw()`: Factory methods with clamping.

</details>

---

### 🔷 [render](#render) — Visualization Layer
> Type-safe drawing operations for embedded systems

<details><summary><strong>Classes</strong></summary>

#### `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`: `Stroke` configuration (thickness, segment, alpha).
* `fill`: `Fill` configuration (alpha).
* `font`: `Font` configuration (color, font face, scale, thickness).
* `rounding`, `smooth`, `alpha`: All range-validated.
* `label`: `LabelPosition` enum for badge placement.
* `show`: Global toggle — `False` bypasses all rendering.
* `to_dict()`, `from_dict()`: Full JSON serialization.

#### `Stroke` — Outline styling
* `thickness`: Line thickness in pixels (`int ≥ 0`).
* `segment`: Corner segment factor `[0.0, 0.5]`.
* `alpha`: Stroke opacity `[0.0, 1.0]`.

#### `Fill` — Interior fill styling
* `alpha`: Fill opacity `[0.0, 1.0]`.

#### `Font` — OpenCV typography config
* `color`: 3-element RGB tuple validation.
* `font`: OpenCV font identifier `[0, 7]`.
* `font_scale`, `thickness`: Positive integer validation.

#### `LabelPosition` — Badge positioning enum
* `TOP`, `BOTTOM`, `LEFT`, `RIGHT`, `CENTER`, `OFF`.

</details>

---

## 💡 Quick Start

```python
from acmenra_cv.instance import Point, Box, Instance
from acmenra_cv.inference import Result, Timing
from acmenra_cv.tracker import Tracker, TimedPointQueue
from acmenra_cv.render import Drawer, Style, Font, Stroke, Fill
from acmenra_cv.instance import DeviceType
from ultralytics import YOLO
from enum import Enum

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

# 1. Initialize components
model = YOLO("yolov8n.pt")
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 = Tracker(
    id=0,
    model=model,
    category=CocoClass,
    device=DeviceType.CPU,
    max_length=50
)
drawer = Drawer(style=style)

# 2. Process a frame
frame = ...  # Your BGR frame (numpy array)
tracked_objects = tracker.track(frame, enable_tracking=True)

# 3. Create Result container (optional, for serialization)
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
)

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

# 5. Use Result collection-like API
print(f"Detected {len(result)} objects")
for instance in result:
    print(f"  - {instance.category.name}: {instance.conf:.2f}")

# 6. Serialize for Outbox/Analytics
result_dict = result.to_dict()
# ... send to backend or save to disk

# 7. Use spatial data for business logic
for obj in tracked_objects:
    if obj.trajectory.count >= 5:
        speed = estimate_speed(obj.trajectory)  # Your logic
        if obj.instance.category == CocoClass.CAR and speed > threshold:
            trigger_alert(obj)
```

---

## 📋 Requirements

```txt
numpy>=1.21.0
opencv-python>=4.5.0
ultralytics>=8.0.0
```

Optional for development:
```txt
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:

```bash
# 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

© 2026 **acmenra.studio**. All rights reserved.

This software is proprietary and confidential. Unauthorized copying, distribution, or use is strictly prohibited.

For commercial licensing inquiries: [contact@acmenra.studio](mailto:contact@acmenra.studio)

---

## 🌐 Links

- **PyPI**: https://pypi.org/project/acmenra-cv/
- **Source**: https://github.com/acmenra/acmenra-cv
- **Documentation**: https://github.com/acmenra/acmenra-cv#readme
- **Issues**: https://github.com/acmenra/acmenra-cv/issues

---

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