Spaces:
Sleeping
Sleeping
File size: 8,732 Bytes
3b90d9c | 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 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | """
Visualization utilities for ball tracking.
This module provides functions for rendering bounding boxes, trajectories,
and creating 2D trajectory plots with speed-based color coding.
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from typing import List, Tuple, Optional
from matplotlib.figure import Figure
def draw_detection(
frame: np.ndarray,
detection: Tuple[int, int, int, int, float],
color: Tuple[int, int, int] = (0, 255, 0),
thickness: int = 2
) -> np.ndarray:
"""
Draw a bounding box for a detection on the frame.
Args:
frame: Input frame (BGR format)
detection: Bounding box as (x1, y1, x2, y2, confidence)
color: Box color in BGR format
thickness: Line thickness
Returns:
Frame with drawn bounding box
"""
x1, y1, x2, y2, conf = detection
# Draw rectangle
cv2.rectangle(frame, (x1, y1), (x2, y2), color, thickness)
# Draw confidence label
label = f"{conf:.2f}"
label_size, _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
label_y = max(y1 - 10, label_size[1])
cv2.rectangle(
frame,
(x1, label_y - label_size[1] - 5),
(x1 + label_size[0], label_y + 5),
color,
-1
)
cv2.putText(
frame,
label,
(x1, label_y),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
(0, 0, 0),
1
)
return frame
def draw_trajectory_trail(
frame: np.ndarray,
positions: List[Tuple[float, float]],
color: Tuple[int, int, int] = (0, 255, 255),
max_points: int = 20
) -> np.ndarray:
"""
Draw a trail showing recent ball positions.
Args:
frame: Input frame (BGR format)
positions: List of (x, y) positions (most recent last)
color: Trail color in BGR format
max_points: Maximum number of points to show
Returns:
Frame with drawn trajectory trail
"""
if len(positions) < 2:
return frame
# Use only recent positions
recent = positions[-max_points:]
# Draw lines connecting positions with fading effect
for i in range(1, len(recent)):
# Calculate alpha (opacity) based on position in trail
alpha = i / len(recent)
# Blend color with background
pt1 = (int(recent[i - 1][0]), int(recent[i - 1][1]))
pt2 = (int(recent[i][0]), int(recent[i][1]))
# Draw line with thickness varying by position
thickness = max(1, int(2 * alpha))
line_color = tuple(int(c * alpha) for c in color)
cv2.line(frame, pt1, pt2, line_color, thickness, cv2.LINE_AA)
# Draw circle at current position
if len(recent) > 0:
curr_pos = (int(recent[-1][0]), int(recent[-1][1]))
cv2.circle(frame, curr_pos, 5, color, -1, cv2.LINE_AA)
return frame
def draw_speed_label(
frame: np.ndarray,
position: Tuple[float, float],
speed: float,
fps: float,
color: Tuple[int, int, int] = (255, 255, 255)
) -> np.ndarray:
"""
Draw speed information near the ball position.
Args:
frame: Input frame (BGR format)
position: Ball position as (x, y)
speed: Speed in pixels per second
fps: Video frame rate
color: Text color in BGR format
Returns:
Frame with speed label
"""
x, y = int(position[0]), int(position[1])
# Convert pixel speed to approximate real-world units
# (This is a rough estimate; proper conversion requires camera calibration)
speed_kmh = speed * 0.01 # Rough approximation
label = f"{speed_kmh:.1f} km/h"
# Draw label with background
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.6
thickness = 2
label_size, _ = cv2.getTextSize(label, font, font_scale, thickness)
# Position label above the ball
label_x = x - label_size[0] // 2
label_y = y - 20
# Ensure label stays within frame
label_x = max(0, min(label_x, frame.shape[1] - label_size[0]))
label_y = max(label_size[1] + 5, label_y)
# Draw background rectangle
cv2.rectangle(
frame,
(label_x - 5, label_y - label_size[1] - 5),
(label_x + label_size[0] + 5, label_y + 5),
(0, 0, 0),
-1
)
# Draw text
cv2.putText(
frame,
label,
(label_x, label_y),
font,
font_scale,
color,
thickness,
cv2.LINE_AA
)
return frame
def draw_info_panel(
frame: np.ndarray,
frame_num: int,
total_frames: int,
fps: float,
detection_conf: Optional[float] = None
) -> np.ndarray:
"""
Draw an information panel at the top of the frame.
Args:
frame: Input frame (BGR format)
frame_num: Current frame number
total_frames: Total number of frames
fps: Video frame rate
detection_conf: Detection confidence (if available)
Returns:
Frame with info panel
"""
# Create semi-transparent overlay
overlay = frame.copy()
cv2.rectangle(overlay, (0, 0), (frame.shape[1], 60), (0, 0, 0), -1)
frame = cv2.addWeighted(overlay, 0.6, frame, 0.4, 0)
# Draw text information
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.6
color = (255, 255, 255)
thickness = 2
# Frame counter
frame_text = f"Frame: {frame_num}/{total_frames}"
cv2.putText(frame, frame_text, (10, 25), font, font_scale, color, thickness)
# Time
time_text = f"Time: {frame_num / fps:.2f}s"
cv2.putText(frame, time_text, (10, 50), font, font_scale, color, thickness)
# Detection confidence (if available)
if detection_conf is not None:
conf_text = f"Confidence: {detection_conf:.2%}"
cv2.putText(frame, conf_text, (250, 25), font, font_scale, color, thickness)
return frame
def create_trajectory_plot(
trajectory: List[Tuple[float, float, float, float, int]],
fps: float,
output_path: Optional[str] = None
) -> Figure:
"""
Create a 2D trajectory plot color-coded by speed.
Args:
trajectory: List of (x, y, vx, vy, frame_num) tuples
fps: Video frame rate
output_path: Path to save plot (optional)
Returns:
Matplotlib Figure object
"""
if len(trajectory) == 0:
# Create empty plot
fig, ax = plt.subplots(figsize=(10, 8))
ax.text(
0.5, 0.5, "No trajectory data available",
ha='center', va='center', fontsize=14
)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
return fig
# Extract coordinates and velocities
x_coords = [p[0] for p in trajectory]
y_coords = [p[1] for p in trajectory]
vx = [p[2] for p in trajectory]
vy = [p[3] for p in trajectory]
# Calculate speeds
speeds = [np.sqrt(vx[i]**2 + vy[i]**2) / (1.0 / fps) for i in range(len(vx))]
# Create figure
fig, ax = plt.subplots(figsize=(12, 10))
# Normalize speeds for color mapping
if max(speeds) > 0:
norm = mcolors.Normalize(vmin=min(speeds), vmax=max(speeds))
colormap = plt.cm.jet
else:
norm = None
colormap = None
# Plot trajectory with color-coded speeds
for i in range(1, len(x_coords)):
if norm is not None:
color = colormap(norm(speeds[i]))
else:
color = 'blue'
ax.plot(
[x_coords[i - 1], x_coords[i]],
[y_coords[i - 1], y_coords[i]],
color=color,
linewidth=2,
alpha=0.7
)
# Add start and end markers
ax.scatter(x_coords[0], y_coords[0], c='green', s=100, marker='o',
label='Start', zorder=5, edgecolors='black', linewidths=2)
ax.scatter(x_coords[-1], y_coords[-1], c='red', s=100, marker='X',
label='End', zorder=5, edgecolors='black', linewidths=2)
# Formatting
ax.set_xlabel('X Position (pixels)', fontsize=12, fontweight='bold')
ax.set_ylabel('Y Position (pixels)', fontsize=12, fontweight='bold')
ax.set_title('Tennis Ball Trajectory (Color = Speed)', fontsize=14, fontweight='bold')
ax.legend(loc='best', fontsize=10)
ax.grid(True, alpha=0.3)
ax.invert_yaxis() # Invert Y-axis to match image coordinates
# Add colorbar
if norm is not None:
sm = plt.cm.ScalarMappable(cmap=colormap, norm=norm)
sm.set_array([])
cbar = plt.colorbar(sm, ax=ax, label='Speed (pixels/sec)')
plt.tight_layout()
# Save if path provided
if output_path:
try:
plt.savefig(output_path, dpi=150, bbox_inches='tight')
except Exception as e:
print(f"Error saving plot: {str(e)}")
return fig
|