Skip to content

Repository files navigation

overstep

High-performance, dependency-minimal Python spatial AI and physical video analytics engine.

overstep is a pure NumPy-accelerated library designed for real-time video spatial reasoning, perimeter defense, line-crossing detection, crowd density monitoring, trajectory anomaly detection, collision forecasting, and multi-camera spatial intelligence.


Core Capabilities

1. Vectorized Computational Geometry

  • Batch Point-in-Polygon (PIP): batch_point_in_polygon evaluates $M$ query points against an $N$-vertex polygon simultaneously using array broadcasting.
  • Multiple PIP Algorithms: Supports ray casting (even-odd), winding number, convex, and spatial bounding algorithms.
  • Polygon Simplification & Hulls: Ramer-Douglas-Peucker (simplify_polygon), convex_hull, concave_hull, and oriented_bounding_box.
  • Buffer & Clipping: Polygon buffering (buffer_polygon) and Sutherland-Hodgman polygon clipping (clip_polygon) for overlap ratio calculation.

2. Spatial Safety & Perimeter Enforcement

  • Unified Boundary Interface: Boundary abstract base class contract across all boundaries.
  • Polygon & Line Zones: PolygonZone, LineBoundary, MovingZone, PolygonWithHoles, and DirectionalPolygonZone.
  • Wrong-Way Traffic Detector: WrongWayDetector enforces one-way lane direction vectors across tripwires and boundaries.
  • Zone Capacity Manager: CapacityManager monitors live occupancy with hysteresis thresholding to prevent alert flickering.
  • Queue Length Analyzer: QueueLengthAnalyzer tracks stationary object count, line formation extent, and average wait duration.

3. Motion Intelligence & Trajectory Mining

  • Trajectory Anomaly Detection: TrajectoryAnomalyDetector evaluates active track paths against standard reference trajectories using Fréchet, DTW, or Hausdorff distance.
  • Trajectory Clustering: TrajectoryClusterer clusters motion paths using DBSCAN on distance matrices.
  • Near-Miss & Collision Forecasting: NearMissDetector and CollisionPredictor calculate pairwise Time-To-Collision (TTC) and minimum future separation distances.
  • RTS Trajectory Smoothing: TrajectorySmoother uses Rauch-Tung-Striebel (RTS) fixed-interval backward smoothing.

4. Tracking, Re-ID & Multi-Camera Fusion

  • Kalbee SORT Tracker: KalmanBoxTracker and MultiObjectTracker backed by kalbee's 7D Kalman filter with Chi-Square innovation gating and confidence ellipses.
  • Visual Re-ID Matching: ReIDFeatureMatcher matches track feature embeddings using cosine similarity.
  • Multi-Camera Aggregation: MultiCameraAggregator and MultiCameraFusionEngine fuse overlapping or non-overlapping camera feeds.

5. Multi-Zone Markov Transitions & Heatmaps

  • Markov Transition Graph: ZoneTransitionGraph models inter-zone transition probability matrices $P(Z_j \mid Z_i)$ and scores trajectory transition anomalies.
  • Multi-Zone Manager: ZoneManager tracks live per-zone occupancy and inter-zone transitions.
  • Spatial Heatmaps: SpatialHeatmap and GaussianSpatialHeatmap.

6. Event Engine, GIS GeoJSON & Analytics

  • Debounced Event Engines: EventEngine and AsyncEventEngine.
  • Event Streaming: EventStreamWriter dispatches events to JSON-Lines log files or custom callback sinks.
  • GIS GeoJSON: Export zones and events to RFC 7946 GeoJSON (polygon_to_geojson, events_to_geojson_feature_collection).
  • Analytics Reporting: AnalyticsReportGenerator generates spatial summary statistics.

Installation

Using uv:

uv pip install -e .

Or using standard pip:

pip install -e .

Quickstart Examples

1. Basic Zone Violation & Event Engine

import numpy as np
import overstep as ov

# Define boundary zone and tracker
zone = ov.PolygonZone([(100, 100), (500, 100), (500, 400), (100, 400)])
tracker = ov.MultiObjectTracker()
engine = ov.EventEngine(boundary=zone, debounce_frames=3)

# Process frame detections
detections = [
    ov.Detection(bbox=np.array([150, 150, 200, 200]), score=0.92, class_id=0),
]

tracks = tracker.update(detections)
violations = zone.check_batch(tracks)
events = engine.update(tracks, frame=1)

for event in events:
    print(f"Event {event.type} triggered by Track #{event.track_id}")

2. Wrong-Way Lane Enforcement

import numpy as np
import overstep as ov

# Define allowed lane traffic flow direction (moving right)
wrong_way_detector = ov.WrongWayDetector(
    allowed_direction_vector=[1.0, 0.0],
    cos_threshold=-0.5,
    min_speed=1.0,
)

# Active track moving in prohibited reverse direction (moving left)
track = ov.Track(
    id=10,
    bbox=np.array([200, 200, 250, 250]),
    velocity=np.array([-4.5, 0.0]),
    age=5,
    hits=5,
    time_since_update=0,
)

events = wrong_way_detector.update([track], frame=42)
for event in events:
    print(f"Wrong-way violation detected for Track #{event.track_id}")

3. Queue Length & Capacity Management

import numpy as np
import overstep as ov

zone = ov.PolygonZone([(50, 50), (300, 50), (300, 300), (50, 300)])
queue_analyzer = ov.QueueLengthAnalyzer(zone, stationary_speed_threshold=0.8, fps=30.0)
capacity_mgr = ov.CapacityManager(max_capacity=5, hysteresis=1)

# Active tracks inside zone
tracks = [
    ov.Track(id=1, bbox=np.array([60, 60, 80, 80]), velocity=np.array([0.1, 0.0]), age=10, hits=10, time_since_update=0),
    ov.Track(id=2, bbox=np.array([120, 120, 140, 140]), velocity=np.array([0.0, 0.1]), age=10, hits=10, time_since_update=0),
]

metrics = queue_analyzer.update(tracks)
print(f"Queue Count: {metrics['queue_count']}, Avg Wait: {metrics['avg_wait_time_seconds']:.2f}s")

cap_events = capacity_mgr.update(current_count=int(metrics['queue_count']), frame=100)

4. Ecosystem Adapters (Supervision & Ultralytics YOLO)

import overstep as ov

# Convert Ultralytics YOLO results to overstep Detections
# detections = ov.from_ultralytics(yolo_results)

# Convert Roboflow Supervision Detections
# detections = ov.from_supervision(supervision_detections)

Performance Benchmarks

All benchmark metrics measured on Apple M-series hardware using NumPy array operations:

Operation Scale / Count Execution Time
Batch Point-in-Polygon (batch_point_in_polygon) 10,000 Points vs 10-Vertex Polygon < 0.8 ms
IoU Matrix Broadcasting (compute_iou_matrix) 100 Trackers vs 100 Detections < 0.12 ms
Pairwise Signed Distance (signed_distance) 50 Points vs 20-Vertex Polygon < 0.15 ms
Complete Test Suite Execution 77 Unit Tests across 28 Modules < 0.75 seconds

Testing & Quality Assurance

Run the complete test suite with uv:

uv run pytest

Check formatting and lint rules with ruff:

uv run ruff check .
uv run ruff format --check .

License

overstep is released under the MIT License.

About

Lightweight boundary violation detection, spatial video analytics, and tracking library in Python.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages