### Install NanoTrack via PyPI Source: https://github.com/ragultv/nanotrack/blob/main/README.md Installs the NanoTrack library using pip from the Python Package Index. ```bash pip install nanotrack ``` -------------------------------- ### Install NanoTrack from GitHub Source: https://github.com/ragultv/nanotrack/blob/main/README.md Installs the latest version of NanoTrack directly from its GitHub repository using pip. ```bash pip install git+https://github.com/ragultv/nanotrack.git ``` -------------------------------- ### Calculate IoU between bounding boxes in Python Source: https://context7.com/ragultv/nanotrack/llms.txt Utility method for calculating Intersection over Union between bounding boxes. Includes example usage with numpy arrays and demonstrates filtering detections by IoU threshold. Requires numpy and nanotrack package. ```python import numpy as np from nanotrack import NanoTrack # Define two bounding boxes [x1, y1, x2, y2] box1 = np.array([100, 100, 200, 200]) # 100x100 box box2 = np.array([150, 150, 250, 250]) # 100x100 box, overlapping # Calculate IoU iou_score = NanoTrack.iou(box1, box2) print(f"IoU between boxes: {iou_score:.4f}") # ~0.1429 # Example: Filter detections by IoU threshold detections = [ np.array([100, 100, 200, 200, 0.9, 0]), np.array([150, 150, 250, 250, 0.85, 0]), np.array([300, 300, 400, 400, 0.88, 0]) ] reference_box = np.array([110, 110, 210, 210]) iou_threshold = 0.3 matched_detections = [] for det in detections: iou = NanoTrack.iou(reference_box, det[:4]) if iou > iou_threshold: matched_detections.append(det) print(f"Matched detection with IoU: {iou:.4f}") print(f"Total matched: {len(matched_detections)} out of {len(detections)}") ``` -------------------------------- ### Initialize YOLOv8 Detector and NanoTrack Tracker Source: https://github.com/ragultv/nanotrack/blob/main/README.md Initializes the YOLOv8 detector with a specified model path and the NanoTrack tracker. This is the first step before processing video streams. ```python from nanotrack import YOLOv8Detector, NanoTrack import cv2 # Initialize the YOLOv8 Detector detector = YOLOv8Detector(model_path="yolov8n.pt") # Replace with your model path # Initialize the NanoTrack Tracker tracker = NanoTrack() ``` -------------------------------- ### Create a new branch for contribution Source: https://github.com/ragultv/nanotrack/blob/main/README.md Command to create a new Git branch for developing features or making changes to the NanoTrack repository. ```bash git checkout -b feature-branch ``` -------------------------------- ### Process Video with NanoTrack for Detection and Tracking Source: https://github.com/ragultv/nanotrack/blob/main/README.md Processes a video file or live stream using YOLOv8 for detection and NanoTrack for tracking. It draws bounding boxes and track IDs on the frames and displays the output. ```python # Load video file or webcam input cap = cv2.VideoCapture("path_to_video.mp4") # Replace with your video file path while True: ret, frame = cap.read() if not ret: break # Perform object detection detections = detector.detect(frame) # Update tracker with detections tracks = tracker.update(detections) # Draw bounding boxes and track IDs for track in tracks: x1, y1, x2, y2, _, _, track_id = track[:7] cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2) cv2.putText(frame, f"ID: {track_id}", (int(x1), int(y1) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 1) # Display the results cv2.imshow("NanoTrack", frame) # Press 'q' to exit if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() ``` -------------------------------- ### Real-Time Video Tracking Pipeline with NanoTrack and YOLOv8 Source: https://context7.com/ragultv/nanotrack/llms.txt Processes a video file using YOLOv8 for object detection and NanoTrack for tracking. It outputs a video file with bounding boxes and track IDs visualized. Dependencies include OpenCV and NanoTrack. ```python import cv2 from nanotrack import YOLOv8Detector, NanoTrack # Initialize detector and tracker detector = YOLOv8Detector( model_path="yolov8n.pt", conf_threshold=0.25 ) tracker = NanoTrack( iou_threshold=0.5, max_age=30, min_hits=3 ) # Open video source cap = cv2.VideoCapture("traffic_video.mp4") # Get video properties fps = int(cap.get(cv2.CAP_PROP_FPS)) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # Setup video writer fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter('output_tracked.mp4', fourcc, fps, (width, height)) frame_count = 0 try: while True: ret, frame = cap.read() if not ret: break frame_count += 1 # Detect objects in current frame detections = detector.detect(frame) # Update tracker with new detections tracks = tracker.update(detections) # Visualize results for track in tracks: x1, y1, x2, y2, conf, class_id, track_id = track[:7] # Draw bounding box cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2) # Draw track ID and confidence label = f"ID: {int(track_id)} | Conf: {conf:.2f}" cv2.putText(frame, label, (int(x1), int(y1) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2) # Add frame counter cv2.putText(frame, f"Frame: {frame_count} | Tracks: {len(tracks)}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) # Write frame and display out.write(frame) cv2.imshow('NanoTrack - Real-Time Tracking', frame) # Exit on 'q' key if cv2.waitKey(1) & 0xFF == ord('q'): break except KeyboardInterrupt: print("Tracking interrupted by user") finally: cap.release() out.release() cv2.destroyAllWindows() print(f"Processed {frame_count} frames") ``` -------------------------------- ### Initialize YOLOv8 Detector for Object Detection Source: https://context7.com/ragultv/nanotrack/llms.txt Initializes YOLOv8 object detector for real-time inference with custom confidence and IoU thresholds. Requires OpenCV and YOLOv8 model file. Processes images and returns bounding boxes with class IDs and confidence scores. Suitable for single image detection and supports both CPU and GPU processing. ```python import cv2 import numpy as np from nanotrack import YOLOv8Detector # Initialize detector with custom parameters detector = YOLOv8Detector( model_path="yolov8n.pt", device="cpu", # or "cuda" for GPU conf_threshold=0.25, iou_threshold=0.45 ) # Load an image image = cv2.imread("sample_image.jpg") # Perform detection detections = detector.detect(image) # Process results print(f"Detected {len(detections)} objects") for detection in detections: x1, y1, x2, y2, confidence, class_id = detection print(f"Class: {int(class_id)}, Confidence: {confidence:.2f}, Box: [{x1:.0f}, {y1:.0f}, {x2:.0f}, {y2:.0f}]") cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2) cv2.putText(image, f"Class {int(class_id)}: {confidence:.2f}", (int(x1), int(y1) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) cv2.imwrite("output_detection.jpg", image) ``` -------------------------------- ### Webcam Live Object Tracking with NanoTrack and YOLOv8 Source: https://context7.com/ragultv/nanotrack/llms.txt Performs real-time object tracking from a webcam feed using YOLOv8 for detection and NanoTrack for tracking. It displays the live feed with bounding boxes, track IDs, and calculated FPS. Requires OpenCV, NanoTrack, and a connected webcam. ```python import cv2 import time from nanotrack import YOLOv8Detector, NanoTrack # Initialize components detector = YOLOv8Detector(model_path="yolov8n.pt", device="cpu") tracker = NanoTrack(iou_threshold=0.5, max_age=10, min_hits=2) # Open webcam (0 is default camera) cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) prev_time = time.time() while cap.isOpened(): ret, frame = cap.read() if not ret: print("Failed to grab frame") break # Calculate FPS curr_time = time.time() fps = 1 / (curr_time - prev_time) prev_time = curr_time # Run detection and tracking detections = detector.detect(frame) tracks = tracker.update(detections) # Draw tracks for track in tracks: x1, y1, x2, y2, conf, class_id, track_id = track[:7] color = (int(track_id * 50) % 255, int(track_id * 100) % 255, int(track_id * 150) % 255) cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), color, 3) cv2.putText(frame, f"ID: {int(track_id)}", (int(x1), int(y1) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, color, 2) # Display FPS and track count cv2.putText(frame, f"FPS: {fps:.1f} | Tracks: {len(tracks)}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2) cv2.imshow('Webcam Tracking', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() ``` -------------------------------- ### Factory Function for YOLO Detector Creation in NanoTrack Source: https://context7.com/ragultv/nanotrack/llms.txt Provides a factory function `create_detector` to instantiate YOLOv5 and YOLOv8 detectors with unified configuration parameters. This allows for flexible detector selection and consistent usage across different YOLO versions. Requires NanoTrack and OpenCV. ```python from nanotrack.detector import create_detector import cv2 # Create YOLOv8 detector using factory detector_v8 = create_detector( model_path="yolov8n.pt", version="v8", device="cpu", conf_threshold=0.3, iou_threshold=0.5 ) # Create YOLOv5 detector using factory detector_v5 = create_detector( model_path="yolov5s.pt", version="v5", device="cpu", conf_threshold=0.3, iou_threshold=0.5 ) # Use either detector with the same interface image = cv2.imread("test_image.jpg") detections_v8 = detector_v8.detect(image) print(f"YOLOv8 detected {len(detections_v8)} objects") detections_v5 = detector_v5.detect(image) print(f"YOLOv5 detected {len(detections_v5)} objects") ``` -------------------------------- ### Batch video processing with tracking in Python Source: https://context7.com/ragultv/nanotrack/llms.txt Automated batch processing of video files with object tracking. Includes video I/O operations, detection processing, and tracking visualization. Requires OpenCV, numpy, and nanotrack package. ```python import cv2 import os from nanotrack import YOLOv8Detector, NanoTrack from pathlib import Path def process_video(video_path, output_dir, detector, tracker): """Process single video file with tracking""" cap = cv2.VideoCapture(video_path) if not cap.isOpened(): return {"error": "Failed to open video", "frames": 0} fps = int(cap.get(cv2.CAP_PROP_FPS)) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) output_path = os.path.join(output_dir, f"tracked_{Path(video_path).name}") fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter(output_path, fourcc, fps, (width, height)) frame_count = 0 total_tracks = 0 while True: ret, frame = cap.read() if not ret: break detections = detector.detect(frame) tracks = tracker.update(detections) total_tracks += len(tracks) frame_count += 1 # Draw tracks for track in tracks: x1, y1, x2, y2, conf, class_id, track_id = track[:7] cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2) cv2.putText(frame, f"ID: {int(track_id)}", (int(x1), int(y1) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2) out.write(frame) cap.release() out.release() return { "frames": frame_count, "avg_tracks": total_tracks / frame_count if frame_count > 0 else 0, "output": output_path } # Batch processing setup detector = YOLOv8Detector(model_path="yolov8n.pt") input_videos = ["video1.mp4", "video2.mp4", "video3.mp4"] output_directory = "tracked_videos" os.makedirs(output_directory, exist_ok=True) # Process each video results = {} for video_path in input_videos: print(f"Processing {video_path}...") # Create new tracker for each video tracker = NanoTrack(iou_threshold=0.5, max_age=30, min_hits=3) result = process_video(video_path, output_directory, detector, tracker) results[video_path] = result if "error" not in result: print(f" Completed: {result['frames']} frames, " f"avg {result['avg_tracks']:.1f} tracks/frame") else: print(f" Error: {result['error']}") print("\nBatch processing complete!") print(f"Processed {len([r for r in results.values() if 'error' not in r])} videos successfully") ``` -------------------------------- ### Initialize YOLOv5 Detector for Video Processing Source: https://context7.com/ragultv/nanotrack/llms.txt Initializes YOLOv5 object detector with built-in Non-Maximum Suppression for video stream processing. Requires OpenCV and YOLOv5 model file. Processes video frames and returns detection arrays with bounding box coordinates, confidence scores, and class IDs. Optimized for video file input with frame-by-frame detection capability. ```python import cv2 from nanotrack.detector import YOLOv5Detector # Initialize YOLOv5 detector detector = YOLOv5Detector( model_path="yolov5s.pt", device="cpu", conf_threshold=0.3, iou_threshold=0.5 ) # Load video capture cap = cv2.VideoCapture("input_video.mp4") ret, frame = cap.read() if ret: # Run detection on frame detections = detector.detect(frame) # Output format: [x1, y1, x2, y2, confidence, class_id] for det in detections: bbox = det[:4] conf = det[4] cls_id = int(det[5]) print(f"Detection: class={cls_id}, conf={conf:.3f}, bbox={bbox}") cap.release() ``` -------------------------------- ### Configure and Use NanoTrack Multi-Object Tracker Source: https://context7.com/ragultv/nanotrack/llms.txt Initializes and configures NanoTrack multi-object tracker with IoU-based matching and linear assignment for persistent track ID maintenance. Requires NumPy for array operations. Processes detection arrays across frames and returns confirmed tracks with IDs. Supports configurable track lifecycle parameters including maximum age, minimum hits threshold, and IoU matching threshold for robust tracking across occlusions. ```python from nanotrack import NanoTrack import numpy as np # Initialize tracker with custom parameters tracker = NanoTrack( iou_threshold=0.5, # Minimum IoU for matching detection to track max_age=5, # Frames to keep track alive without detection min_hits=3 # Minimum detections before track is confirmed ) # Simulate detections from three consecutive frames detections_frame1 = [ np.array([100, 100, 200, 200, 0.9, 0]), # [x1, y1, x2, y2, conf, class] np.array([300, 150, 400, 250, 0.85, 0]) ] detections_frame2 = [ np.array([105, 102, 205, 202, 0.88, 0]), # Same object moved slightly np.array([305, 152, 405, 252, 0.87, 0]) ] detections_frame3 = [ np.array([110, 105, 210, 205, 0.91, 0]), np.array([310, 155, 410, 255, 0.86, 0]) ] # Update tracker across frames tracks_1 = tracker.update(detections_frame1) print(f"Frame 1: {len(tracks_1)} confirmed tracks") # 0 (min_hits not reached) tracks_2 = tracker.update(detections_frame2) print(f"Frame 2: {len(tracks_2)} confirmed tracks") # 0 (min_hits not reached) tracks_3 = tracker.update(detections_frame3) print(f"Frame 3: {len(tracks_3)} confirmed tracks") # 2 (min_hits reached) for track in tracks_3: x1, y1, x2, y2, conf, class_id, track_id = track[:7] print(f"Track ID: {track_id}, Position: [{x1:.0f}, {y1:.0f}, {x2:.0f}, {y2:.0f}]") ``` -------------------------------- ### Error handling for invalid version in Python Source: https://context7.com/ragultv/nanotrack/llms.txt Demonstrates handling invalid version inputs when creating a detector. Catches ValueError exceptions and prints user-friendly error messages. Requires version to be either 'v5' or 'v8'. ```python try: invalid_detector = create_detector("model.pt", version="v7") except ValueError as e: print(f"Error: {e}") # "Version must be 'v5' or 'v8'" ``` -------------------------------- ### NanoTrack Class Source: https://context7.com/ragultv/nanotrack/llms.txt The NanoTrack class implements multi-object tracking using IoU-based matching and linear assignment. It maintains persistent track IDs across frames, handles occlusions with track aging, and supports velocity prediction. Configure parameters to control track lifecycle and matching. ```APIDOC ## NanoTrack ### Description Multi-object tracker that maintains persistent track IDs using IoU-based matching and linear assignment. Configurable parameters control track lifecycle and matching behavior. ### Method Class Initialization: NanoTrack() and update() ### Endpoint N/A (Python Class) ### Parameters #### Initialization Parameters - **iou_threshold** (float) - Optional - Minimum IoU for matching detection to track (default: 0.5) - **max_age** (int) - Optional - Frames to keep track alive without detection (default: 5) - **min_hits** (int) - Optional - Minimum detections before track is confirmed (default: 3) #### Update Method Parameters - **detections** (list of np.arrays) - Required - List of detection arrays [x1, y1, x2, y2, conf, class] ### Request Example ```python from nanotrack import NanoTrack import numpy as np tracker = NanoTrack( iou_threshold=0.5, max_age=5, min_hits=3 ) detections_frame1 = [ np.array([100, 100, 200, 200, 0.9, 0]), np.array([300, 150, 400, 250, 0.85, 0]) ] ``` ### Response #### Success Response - **tracks** (list of arrays) - List of track arrays: [x1, y1, x2, y2, conf, class_id, track_id, ...] #### Response Example ```python tracks_1 = tracker.update(detections_frame1) print(f"Frame 1: {len(tracks_1)} confirmed tracks") # Similar for frame2 and frame3 for track in tracks_3: x1, y1, x2, y2, conf, class_id, track_id = track[:7] print(f"Track ID: {track_id}, Position: [{x1:.0f}, {y1:.0f}, {x2:.0f}, {y2:.0f}]") ``` ``` -------------------------------- ### YOLOv8Detector Class Source: https://context7.com/ragultv/nanotrack/llms.txt The YOLOv8Detector class wraps YOLOv8 models for real-time object detection. It supports custom confidence thresholds, IoU settings for NMS, and device selection (CPU or GPU). Use this class to perform inference on images or video frames. ```APIDOC ## YOLOv8Detector ### Description Object detector class that wraps YOLOv8 models for real-time inference. Supports custom confidence thresholds, IoU settings for NMS, and device selection for CPU or GPU processing. ### Method Class Initialization: YOLOv8Detector() ### Endpoint N/A (Python Class) ### Parameters #### Initialization Parameters - **model_path** (string) - Required - Path to the YOLOv8 model file (e.g., "yolov8n.pt") - **device** (string) - Optional - Device for processing ("cpu" or "cuda") - **conf_threshold** (float) - Optional - Confidence threshold for detections (default: 0.25) - **iou_threshold** (float) - Optional - IoU threshold for NMS (default: 0.45) ### Request Example ```python import cv2 import numpy as np from nanotrack import YOLOv8Detector detector = YOLOv8Detector( model_path="yolov8n.pt", device="cpu", conf_threshold=0.25, iou_threshold=0.45 ) image = cv2.imread("sample_image.jpg") ``` ### Response #### Success Response - **detections** (list of arrays) - List of detection arrays, each containing [x1, y1, x2, y2, confidence, class_id] #### Response Example ```python detections = detector.detect(image) print(f"Detected {len(detections)} objects") for detection in detections: x1, y1, x2, y2, confidence, class_id = detection print(f"Class: {int(class_id)}, Confidence: {confidence:.2f}, Box: [{x1:.0f}, {y1:.0f}, {x2:.0f}, {y2:.0f}]") ``` ``` -------------------------------- ### YOLOv5Detector Class Source: https://context7.com/ragultv/nanotrack/llms.txt The YOLOv5Detector class handles object detection with YOLOv5 models, including built-in Non-Maximum Suppression. It offers the same interface as YOLOv8Detector for easy model switching. Ideal for processing video frames or images. ```APIDOC ## YOLOv5Detector ### Description Object detector class for YOLOv5 models with built-in Non-Maximum Suppression. Provides the same interface as YOLOv8Detector for seamless model switching. ### Method Class Initialization: YOLOv5Detector() ### Endpoint N/A (Python Class) ### Parameters #### Initialization Parameters - **model_path** (string) - Required - Path to the YOLOv5 model file (e.g., "yolov5s.pt") - **device** (string) - Optional - Device for processing ("cpu") - **conf_threshold** (float) - Optional - Confidence threshold (default: 0.3) - **iou_threshold** (float) - Optional - IoU threshold for NMS (default: 0.5) ### Request Example ```python import cv2 from nanotrack.detector import YOLOv5Detector detector = YOLOv5Detector( model_path="yolov5s.pt", device="cpu", conf_threshold=0.3, iou_threshold=0.5 ) cap = cv2.VideoCapture("input_video.mp4") ret, frame = cap.read() ``` ### Response #### Success Response - **detections** (list of arrays) - List of detection arrays: [x1, y1, x2, y2, confidence, class_id] #### Response Example ```python if ret: detections = detector.detect(frame) for det in detections: bbox = det[:4] conf = det[4] cls_id = int(det[5]) print(f"Detection: class={cls_id}, conf={conf:.3f}, bbox={bbox}") cap.release() ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.