### Setup and Run Benchmarks (Bash) Source: https://github.com/nmichlo/norfair-rs/blob/main/examples/benchmark/README.md Shell script to install dependencies (Rust, Go, UV, OpenCV) and execute the cross-language performance benchmarks for Norfair. It generates deterministic data and runs tracking simulations. ```bash # setup brew install rust go uv opencv # run # - generates deterministic data # - runs tracking over deterministic data bash run_benchmarks.sh ``` -------------------------------- ### Rust Quick Start: Object Tracking with Norfair-rs Source: https://github.com/nmichlo/norfair-rs/blob/main/README.md This Rust code snippet demonstrates the basic workflow for using norfair-rs to track objects. It initializes a tracker with an IoU distance function, processes frames by generating detections, and updates the tracker to obtain tracked objects with stable IDs. The example shows how to convert bounding box data into `Detection` objects and utilize the `update` method. ```rust use norfair_rs::{Detection, Tracker, TrackerConfig}; fn main() -> Result<(), Box> { // 1. Create tracker with IoU distance function let mut config = TrackerConfig::from_distance_name("iou", 0.5); config.hit_counter_max = 30; config.initialization_delay = 3; let mut tracker = Tracker::new(config)?; // 2. For each frame for frame in iter_video_frames() { // 2.1 Generate detections from your object detector let detections: Vec = detect_objects(&frame) .iter() .map(|bbox| { // Bounding box format: [x1, y1, x2, y2] Detection::from_slice( &[bbox.x, bbox.y, bbox.x + bbox.w, bbox.y + bbox.h], 1, 4 // 1 row, 4 columns ).unwrap() }) .collect(); // 2.2 Update tracker, returning current tracked objects with stable IDs let tracked_objects = tracker.update(detections, 1, None); // 2.3 Use tracked objects (draw, analyze, etc.) for obj in tracked_objects { if let Some(id) = obj.id { draw_box(&frame, &obj.estimate, id); } } } Ok(()) } ``` -------------------------------- ### Python Installation and Import for norfair-rs Source: https://github.com/nmichlo/norfair-rs/blob/main/README.md Install norfair-rs for Python using pip or uv to utilize its drop-in replacement capabilities. Update your import statement to use the new library, offering significant performance improvements over the original. ```bash uv add norfair-rs # or: pip install norfair-rs ``` ```python # Before (original norfair) from norfair import Detection, Tracker # After (norfair-rs drop-in replacement) # from norfair_rs import Detection, Tracker ``` -------------------------------- ### Rust Dependency Installation for norfair-rs Source: https://github.com/nmichlo/norfair-rs/blob/main/README.md Add the norfair-rs crate as a dependency to your Rust project by including it in your Cargo.toml file. This specifies the version of the library to be used. ```toml [dependencies] norfair-rs = "0.3" ``` -------------------------------- ### Norfair-rs Filter Options Initialization (Rust) Source: https://github.com/nmichlo/norfair-rs/blob/main/README.md Demonstrates how to import and use different filter factory types for the Norfair tracker. It includes the optimized Kalman filter, a filterpy-compatible Kalman filter, and a no-filter option for detection-only scenarios. These factories are crucial for configuring the tracker's prediction mechanism. ```rust use norfair_rs::filter:: OptimizedKalmanFilterFactory, FilterPyKalmanFilterFactory, NoFilterFactory; // Example usage (assuming instantiation elsewhere): // let kalman_factory = OptimizedKalmanFilterFactory; // let filterpy_kalman_factory = FilterPyKalmanFilterFactory; // let no_filter_factory = NoFilterFactory; ``` -------------------------------- ### Python Norfair Equivalent: Object Tracking Workflow Source: https://github.com/nmichlo/norfair-rs/blob/main/README.md This Python code snippet illustrates the equivalent object tracking workflow using the original Python norfair library. It shows how to initialize the `Tracker` with similar parameters and process frames by creating `Detection` objects from detected bounding boxes. This serves as a direct comparison to the Rust implementation. ```python # OLD: from norfair import Detection, Tracker from norfair_rs import Detection, Tracker # Create tracker tracker = Tracker( distance_function="iou", distance_threshold=0.5, hit_counter_max=30, initialization_delay=3, ) # Process frames for frame in iter_video_frames(): # Get detections from your detector detections = [ Detection(points=np.array([[x1, y1, x2, y2]])) for x1, y1, x2, y2 in detect_objects(frame) ] # Update tracker tracked_objects = tracker.update(detections=detections) # Use tracked objects for obj in tracked_objects: draw_box(frame, obj.estimate, obj.id) ``` -------------------------------- ### Create and Update Tracker with Detections in Rust Source: https://context7.com/nmichlo/norfair-rs/llms.txt Demonstrates the basic usage of norfair-rs for object tracking. It shows how to configure a tracker with specific parameters like distance metric and thresholds, process raw bounding box detections from an object detector, and update the tracker to obtain stable object IDs and their estimated positions. The output includes active tracked objects with their IDs and position estimates. ```rust use norfair_rs::{Detection, Tracker, TrackerConfig}; fn main() -> Result<(), Box> { // Create tracker configuration with IoU distance and threshold let mut config = TrackerConfig::from_distance_name("iou", 0.5); config.hit_counter_max = 30; // Keep objects alive 30 frames without detection config.initialization_delay = 3; // Require 3 detections to initialize config.detection_threshold = 0.5; // Minimum detection confidence let mut tracker = Tracker::new(config)?; // Process each video frame for frame_idx in 0..100 { // Get bounding boxes from your detector: [[x1, y1, x2, y2], ...] let bboxes = detect_objects_yolo(frame_idx); // Your detector function // Convert to Detection objects let detections: Vec = bboxes .iter() .map(|bbox| { // Bounding box format: [x1, y1, x2, y2] Detection::from_slice( &[bbox.x1, bbox.y1, bbox.x2, bbox.y2], 1, // 1 row (single bounding box) 4 // 4 columns (x1, y1, x2, y2) ).unwrap() }) .collect(); // Update tracker - returns active objects with stable IDs let tracked_objects = tracker.update(detections, 1, None); // Use tracked objects for your application for obj in tracked_objects { if let Some(id) = obj.id { println!("Frame {}: Object {} at {:?}", frame_idx, id, obj.estimate); // obj.estimate contains the smoothed position estimate // obj.hit_counter shows tracking confidence // obj.age is frames since first detection } } } println!("Total objects tracked: {}", tracker.total_object_count()); Ok(()) } // Mock detector for example fn detect_objects_yolo(frame: usize) -> Vec { vec![ BBox { x1: 100.0, y1: 100.0, x2: 200.0, y2: 200.0 }, BBox { x1: 300.0, y1: 150.0, x2: 400.0, y2: 250.0 }, ] } struct BBox { x1: f64, y1: f64, x2: f64, y2: f64, } ``` -------------------------------- ### Norfair-RS Kalman Filter Implementations and Configuration Source: https://context7.com/nmichlo/norfair-rs/llms.txt Explains the different Kalman filter implementations available in Norfair-RS: OptimizedKalmanFilter (default, fast), FilterPyKalmanFilter (for compatibility), and NoFilter (for no prediction). It shows how to instantiate these filters with their respective parameters (R, Q, P) and configure them within the TrackerConfig. ```rust use norfair_rs::filter::{ OptimizedKalmanFilterFactory, FilterPyKalmanFilterFactory, NoFilterFactory, FilterFactoryEnum, }; fn demo_filter_types() { // 1. OptimizedKalmanFilter - Fast, simplified Kalman (default, recommended) // Best for real-time tracking with good accuracy/performance tradeoff let optimized_factory = OptimizedKalmanFilterFactory::new( 4.0, // R: measurement noise (sensor uncertainty) 0.1, // Q: process noise (how much object moves between frames) 10.0, // P: initial covariance (initial position uncertainty) 0.0, // pos_variance: position variance scaling 1.0 // vel_variance: velocity variance scaling ); // 2. FilterPyKalmanFilter - Full filterpy-compatible implementation // Use when you need exact numerical equivalence with Python filterpy let filterpy_factory = FilterPyKalmanFilterFactory::new( 4.0, // R: measurement noise 0.1, // Q: process noise 10.0 // P: initial covariance ); // 3. NoFilter - No prediction, detection-only tracking // Use when objects move unpredictably or for debugging let no_filter_factory = NoFilterFactory::new(); // Use in tracker configuration let mut config = norfair_rs::TrackerConfig::from_distance_name("euclidean", 50.0); // Set filter type (enum-based for performance) config.filter_factory = FilterFactoryEnum::Optimized(optimized_factory); // or: FilterFactoryEnum::FilterPy(filterpy_factory) // or: FilterFactoryEnum::None(no_filter_factory) let tracker = norfair_rs::Tracker::new(config).unwrap(); println!("Tracker created with optimized Kalman filter"); } // Filter parameter tuning guide fn tuning_example() { // High measurement noise (R=10.0): Trust predictions more than measurements // Use when detector is noisy or unreliable let noisy_detector = OptimizedKalmanFilterFactory::new(10.0, 0.1, 10.0, 0.0, 1.0); // High process noise (Q=5.0): Expect large movements between frames // Use for fast-moving objects or low frame rate let fast_objects = OptimizedKalmanFilterFactory::new(4.0, 5.0, 10.0, 0.0, 1.0); // High initial covariance (P=50.0): Very uncertain about initial positions // Use when first detections are unreliable let uncertain_init = OptimizedKalmanFilterFactory::new(4.0, 0.1, 50.0, 0.0, 1.0); } ``` -------------------------------- ### Norfair-RS Distance Functions and Custom Implementation Source: https://context7.com/nmichlo/norfair-rs/llms.txt Demonstrates how to use built-in distance functions (IoU, Euclidean, Manhattan, Mean Euclidean, Frobenius) by name and how to implement and use a custom scalar distance function. It also shows how these distances are used within the TrackerConfig and for computing a distance matrix between detections and tracked objects. ```rust use norfair_rs::{TrackerConfig, distances::{distance_by_name, Distance, ScalarDistance}}; use norfair_rs::{Detection, TrackedObject}; use nalgebra::DMatrix; fn demo_distance_functions() { // Built-in distance functions via string name let iou_distance = distance_by_name("iou"); // Intersection over Union let euclidean = distance_by_name("euclidean"); // L2 distance let manhattan = distance_by_name("manhattan"); // L1 distance let mean_euc = distance_by_name("mean_euclidean"); // Average L2 per point let frobenius = distance_by_name("frobenius"); // Frobenius norm // Custom distance function fn custom_weighted_distance(det_points: &DMatrix, obj_points: &DMatrix) -> f64 { // Weight X coordinates more than Y let diff = det_points - obj_points; let x_diff = diff.column(0).norm(); let y_diff = diff.column(1).norm(); x_diff * 2.0 + y_diff // X coordinates weighted 2x } let custom_distance = ScalarDistance::new(custom_weighted_distance); // Use in tracker config let config = TrackerConfig::new( norfair_rs::distances::distance_function_by_name("iou"), 0.7 ); } // Distance function comparison example fn compute_distance_matrix_example() { use norfair_rs::distances::Distance; let distance = distance_by_name("iou"); // Create mock detections and tracked objects let det1 = Detection::from_slice(&[0.0, 0.0, 10.0, 10.0], 1, 4).unwrap(); let det2 = Detection::from_slice(&[5.0, 5.0, 15.0, 15.0], 1, 4).unwrap(); // In actual use, tracked_objects come from tracker.tracked_objects // Here we show the distance computation concept let detections = vec![&det1, &det2]; // Distance matrix: rows = detections, cols = tracked objects // matrix[(i, j)] = distance between detection i and object j println!("Distance computation ready for {} detections", detections.len()); } ``` -------------------------------- ### Create Detections with Keypoints and Confidence Scores (Rust) Source: https://context7.com/nmichlo/norfair-rs/llms.txt This Rust code illustrates how to create Norfair `Detection` objects incorporating multiple keypoints and their associated confidence scores. It shows how to represent both keypoint data and bounding boxes using `nalgebra::DMatrix`. ```rust use norfair_rs::Detection; use nalgebra::DMatrix; fn create_keypoint_detections() -> Vec { let mut detections = Vec::new(); // Person detection with 5 keypoints: [nose, left_shoulder, right_shoulder, left_hip, right_hip] let keypoints = vec![ [150.0, 100.0], // nose [140.0, 120.0], // left shoulder [160.0, 120.0], // right shoulder [140.0, 160.0], // left hip [160.0, 160.0], // right hip ]; // Confidence scores for each keypoint (0.0 to 1.0) let scores = vec![0.9, 0.85, 0.8, 0.7, 0.75]; // Flatten keypoints to row-major format let points_flat: Vec = keypoints.iter().flatten().copied().collect(); // Create detection with 5 points, 2 dimensions each let points_matrix = DMatrix::from_row_slice(5, 2, &points_flat); let detection = Detection::with_config( points_matrix, Some(scores), Some("person".to_string()), // class label None, // embedding for ReID (optional) ).unwrap(); detections.push(detection); // Another detection: bounding box (single point with 4 coordinates) let bbox = Detection::from_slice( &[200.0, 200.0, 300.0, 300.0], 1, // 1 point 4 // 4 coordinates [x1, y1, x2, y2] ).unwrap(); detections.push(bbox); detections } ``` -------------------------------- ### Norfair Benchmark Results (v0.1.0) Source: https://github.com/nmichlo/norfair-rs/blob/main/examples/benchmark/README.md Table summarizing the performance of Norfair implementations in Python, Go, and Rust for various scenarios (small, medium, large, stress) based on objects, frames, and detections. Includes 'skipped' for scenarios where performance was too low. ```markdown | Scenario | Objects | Frames | Detections | norfair | norfair-go | norfair-rs (python) | norfair-rs (rust) | |----------|---------|--------|------------|---------|------------|---------------------|-------------------| | small | 5 | 100 | 446 | ~4,700 | ~243k | ~107k | ~296k | | medium | 20 | 500 | 9,015 | ~540 | ~31k | ~27k | ~89k | | large | 50 | 1000 | 44,996 | ~101 | ~3.8k | ~11k | ~41k | | stress | 100 | 2000 | 179,789 | skipped | ~547 | ~5.2k | ~18.5k | ``` -------------------------------- ### Python: Norfair-RS as Drop-in Replacement and Customization Source: https://context7.com/nmichlo/norfair-rs/llms.txt Integrates norfair-rs into Python projects, offering a 20-50x performance improvement over the standard norfair library. This snippet shows tracker initialization with various parameters, processing detections from a model, and accessing tracked object properties. It also demonstrates using a custom Python callable for distance calculations and integrating ReID embeddings for more robust tracking. ```python # Install: pip install norfair-rs # or: uv add norfair-rs import numpy as np from norfair_rs import Tracker, Detection # Create tracker (same API as norfair) tracker = Tracker( distance_function="iou", distance_threshold=0.5, hit_counter_max=30, initialization_delay=3, detection_threshold=0.5, ) # Process video frames for frame in video_frames: # Get detections from your model (YOLO, Faster R-CNN, etc.) bboxes = model.detect(frame) # Returns list of [x1, y1, x2, y2] # Create Detection objects detections = [ Detection(points=np.array([[x1, y1, x2, y2]])) for x1, y1, x2, y2 in bboxes ] # Update tracker - returns TrackedObject instances with stable IDs tracked_objects = tracker.update(detections=detections) # Access tracked object properties (same as norfair) for obj in tracked_objects: print(f"Object {obj.id}:") print(f" Position: {obj.estimate}") print(f" Age: {obj.age} frames") print(f" Hit counter: {obj.hit_counter}") print(f" Last distance: {obj.last_distance}") # Advanced: Custom distance function in Python def custom_distance(detection, tracked_object): """Python callable distance function (compatible with norfair-rs)""" diff = detection.points - tracked_object.estimate return np.linalg.norm(diff) tracker_custom = Tracker( distance_function=custom_distance, # Python function works! distance_threshold=50.0, ) # ReID example with embeddings from norfair_rs import Detection # Detection with ReID embedding detection_with_reid = Detection( points=np.array([[100, 100, 200, 200]]), embedding=np.array([0.1, 0.2, 0.3, 0.4]) # Feature vector from ReID model ) tracker_reid = Tracker( distance_function="euclidean", distance_threshold=50.0, reid_distance_function="euclidean", reid_distance_threshold=100.0, reid_hit_counter_max=50, past_detections_length=4, ) ``` -------------------------------- ### Configure Norfair Tracker with ReID and Custom Kalman Filter (Rust) Source: https://context7.com/nmichlo/norfair-rs/llms.txt This Rust code demonstrates how to configure the Norfair tracker with re-identification for track recovery and a custom OptimizedKalmanFilterFactory. It sets parameters for distance matching, tracking lifecycle, re-identification thresholds, and Kalman filter noise and covariance. ```rust use norfair_rs::{TrackerConfig, filter::OptimizedKalmanFilterFactory, distances::distance_by_name}; fn create_advanced_tracker() -> Result> { // Start with Euclidean distance for position matching let mut config = TrackerConfig::new( norfair_rs::distances::distance_function_by_name("euclidean"), 50.0 // distance threshold ); // Tracking lifecycle parameters config.hit_counter_max = 15; // Object lifetime without detections config.initialization_delay = 3; // Frames required to initialize config.pointwise_hit_counter_max = 4; // Per-point tracking threshold config.detection_threshold = 0.5; // Minimum detection score config.past_detections_length = 4; // History for re-identification // Re-identification configuration (recover lost objects) config.reid_distance_function = Some( norfair_rs::distances::distance_function_by_name("euclidean") ); config.reid_distance_threshold = 100.0; // Distance threshold for ReID config.reid_hit_counter_max = Some(50); // Keep objects in ReID pool for 50 frames // Custom Kalman filter configuration config.filter_factory = norfair_rs::filter::FilterFactoryEnum::Optimized( OptimizedKalmanFilterFactory::new( 4.0, // R: measurement noise (higher = trust measurements less) 0.1, // Q: process noise (higher = expect more movement) 10.0, // P: initial covariance (initial uncertainty) 0.0, // pos_variance: position variance multiplier 1.0 // vel_variance: velocity variance multiplier ) ); let tracker = norfair_rs::Tracker::new(config)?; Ok(tracker) } ``` -------------------------------- ### Norfair-rs Configuration Options: TrackerConfig Source: https://github.com/nmichlo/norfair-rs/blob/main/README.md This Rust code snippet demonstrates how to configure the `Tracker` in norfair-rs using the `TrackerConfig` struct. It showcases various parameters for controlling tracking behavior, re-identification, and Kalman filter settings, including distance functions, hit counters, initialization delays, and noise parameters for the filter. ```rust use norfair_rs::{TrackerConfig, filter::OptimizedKalmanFilterFactory}; use norfair_rs::distances::distance_by_name; let mut config = TrackerConfig::new(distance_by_name("euclidean"), 50.0); // Tracking behavior config.hit_counter_max = 15; // Frames to keep tracking without detection config.initialization_delay = 3; // Detections required to initialize config.pointwise_hit_counter_max = 4; // Per-point tracking threshold config.detection_threshold = 0.5; // Minimum detection confidence config.past_detections_length = 4; // History for re-identification // Re-identification (optional) config.reid_distance_function = Some(distance_by_name("euclidean")); config.reid_distance_threshold = 100.0; config.reid_hit_counter_max = Some(50); // Kalman filter config.filter_factory = Box::new(OptimizedKalmanFilterFactory::new( 4.0, // R (measurement noise) 0.1, // Q (process noise) 10.0, // P (initial covariance) 0.0, // pos_variance 1.0, // vel_variance )); ``` -------------------------------- ### Norfair v0.1.0 Baseline Performance (Box) Source: https://github.com/nmichlo/norfair-rs/blob/main/examples/benchmark/README.md Markdown table showing initial benchmark results for Norfair with dynamic dispatch (Box), comparing Rust and Go implementations across various scenarios. Rust shows a significant performance advantage over Go. ```markdown | Scenario | Rust FPS | Go FPS | Rust vs Go | |----------|----------|--------|------------| | small | 477k | 258k | 1.9x | | medium | 44k | 32k | 1.4x | | large | 32k | 3.9k | 8.2x | | stress | 17k | 562 | 30x | ``` -------------------------------- ### Inspecting TrackedObject Properties in Rust Source: https://context7.com/nmichlo/norfair-rs/llms.txt Demonstrates how to access detailed tracking state information from TrackedObject instances. It initializes a tracker, updates it with sample detections, and then iterates through the results to print various properties like ID, age, hit counter, position, velocity, and class labels. ```rust use norfair_rs::{Tracker, TrackerConfig, Detection}; fn inspect_tracked_objects() -> Result<(), Box> { let config = TrackerConfig::from_distance_name("euclidean", 50.0); let mut tracker = Tracker::new(config)?; let detections = vec![ Detection::from_slice(&[100.0, 100.0], 1, 2)?, Detection::from_slice(&[200.0, 150.0], 1, 2)?, ]; let tracked = tracker.update(detections, 1, None); for obj in tracked { // Identity information println!("Permanent ID: {:?}", obj.id); // None if initializing, Some(n) when initialized println!("Global ID: {}", obj.global_id); // Unique across all trackers println!("Initializing ID: {:?}", obj.initializing_id); // Temporary ID during initialization // Tracking state println!("Age: {} frames", obj.age); // Frames since first detection println!("Hit counter: {}", obj.hit_counter); // Remaining lifetime without detection println!("Is initializing: {}", obj.is_initializing); // Still in initialization phase // Position and motion println!("Estimate: {:?}", obj.estimate); // Current position (n_points x n_dims matrix) println!("Velocity: {:?}", obj.estimate_velocity); // Current velocity estimate // Matching information println!("Last distance: {:?}", obj.last_distance); // Distance to last matched detection // Point-level tracking (for keypoints) println!("Live points: {:?}", obj.live_points()); // Which points are currently tracked println!("Point hit counters: {:?}", obj.point_hit_counter); // Per-point tracking confidence println!("Detected once: {:?}", obj.detected_at_least_once_points); // Ever detected // Class and metadata println!("Label: {:?}", obj.label); // Object class // ReID information println!("ReID hit counter: {:?}", obj.reid_hit_counter); // Frames remaining in ReID phase } // Tracker statistics println!("\nTracker stats:"); println!("Total objects: {}", tracker.total_object_count()); // Total objects ever initialized println!("Current objects: {}", tracker.current_object_count()); // Currently active objects Ok(()) } ``` -------------------------------- ### Norfair-rs Feature Flag Configuration (TOML) Source: https://github.com/nmichlo/norfair-rs/blob/main/README.md Illustrates how to enable the 'opencv' feature flag for the norfair crate in a Cargo.toml file. This feature enables additional functionalities such as video I/O, drawing capabilities, and homography transforms, which are useful for advanced computer vision tasks. ```toml [dependencies] norfair = { git = "...", features = ["opencv"] } ``` -------------------------------- ### Rust: Compensate Camera Motion for Accurate Tracking Source: https://context7.com/nmichlo/norfair-rs/llms.txt Compensates for camera movement in real-time tracking applications using norfair-rs's `TranslationTransformation`. This function demonstrates how to initialize a tracker, update it with detections, and apply camera motion transformations to maintain accurate object tracking across frames. It requires the `norfair_rs` crate and standard Rust error handling. ```rust use norfair_rs::{Tracker, TrackerConfig, Detection}; use norfair_rs::camera_motion::TranslationTransformation; fn tracking_with_camera_motion() -> Result<(), Box> { let mut config = TrackerConfig::from_distance_name("euclidean", 50.0); config.initialization_delay = 0; // Immediate initialization for demo let mut tracker = Tracker::new(config)?; // Frame 0: Object at (100, 100), camera at origin let det1 = vec![Detection::from_slice(&[100.0, 100.0], 1, 2)?]; let objects = tracker.update(det1, 1, None); println!("Frame 0: {} objects", objects.len()); // Frame 1: Camera moved right by 10 pixels and down by 5 pixels // Object appears at (110, 105) in frame coordinates, but hasn't actually moved // Create transformation: camera moved by [dx, dy] = [10, 5] let camera_motion = TranslationTransformation::new([10.0, 5.0]); // Detection in frame coordinates: (110, 105) let det2 = vec![Detection::from_slice(&[110.0, 105.0], 1, 2)?]; // Pass camera motion to tracker - it will transform coordinates correctly let objects = tracker.update(det2, 1, Some(&camera_motion)); // Tracker understands object hasn't moved (accounts for camera motion) println!("Frame 1: {} objects (same object tracked)", objects.len()); // Frame 2: Camera moved back left by 5 pixels let camera_motion2 = TranslationTransformation::new([5.0, 5.0]); let det3 = vec![Detection::from_slice(&[105.0, 105.0], 1, 2)?]; let objects = tracker.update(det3, 1, Some(&camera_motion2)); println!("Frame 2: {} objects", objects.len()); Ok(()) } ``` -------------------------------- ### Norfair-rs Camera Motion Compensation (Rust) Source: https://github.com/nmichlo/norfair-rs/blob/main/README.md Shows how to use the `TranslationTransformation` to compensate for camera movement within the Norfair tracker. This involves creating a transformation object with the camera's translation (dx, dy) and passing it to the `tracker.update` method. This helps maintain accurate object tracking despite camera motion. ```rust use norfair_rs::camera_motion::TranslationTransformation; // Assuming 'tracker' is an initialized Tracker instance and 'detections' is a Vec // let dx = 10.0; // Example horizontal translation // let dy = 5.0; // Example vertical translation // let transform = TranslationTransformation::new([dx, dy]); // let tracked = tracker.update(detections, 1, Some(&transform)); ``` -------------------------------- ### Norfair Performance After Vec Matching Source: https://github.com/nmichlo/norfair-rs/blob/main/examples/benchmark/README.md Markdown table presenting benchmark results after optimizing greedy matching in Rust to use Vec instead of HashSet. This further improves Rust's performance range and comparison against Go. ```markdown | Scenario | Rust FPS | Go FPS | Rust vs Go | |----------|----------|--------|------------| | small | 200k-370k | 295k-304k | 0.7-1.2x | | medium | 68k-87k | 31k-34k | 2.0-2.8x | | large | 36k-40k | 3.8k | 9.5-10.5x | | stress | 18k-19k | 549-551 | 33-35x | ``` -------------------------------- ### Multi-Class Tracking with Labels in Rust Source: https://context7.com/nmichlo/norfair-rs/llms.txt Tracks multiple object classes simultaneously, assigning separate identities per class. It initializes a tracker with a specified distance metric and delay, then updates it with detections that include class labels. Finally, it iterates through the tracked objects, printing their class label and ID. ```rust use norfair_rs::{Detection, Tracker, TrackerConfig}; use nalgebra::DMatrix; fn multi_class_tracking() -> Result<(), Box> { let mut config = TrackerConfig::from_distance_name("iou", 0.6); config.initialization_delay = 2; let mut tracker = Tracker::new(config)?; // Frame with mixed object classes let mut detections = Vec::new(); // Person detection let person_points = DMatrix::from_row_slice(1, 4, &[100.0, 100.0, 200.0, 300.0]); let person = Detection::with_config( person_points, Some(vec![0.95]), // confidence Some("person".to_string()), // class label None, )?; detections.push(person); // Car detection let car_points = DMatrix::from_row_slice(1, 4, &[300.0, 150.0, 500.0, 300.0]); let car = Detection::with_config( car_points, Some(vec![0.88]), Some("car".to_string()), None, )?; detections.push(car); // Bicycle detection let bike_points = DMatrix::from_row_slice(1, 4, &[600.0, 200.0, 700.0, 350.0]); let bicycle = Detection::with_config( bike_points, Some(vec![0.82]), Some("bicycle".to_string()), None, )?; detections.push(bicycle); // Update tracker let tracked = tracker.update(detections, 1, None); // Filter by class for obj in tracked { if let Some(label) = &obj.label { println!("Tracking {} with ID {:?}", label, obj.id); println!(" Position: {:?}", obj.estimate); } } Ok(()) } ``` -------------------------------- ### Norfair Performance After Enum Dispatch Source: https://github.com/nmichlo/norfair-rs/blob/main/examples/benchmark/README.md Markdown table detailing benchmark results after replacing dynamic dispatch (Box) with enum-based static dispatch in Rust. Performance shows improved range and comparison against Go. ```markdown | Scenario | Rust FPS | Go FPS | Rust vs Go | |----------|----------|--------|------------| | small | 153k-449k | 262k-290k | 0.5-1.7x | | medium | 57k-114k | 32k | 1.8-3.5x | | large | 33k-42k | 3.8k | 8.7-11x | | stress | 17k | 550 | 31x | ``` -------------------------------- ### Tracked Objects Correctness Check (Markdown) Source: https://github.com/nmichlo/norfair-rs/blob/main/examples/benchmark/README.md Markdown table verifying the correctness of all Norfair implementations by comparing the counts of tracked objects across different scenarios. All implementations are shown to produce identical counts. ```markdown | Scenario | norfair | norfair-go | norfair-rs (python) | norfair-rs (rust) | |----------|---------|------------|---------------------|-------------------| | small | 480 | 480 | 480 | 480 | | medium | 9,935 | 9,935 | 9,935 | 9,935 | | large | 49,788 | 49,788 | 49,788 | 49,788 | | stress | 199,602 | 199,602 | 199,602 | 199,602 | ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.