|
import gradio as gr |
|
import torch |
|
import cv2 |
|
import numpy as np |
|
import matplotlib.pyplot as plt |
|
from yolov5 import YOLOv5 |
|
|
|
|
|
model = YOLOv5("best.pt") |
|
|
|
|
|
def process_video(video_file): |
|
|
|
video = cv2.VideoCapture(video_file.name) |
|
ball_positions = [] |
|
speed_data = [] |
|
|
|
frame_count = 0 |
|
last_position = None |
|
|
|
while video.isOpened(): |
|
ret, frame = video.read() |
|
if not ret: |
|
break |
|
|
|
frame_count += 1 |
|
|
|
|
|
results = model(frame) |
|
|
|
|
|
ball_detections = results.pandas().xywh |
|
ball = ball_detections[ball_detections['class'] == 0] |
|
|
|
if not ball.empty: |
|
ball_x = ball.iloc[0]['xmin'] + (ball.iloc[0]['xmax'] - ball.iloc[0]['xmin']) / 2 |
|
ball_y = ball.iloc[0]['ymin'] + (ball.iloc[0]['ymax'] - ball.iloc[0]['ymin']) / 2 |
|
ball_positions.append((frame_count, ball_x, ball_y)) |
|
|
|
if last_position is not None: |
|
|
|
distance = np.sqrt((ball_x - last_position[1]) ** 2 + (ball_y - last_position[2]) ** 2) |
|
fps = video.get(cv2.CAP_PROP_FPS) |
|
speed = distance * fps |
|
speed_data.append(speed) |
|
|
|
last_position = (frame_count, ball_x, ball_y) |
|
|
|
video.release() |
|
|
|
|
|
plot_trajectory(ball_positions) |
|
|
|
|
|
avg_speed = np.mean(speed_data) if speed_data else 0 |
|
return f"Average Ball Speed: {avg_speed:.2f} pixels per second" |
|
|
|
|
|
def plot_trajectory(ball_positions): |
|
x_positions = [pos[1] for pos in ball_positions] |
|
y_positions = [pos[2] for pos in ball_positions] |
|
|
|
plt.figure(figsize=(10, 6)) |
|
plt.plot(x_positions, y_positions, label="Ball Trajectory", color='b') |
|
plt.title("Ball Trajectory on Pitch") |
|
plt.xlabel("X Position (pitch width)") |
|
plt.ylabel("Y Position (pitch length)") |
|
plt.grid(True) |
|
plt.legend() |
|
plt.show() |
|
|
|
|
|
iface = gr.Interface( |
|
fn=process_video, |
|
inputs=gr.inputs.File(label="Upload a Video File"), |
|
outputs="text", |
|
live=True |
|
) |
|
|
|
iface.launch(debug=True) |
|
|