code:
import argparse
import queue
import pandas as pd
import pickle
import imutils
import os
from PIL import Image, ImageDraw
import cv2
import numpy as np
import torch
import sys
import time
from sktime.datatypes._panel._convert import from_2d_array_to_nested
from court_detector import CourtDetector
from Models.tracknet import trackNet
from TrackPlayers.trackplayers import *
from utils import get_video_properties, get_dtype
from detection import *
from pickle import load
I'm sorry, I cannot run the code as there are some missing files and functions such as "get_video_properties", "get_dtype", "mark_player_box", "merge", and "diff_xy". Can you provide more information or the necessary files for me to run the code?
User
how are they detecting bounce of ball
Assistant
After the trajectory of the tennis ball is obtained, the code then predicts the bounces that the ball will make on the court. This is done by training a separate classifier on the trajectory and velocity data of several previous tennis matches.
The code first removes any outliers from the trajectory data, and performs interpolation to obtain a smooth curve of the ball's trajectory. It then prepares the data for the classifier by including the lagged values of the ball's x and y coordinates as well as its velocity.
A pre-trained classifier is then used to predict if a bounce will occur at each time step. If a bounce is predicted, the corresponding frame in the video is marked by drawing a circle around the predicted location of the ball.
while True:
ret, frame = video.read()
frame_i += 1
if ret:
if frame_i == 1:
print('Detecting the court and the players...')
lines = court_detector.detect(frame)
else: # then track it
lines = court_detector.track_court(frame)
detection_model.detect_player_1(frame, court_detector)
detection_model.detect_top_persons(frame, court_detector, frame_i)
code
for i in range(0, len(lines), 4):
x1, y1, x2, y2 = lines[i],lines[i+1], lines[i+2], lines[i+3]
cv2.line(frame, (int(x1),int(y1)),(int(x2),int(y2)), (0,0,255), 5)
new_frame = cv2.resize(frame, (v_width, v_height))
frames.append(new_frame)
video = cv2.VideoCapture(input_video_path)
frame_i = 0
last = time.time() # start counting
while (True):
for img in frames:
print('Tracking the ball: {}'.format(round( (currentFrame / total) * 100, 2)))
frame_i += 1
code
# detect the ball
# img is the frame that TrackNet will predict the position
# since we need to change the size and type of img, copy it to output_img
output_img = img
# resize it
img = cv2.resize(img, (width, height))
# input must be float type
img = img.astype(np.float32)
# since the odering of TrackNet is 'channels_first', so we need to change the axis
X = np.rollaxis(img, 2, 0)
# prdict heatmap
pr = m.predict(np.array([X]))[0]
# since TrackNet output is ( net_output_height*model_output_width , n_classes )
# so we need to reshape image as ( net_output_height, model_output_width , n_classes(depth) )
pr = pr.reshape((height, width, n_classes)).argmax(axis=2)
# cv2 image must be numpy.uint8, convert numpy.int64 to numpy.uint8
pr = pr.astype(np.uint8)
# reshape the image size as original input image
heatmap = cv2.resize(pr, (output_width, output_height))
# heatmap is converted into a binary image by threshold method.
ret, heatmap = cv2.threshold(heatmap, 127, 255, cv2.THRESH_BINARY)
# find the circle in image with 2<=radius<=7
circles = cv2.HoughCircles(heatmap, cv2.HOUGH_GRADIENT, dp=1, minDist=1, param1=50, param2=2, minRadius=2,
maxRadius=7)
output_img = mark_player_box(output_img, player1_boxes, currentFrame-1)
output_img = mark_player_box(output_img, player2_boxes, currentFrame-1)
PIL_image = cv2.cvtColor(output_img, cv2.COLOR_BGR2RGB)
PIL_image = Image.fromarray(PIL_image)
# check if there have any tennis be detected
if circles is not None:
# if only one tennis be detected
if len(circles) == 1:
x = int(circles[0][0][0])
y = int(circles[0][0][1])
coords.append([x,y])
t.append(time.time()-last)
# push x,y to queue
q.appendleft([x, y])
# pop x,y from queue
q.pop()
else:
coords.append(None)
t.append(time.time()-last)
# push None to queue
q.appendleft(None)
# pop x,y from queue
q.pop()
else:
coords.append(None)
t.append(time.time()-last)
# push None to queue
q.appendleft(None)
# pop x,y from queue
q.pop()
# draw current frame prediction and previous 7 frames as yellow circle, total: 8 frames
for i in range(0, 8):
if q[i] is not None:
draw_x = q[i][0]
draw_y = q[i][1]
bbox = (draw_x - 2, draw_y - 2, draw_x + 2, draw_y + 2)
draw = ImageDraw.Draw(PIL_image)
draw.ellipse(bbox, outline='yellow')
del draw
# Convert PIL image format back to opencv image format
opencvImage = cv2.cvtColor(np.array(PIL_image), cv2.COLOR_RGB2BGR)
output_video.write(opencvImage)
# next frame
currentFrame += 1
everything is done, release the video
video.release()
output_video.release()
if minimap == 1:
game_video = cv2.VideoCapture(output_video_path)
for i in range(len(coords)-1):
p1 = coords[i]
p2 = coords[i+1]
t1 = t[i]
t2 = t[i+1]
x = (p1[0]-p2[0])/(t1-t2)
y = (p1[1]-p2[1])/(t1-t2)
Vx.append(x)
Vy.append(y)
for i in range(len(Vx)):
vx = Vx[i]
vy = Vy[i]
v = (vx2+vy2)**0.5
V.append(v)
xy = coords[:]
if bounce == 1:
Predicting Bounces
test_df = pd.DataFrame({'x': [coord[0] for coord in xy[:-1]], 'y':[coord[1] for coord in xy[:-1]], 'V': V})
df.shift
for i in range(20, 0, -1):
test_df[f'lagX_{i}'] = test_df['x'].shift(i, fill_value=0)
for i in range(20, 0, -1):
test_df[f'lagY_{i}'] = test_df['y'].shift(i, fill_value=0)
for i in range(20, 0, -1):
test_df[f'lagV_{i}'] = test_df['V'].shift(i, fill_value=0)
output_video = cv2.VideoWriter('VideoOutput/final_video.mp4', fourcc, fps, (output_width, output_height))
i = 0
while True:
ret, frame = video.read()
if ret:
# if coords[i] is not None:
if i in idx:
center_coordinates = int(xy[i][0]), int(xy[i][1])
radius = 3
color = (255, 0, 0)
thickness = -1
cv2.circle(frame, center_coordinates, 10, color, thickness)
i += 1
output_video.write(frame)
else:
break