This is a great request for optimizing YOLO object detection in video inference. Let me create a comprehensive solution that covers:
-
Multiprocessing architecture with separate processes for:
- Frame reading/capturing
- Frame inference using YOLO
- Frame display/visualization
-
Queue management to decouple these processes
-
Frame skipping logic to handle when inference falls behind, dropping old frames and jumping to the latest
-
Frame synchronization between processes
-
Resource management (GPU/CPU, memory)
Let me build a robust solution with:
- Clear separation of concerns
- Proper queue management with size limits
- Frame skipping mechanism
- FPS tracking and monitoring
- Graceful shutdown
- Error handling
- Configuration options
- Example usage with different video sources
I'll provide multiple implementations:
- Basic version with core functionality
- Advanced version with more features
- Configuration class
- Utility functions
- Example usage with benchmarking
Let me structure this well:
# Core classes and functions:
1. FrameBuffer - manages queues and frame skipping
2. FrameReader - reads frames from video/camera
3. FrameInference - performs YOLO inference
4. FrameDisplay - displays results
5. VideoProcessor - orchestrates everything
6. Config - configuration management
Let me write comprehensive code with:
- Proper synchronization primitives
- Performance monitoring
- Flexible configuration
- Multiple video source support
- GPU batching options
- Adaptive frame skipping
YOLO Multiprocessing Video Inference with Frame Skipping
I'll create a complete optimized solution with frame skipping, queue management, and multiprocessing:
1. Core Implementation
import cv2
import numpy as np
from ultralytics import YOLO
from multiprocessing import Process, Queue, Value, Lock
from queue import Empty, Full
from collections import deque
import time
import threading
from dataclasses import dataclass
from typing import Optional, Tuple, Dict
import logging
from pathlib import Path
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class FrameData:
"""Container for frame and metadata"""
frame: np.ndarray
frame_id: int
timestamp: float
original_index: int = 0
@dataclass
class Config:
"""Configuration for video processing"""
model_path: str = "yolov8n.pt"
video_source: str = "0" # 0 for webcam, or video file path
input_queue_size: int = 2
output_queue_size: int = 5
inference_batch_size: int = 1
frame_skip_threshold: int = 2 # Skip frames if queue has > N frames
confidence_threshold: float = 0.5
max_workers: int = 1
display_fps: bool = True
save_video: bool = False
output_path: str = "output.mp4"
device: str = "0" # GPU device
imgsz: int = 416
# Performance
frame_read_timeout: float = 2.0
inference_timeout: float = 5.0
# Frame skipping strategy
adaptive_skip: bool = True
min_skip_interval: int = 1
max_skip_interval: int = 10
class FrameBuffer:
"""Manages frame queues with intelligent skipping"""
def __init__(self, config: Config):
self.config = config
self.input_queue = Queue(maxsize=config.input_queue_size)
self.output_queue = Queue(maxsize=config.output_queue_size)
# Metrics
self.frames_read = Value('i', 0)
self.frames_processed = Value('i', 0)
self.frames_skipped = Value('i', 0)
self.lock = Lock()
# Frame tracking
self.last_frame_id = Value('i', -1)
self.skip_interval = Value('i', config.min_skip_interval)
def should_skip_frame(self) -> bool:
"""Determine if current frame should be skipped"""
try:
queue_size = self.input_queue.qsize()
if queue_size > self.config.frame_skip_threshold:
if self.config.adaptive_skip:
# Increase skip interval dynamically
new_interval = min(
self.skip_interval.value + 1,
self.config.max_skip_interval
)
self.skip_interval.value = new_interval
return True
else:
return True
else:
# Decrease skip interval when caught up
if self.skip_interval.value > self.config.min_skip_interval:
self.skip_interval.value = max(
self.skip_interval.value - 1,
self.config.min_skip_interval
)
return False
except:
return False
def put_frame(self, frame_data: FrameData, timeout: float = 1.0) -> bool:
"""Put frame in input queue"""
try:
self.input_queue.put(frame_data, timeout=timeout)
with self.lock:
self.frames_read.value += 1
return True
except Full:
logger.warning("Input queue full, dropping frame")
return False
def get_frame(self, timeout: float = 1.0) -> Optional[FrameData]:
"""Get frame from input queue"""
try:
return self.input_queue.get(timeout=timeout)
except Empty:
return None
def put_result(self, frame_data: FrameData, timeout: float = 1.0) -> bool:
"""Put processed frame in output queue"""
try:
self.output_queue.put(frame_data, timeout=timeout)
with self.lock:
self.frames_processed.value += 1
return True
except Full:
logger.warning("Output queue full")
return False
def get_result(self, timeout: float = 0.1) -> Optional[FrameData]:
"""Get processed frame from output queue"""
try:
return self.output_queue.get(timeout=timeout)
except Empty:
return None
def get_stats(self) -> Dict:
"""Get processing statistics"""
with self.lock:
return {
'frames_read': self.frames_read.value,
'frames_processed': self.frames_processed.value,
'frames_skipped': self.frames_skipped.value,
'input_queue_size': self.input_queue.qsize(),
'output_queue_size': self.output_queue.qsize(),
'skip_interval': self.skip_interval.value,
}
class FrameReader(Process):
"""Reads frames from video source"""
def __init__(self, buffer: FrameBuffer, config: Config):
super().__init__(daemon=True)
self.buffer = buffer
self.config = config
self.running = True
def run(self):
"""Main loop for frame reading"""
try:
# Open video source
source = self.config.video_source
if source.isdigit():
source = int(source)
cap = cv2.VideoCapture(source)
if not cap.isOpened():
logger.error(f"Failed to open video source: {source}")
return
frame_id = 0
frame_count = 0
skip_counter = 0
logger.info(f"Video Reader started - Source: {source}")
while self.running:
ret, frame = cap.read()
if not ret:
logger.info("End of video reached or failed to read frame")
break
frame_count += 1
skip_counter += 1
# Apply frame skipping based on inference lag
if self.buffer.should_skip_frame():
if skip_counter >= self.buffer.skip_interval.value:
skip_counter = 0
else:
with self.buffer.lock:
self.buffer.frames_skipped.value += 1
continue
# Create frame data
frame_data = FrameData(
frame=frame.copy(),
frame_id=frame_id,
timestamp=time.time(),
original_index=frame_count - 1
)
# Put in queue
if self.buffer.put_frame(frame_data,
timeout=self.config.frame_read_timeout):
frame_id += 1
else:
# Queue full, skip this frame
with self.buffer.lock:
self.buffer.frames_skipped.value += 1
cap.release()
logger.info(f"Video Reader stopped - Total frames: {frame_count}")
except Exception as e:
logger.error(f"Error in frame reader: {e}", exc_info=True)
finally:
self.running = False
class FrameInference(Process):
"""Performs YOLO inference on frames"""
def __init__(self, buffer: FrameBuffer, config: Config, worker_id: int = 0):
super().__init__(daemon=True)
self.buffer = buffer
self.config = config
self.worker_id = worker_id
self.running = True
def run(self):
"""Main loop for inference"""
try:
# Load YOLO model
model = YOLO(self.config.model_path)
model.to(f"cuda:{self.config.device}")
logger.info(f"Inference Worker {self.worker_id} started")
while self.running:
# Get frame from input queue
frame_data = self.buffer.get_frame(
timeout=self.config.inference_timeout
)
if frame_data is None:
continue
try:
# Run inference
results = model(
frame_data.frame,
conf=self.config.confidence_threshold,
imgsz=self.config.imgsz,
verbose=False
)
# Annotate frame
annotated_frame = results[0].plot()
# Store results
frame_data.frame = annotated_frame
frame_data.results = results
# Put in output queue
self.buffer.put_result(frame_data)
except Exception as e:
logger.error(f"Error during inference: {e}")
continue
logger.info(f"Inference Worker {self.worker_id} stopped")
except Exception as e:
logger.error(f"Error in inference worker: {e}", exc_info=True)
finally:
self.running = False
class FrameDisplay(Process):
"""Displays processed frames"""
def __init__(self, buffer: FrameBuffer, config: Config):
super().__init__(daemon=True)
self.buffer = buffer
self.config = config
self.running = True
def run(self):
"""Main loop for display"""
try:
logger.info("Display process started")
# Setup video writer if saving
writer = None
frame_size = None
fps_deque = deque(maxlen=30)
last_time = time.time()
frame_count = 0
while self.running:
# Get processed frame
frame_data = self.buffer.get_result(timeout=0.1)
if frame_data is None:
continue
frame = frame_data.frame
# Setup video writer with first frame
if writer is None and self.config.save_video:
frame_size = (frame.shape[1], frame.shape[0])
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
writer = cv2.VideoWriter(
self.config.output_path,
fourcc,
30.0,
frame_size
)
# Calculate FPS
current_time = time.time()
fps = 1.0 / (current_time - last_time) if (current_time - last_time) > 0 else 0
fps_deque.append(fps)
last_time = current_time
avg_fps = np.mean(fps_deque)
# Add FPS and stats to frame
if self.config.display_fps:
stats = self.buffer.get_stats()
text_lines = [
f"FPS: {avg_fps:.1f}",
f"Queue: {stats['input_queue_size']}/{self.config.input_queue_size}",
f"Skip: {stats['frames_skipped']} (interval: {stats['skip_interval']})",
]
for i, text in enumerate(text_lines):
cv2.putText(
frame, text,
(10, 30 + i * 25),
cv2.FONT_HERSHEY_SIMPLEX,
0.7, (0, 255, 0), 2
)
# Save to video file
if writer is not None:
writer.write(frame)
# Display frame
cv2.imshow('YOLO Detection', frame)
frame_count += 1
# Break on 'q' key
if cv2.waitKey(1) & 0xFF == ord('q'):
self.running = False
# Cleanup
if writer is not None:
writer.release()
cv2.destroyAllWindows()
logger.info(f"Display process stopped - Total frames: {frame_count}")
except Exception as e:
logger.error(f"Error in display process: {e}", exc_info=True)
finally:
self.running = False
class VideoProcessor:
"""Orchestrates multi-process video processing"""
def __init__(self, config: Config):
self.config = config
self.buffer = FrameBuffer(config)
self.processes = []
def start(self):
"""Start all processes"""
logger.info("Starting video processor")
# Start frame reader
reader = FrameReader(self.buffer, self.config)
reader.start()
self.processes.append(reader)
# Start inference workers
for i in range(self.config.max_workers):
worker = FrameInference(self.buffer, self.config, worker_id=i)
worker.start()
self.processes.append(worker)
# Start display process
display = FrameDisplay(self.buffer, self.config)
display.start()
self.processes.append(display)
logger.info(f"Started {len(self.processes)} processes")
# Monitor performance
self._monitor()
def _monitor(self):
"""Monitor and log performance metrics"""
try:
while any(p.is_alive() for p in self.processes):
time.sleep(5)
stats = self.buffer.get_stats()
logger.info(
f"Stats - Read: {stats['frames_read']}, "
f"Processed: {stats['frames_processed']}, "
f"Skipped: {stats['frames_skipped']}, "
f"Queues: {stats['input_queue_size']}/{self.config.input_queue_size}, "
f"Skip interval: {stats['skip_interval']}"
)
except KeyboardInterrupt:
self.stop()
def stop(self):
"""Stop all processes gracefully"""
logger.info("Stopping video processor")
# Terminate processes
for process in self.processes:
if process.is_alive():
process.terminate()
process.join(timeout=2)
if process.is_alive():
process.kill()
process.join()
logger.info("Video processor stopped")
2. Advanced Features - Batch Processing
class BatchFrameInference(Process):
"""YOLO inference with frame batching"""
def __init__(self, buffer: FrameBuffer, config: Config, worker_id: int = 0):
super().__init__(daemon=True)
self.buffer = buffer
self.config = config
self.worker_id = worker_id
self.running = True
def run(self):
"""Main loop with batch processing"""
try:
model = YOLO(self.config.model_path)
model.to(f"cuda:{self.config.device}")
batch_size = self.config.inference_batch_size
frame_batch = []
timeout_counter = 0
logger.info(f"Batch Inference Worker {self.worker_id} started")
while self.running:
# Collect frames for batch
frame_data = self.buffer.get_frame(timeout=0.5)
if frame_data is not None:
frame_batch.append(frame_data)
timeout_counter = 0
else:
timeout_counter += 1
# Process batch when full or timeout
should_process = (
len(frame_batch) >= batch_size or
(timeout_counter > 2 and len(frame_batch) > 0)
)
if should_process:
self._process_batch(model, frame_batch)
frame_batch = []
logger.info(f"Batch Inference Worker {self.worker_id} stopped")
except Exception as e:
logger.error(f"Error in batch inference: {e}", exc_info=True)
def _process_batch(self, model, frame_batch):
"""Process batch of frames"""
try:
frames = [fd.frame for fd in frame_batch]
results = model(
frames,
conf=self.config.confidence_threshold,
imgsz=self.config.imgsz,
verbose=False
)
for frame_data, result in zip(frame_batch, results):
frame_data.frame = result.plot()
frame_data.results = [result]
self.buffer.put_result(frame_data)
except Exception as e:
logger.error(f"Error processing batch: {e}")
# Put frames back in queue on error
for frame_data in frame_batch:
self.buffer.put_result(frame_data)
3. Usage Examples
# Basic usage
if __name__ == "__main__":
# Webcam inference
config = Config(
video_source="0",
model_path="yolov8n.pt",
input_queue_size=2,
output_queue_size=5,
max_workers=2,
adaptive_skip=True,
)
processor = VideoProcessor(config)
processor.start()
# Video file with batching
def process_video_file():
config = Config(
video_source="video.mp4",
model_path="yolov8m.pt",
input_queue_size=3,
output_queue_size=8,
max_workers=2,
inference_batch_size=2,
frame_skip_threshold=3,
adaptive_skip=True,
save_video=True,
output_path="output_detected.mp4",
device="0"
)
processor = VideoProcessor(config)
processor.start()
# Custom configuration with GPU optimization
def process_with_gpu_optimization():
config = Config(
video_source="0",
model_path="yolov8l.pt", # Larger model on GPU
input_queue_size=1, # Tight input queue
output_queue_size=10, # Larger output for display flexibility
max_workers=1, # Single inference process for GPU
inference_batch_size=4, # Batch processing
frame_skip_threshold=2,
adaptive_skip=True,
imgsz=640,
device="0"
)
processor = VideoProcessor(config)
processor.start()
# Benchmark different configurations
def benchmark():
configs = [
Config(
video_source="test_video.mp4",
max_workers=1,
inference_batch_size=1,
adaptive_skip=False,
),
Config(
video_source="test_video.mp4",
max_workers=1,
inference_batch_size=2,
adaptive_skip=True,
),
Config(
video_source="test_video.mp4",
max_workers=2,
inference_batch_size=1,
adaptive_skip=True,
),
]
for i, config in enumerate(configs):
logger.info(f"\n=== Benchmark Config {i+1} ===")
logger.info(f"Workers: {config.max_workers}, Batch: {config.inference_batch_size}")
processor = VideoProcessor(config)
processor.start()
4. Performance Monitoring Utilities
class PerformanceMonitor:
"""Track and analyze performance metrics"""
def __init__(self, buffer: FrameBuffer):
self.buffer = buffer
self.metrics_history = deque(maxlen=100)
def record_metrics(self):
"""Record current metrics"""
stats = self.buffer.get_stats()
stats['timestamp'] = time.time()
self.metrics_history.append(stats)
def get_throughput(self):
"""Calculate frames per second"""
if len(self.metrics_history) < 2:
return 0
first = self.metrics_history[0]
last = self.metrics_history[-1]
time_diff = last['timestamp'] - first['timestamp']
frame_diff = last['frames_processed'] - first['frames_processed']
return frame_diff / time_diff if time_diff > 0 else 0
def get_latency(self):
"""Estimate average latency"""
stats = self.metrics_history[-1]
queue_size = stats['input_queue_size']
return queue_size * (1.0 / 30) # Assuming 30 FPS
def print_report(self):
"""Print performance report"""
if not self.metrics_history:
return
stats = self.metrics_history[-1]
print("\n" + "="*50)
print("PERFORMANCE REPORT")
print("="*50)
print(f"Frames Read: {stats['frames_read']}")
print(f"Frames Processed: {stats['frames_processed']}")
print(f"Frames Skipped: {stats['frames_skipped']}")
print(f"Throughput: {self.get_throughput():.2f} FPS")
print(f"Latency: {self.get_latency():.2f}s")
print(f"Input Queue: {stats['input_queue_size']}/{self.buffer.config.input_queue_size}")
print(f"Output Queue: {stats['output_queue_size']}/{self.buffer.config.output_queue_size}")
print(f"Skip Interval: {stats['skip_interval']}")
print("="*50 + "\n")
# Real-time monitoring with threading
class MonitorThread(threading.Thread):
"""Background monitoring thread"""
def __init__(self, processor: VideoProcessor, interval: int = 10):
super().__init__(daemon=True)
self.processor = processor
self.interval = interval
self.monitor = PerformanceMonitor(processor.buffer)
self.running = True
def run(self):
while self.running:
self.monitor.record_metrics()
time.sleep(self.interval)
def stop(self):
self.running = False
def print_stats(self):
self.monitor.print_report()
5. Complete Example with Monitoring
def main():
"""Complete example with monitoring"""
config = Config(
video_source="0",
model_path="yolov8n.pt",
input_queue_size=2,
output_queue_size=5,
max_workers=1,
inference_batch_size=1,
adapter_skip=True,
confidence_threshold=0.5,
display_fps=True,
)
processor = VideoProcessor(config)
# Start monitoring
monitor = MonitorThread(processor, interval=5)
monitor.start()
try:
processor.start()
except KeyboardInterrupt:
logger.info("Interrupted by user")
finally:
monitor.stop()
monitor.print_stats()
if __name__ == "__main__":
main()
6. Advanced Frame Skipping Strategy
class AdaptiveFrameSkipper:
"""Advanced frame skipping with multiple strategies"""
def __init__(self, config: Config):
self.config = config
self.skip_interval = config.min_skip_interval
self.queue_history = deque(maxlen=10)
self.inference_times = deque(maxlen=50)
def calculate_optimal_skip(self, queue_size: int,
inference_time: float) -> int:
"""Calculate optimal skip interval"""
self.queue_history.append(queue_size)
self.inference_times.append(inference_time)
# Predict frames arriving while processing
avg_inference_time = np.mean(self.inference_times)
frames_arriving = avg_inference_time * 30 # Assume 30 FPS input
# Calculate skip to prevent queue growth
if queue_size > self.config.frame_skip_threshold:
skip = max(1, int(frames_arriving / 2))
skip = min(skip, self.config.max_skip_interval)
else:
skip = self.config.min_skip_interval
return skip
Key Features:
✅ Multiprocessing: Separate processes for reading, inference, display
✅ Frame Skipping: Adaptive frame dropping when behind
✅ Queue Management: Prevents queue overflow
✅ Performance Monitoring: Real-time FPS and metrics
✅ GPU Acceleration: Batch processing support
✅ Graceful Shutdown: Proper cleanup
✅ Video Saving: Optional output video file
✅ Configurable: Flexible configuration class
✅ Error Handling: Comprehensive error management
✅ Latency Reduction: Minimizes end-to-end latency
This implementation ensures real-time performance even with heavy inference loads!