File size: 8,421 Bytes
7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 0b0ba5e 7e56761 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
#!/usr/bin/env python3
"""
RF-DETR SoccerNet - Complete Usage Examples
This script demonstrates how to use the RF-DETR SoccerNet model for soccer analysis.
Shows image processing, data analysis, and visualization using included sample files.
"""
import os
import sys
import pandas as pd
import numpy as np
from pathlib import Path
# Import our RF-DETR SoccerNet class
from inference import RFDETRSoccerNet
def basic_image_analysis():
"""Basic image processing example using included sample."""
print("๐ผ๏ธ BASIC IMAGE ANALYSIS EXAMPLE")
print("=" * 50)
# Initialize model (automatically detects CUDA/CPU)
print("Loading RF-DETR SoccerNet model...")
model = RFDETRSoccerNet()
# Process sample image (included in repository)
image_path = "examples/sample_soccer_frame.jpg"
if not os.path.exists(image_path):
print(f"โ ๏ธ Sample image not found: {image_path}")
print("Please run this script from the repository root directory.")
return None
print(f"Processing sample image: {image_path}")
# Run inference on single image
df = model.process_image(
image_path=image_path,
confidence_threshold=0.5
)
# Display results
print(f"\n๐ ANALYSIS RESULTS")
print(f"Total detections: {len(df):,}")
if len(df) > 0:
# Show detections by class
print(f"\n๐ฏ Detections by class:")
class_stats = df['class_name'].value_counts()
for class_name, count in class_stats.items():
avg_conf = df[df['class_name'] == class_name]['confidence'].mean()
print(f" {class_name}: {count} (avg confidence: {avg_conf:.3f})")
# Save results
print(f"\n๐พ Saving results...")
model.save_results(df, "image_analysis.csv", format="csv")
model.save_results(df, "image_analysis.json", format="json")
else:
print("No detections found. Try lowering the confidence threshold.")
return df
def analyze_sample_data():
"""Analyze sample detection data included in repository."""
print("\n๐ SAMPLE DATA ANALYSIS EXAMPLE")
print("=" * 50)
# Load sample detection data
csv_path = "examples/sample_detections.csv"
if not os.path.exists(csv_path):
print(f"โ ๏ธ Sample data not found: {csv_path}")
print("Please run this script from the repository root directory.")
return None
print(f"Loading sample detection data: {csv_path}")
df = pd.read_csv(csv_path)
# Basic statistics
print(f"\n๐ Dataset Statistics:")
print(f" Total detections: {len(df):,}")
print(f" Frames: {df['frame'].nunique()}")
print(f" Time span: {df['timestamp'].min():.2f}s - {df['timestamp'].max():.2f}s")
# Class distribution
print(f"\n๐ฏ Class Distribution:")
class_counts = df['class_name'].value_counts()
for class_name, count in class_counts.items():
percentage = (count / len(df)) * 100
avg_conf = df[df['class_name'] == class_name]['confidence'].mean()
print(f" {class_name}: {count} ({percentage:.1f}%) | Avg confidence: {avg_conf:.3f}")
# Confidence analysis
print(f"\n๐ Confidence Analysis:")
print(f" Overall mean: {df['confidence'].mean():.3f}")
print(f" Overall std: {df['confidence'].std():.3f}")
print(f" Range: {df['confidence'].min():.3f} - {df['confidence'].max():.3f}")
# Object size analysis
print(f"\n๐ Object Size Analysis:")
df['area'] = df['width'] * df['height']
for class_name in df['class_name'].unique():
class_data = df[df['class_name'] == class_name]
avg_area = class_data['area'].mean()
print(f" {class_name}: {avg_area:.1f} pxยฒ average area")
return df
def ball_possession_example():
"""Demonstrate ball possession analysis using sample data."""
print("\nโฝ BALL POSSESSION ANALYSIS EXAMPLE")
print("=" * 50)
# Load sample data
csv_path = "examples/sample_detections.csv"
if not os.path.exists(csv_path):
print(f"โ ๏ธ Sample data not found: {csv_path}")
return None
df = pd.read_csv(csv_path)
# Initialize model for possession analysis
model = RFDETRSoccerNet()
print("Analyzing ball possession...")
possession_df = model.analyze_ball_possession(df, distance_threshold=150)
if len(possession_df) > 0:
print(f"\n๐ Possession Analysis Results:")
print(f" Possession events: {len(possession_df)}")
print(f" Average distance to ball: {possession_df['distance_to_ball'].mean():.1f} pixels")
print(f" Frames with possession: {possession_df['frame'].nunique()}")
# Save possession analysis
model.save_results(possession_df, "ball_possession_analysis.csv")
print(f"๐พ Possession analysis saved to: ball_possession_analysis.csv")
else:
print("No possession events found. Try increasing the distance threshold.")
return possession_df
def visualization_example():
"""Show how to work with detection visualizations."""
print("\n๐จ VISUALIZATION EXAMPLE")
print("=" * 50)
# Check if visualization example exists
viz_path = "examples/detection_visualization.jpg"
if os.path.exists(viz_path):
print(f"โ
Sample visualization available: {viz_path}")
print("This image shows detected objects with bounding boxes and labels.")
print("Colors: Red=Ball, Green=Player, Yellow=Referee, Cyan=Goalkeeper")
# Get file size
file_size = os.path.getsize(viz_path) / (1024 * 1024) # MB
print(f"๐ Visualization size: {file_size:.2f} MB")
else:
print(f"โ ๏ธ Visualization not found: {viz_path}")
print("You can create visualizations by drawing bounding boxes on images.")
# Example of how to create visualizations programmatically
print(f"\n๐ก To create your own visualizations:")
print("1. Use cv2.rectangle() to draw bounding boxes")
print("2. Use cv2.putText() to add labels")
print("3. Use different colors for each class")
print("4. Save with cv2.imwrite()")
def advanced_usage_tips():
"""Show advanced usage patterns and tips."""
print("\n๐ ADVANCED USAGE TIPS")
print("=" * 50)
print("๐ Model Configuration:")
print(" - Use confidence_threshold=0.3 for more detections")
print(" - Use confidence_threshold=0.7 for higher precision")
print(" - Process every N frames: frame_skip=N for faster analysis")
print(f"\nโก Performance Tips:")
print(" - GPU acceleration: Model automatically uses CUDA if available")
print(" - Batch processing: Process multiple images in sequence")
print(" - Memory: Large videos may need max_frames limit")
print(f"\n๐ Data Export Options:")
print(" - CSV: Best for spreadsheet analysis")
print(" - JSON: Best for web applications")
print(" - Parquet: Best for large datasets")
print(f"\n๐ฏ Use Cases:")
print(" - Player tracking and formation analysis")
print(" - Ball possession and movement statistics")
print(" - Referee positioning analysis")
print(" - Automated highlight generation")
print(" - Broadcast enhancement")
def main():
"""Run all examples in sequence."""
print("๐ RF-DETR SOCCERNET - COMPLETE EXAMPLES")
print("=" * 60)
print("This script demonstrates all features using included sample files.")
print("No external videos or images required!")
print("=" * 60)
try:
# Run all examples
image_results = basic_image_analysis()
sample_analysis = analyze_sample_data()
possession_results = ball_possession_example()
visualization_example()
advanced_usage_tips()
print(f"\n๐ ALL EXAMPLES COMPLETED SUCCESSFULLY!")
print("Check the generated files:")
print(" - image_analysis.csv")
print(" - image_analysis.json")
print(" - ball_possession_analysis.csv")
except Exception as e:
print(f"\nโ Error running examples: {e}")
print("Make sure you're running from the repository root directory.")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main() |