File size: 6,962 Bytes
49e447c 70802d0 49e447c 70802d0 49a3a3a 49e447c 68f71c4 94fc71e 70802d0 49e447c 49a3a3a 49e447c 70802d0 94fc71e 49a3a3a 94fc71e 70802d0 94fc71e 70802d0 49a3a3a 70802d0 94fc71e 49a3a3a 94fc71e 70802d0 49a3a3a 70802d0 94fc71e 70802d0 94fc71e 70802d0 49e447c 94fc71e 49e447c 70802d0 94fc71e 49e447c 70802d0 68f71c4 94fc71e 68f71c4 94fc71e 49e447c 94fc71e 49e447c 70802d0 49e447c 94fc71e 49e447c 49a3a3a 49e447c f6a6373 |
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 |
from flask import Flask, render_template, request, jsonify
import numpy as np
from sklearn.linear_model import LogisticRegression
import cv2
import os
from werkzeug.utils import secure_filename
from scipy.interpolate import splprep, splev
app = Flask(__name__)
UPLOAD_FOLDER = '/tmp/uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
ALLOWED_EXTENSIONS = {'mp4', 'avi', 'mov'}
def train_dummy_model():
X = np.array([
[0.5, 0.0, 0.4, 0.5, 30, 0],
[0.5, 0.5, 0.5, 0.5, 35, 2],
[0.6, 0.2, 0.5, 0.6, 32, 1],
[0.5, 0.4, 0.5, 0.4, 34, 0],
])
y = np.array([0, 1, 0, 1])
model = LogisticRegression()
model.fit(X, y)
return model
model = train_dummy_model()
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def smooth_trajectory(points):
if len(points) < 3:
return points
x = [p["x"] for p in points]
y = [p["y"] for p in points]
tck, u = splprep([x, y], s=0)
u_new = np.linspace(0, 1, 50)
x_new, y_new = splev(u_new, tck)
return [{"x": x, "y": y} for x, y in zip(x_new, y_new)]
def process_video(video_path):
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
return None, None, "Failed to open video"
actual_path = []
frame_count = 0
spin = 0
last_point = None
pitching_detected = False
impact_detected = False
y_positions = []
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, (0, 120, 70), (10, 255, 255))
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if contours:
c = max(contours, key=cv2.contourArea)
x, y, w, h = cv2.boundingRect(c)
center_x = x + w / 2
center_y = y + h / 2
norm_x = center_x / 1280
norm_y = center_y / 720
current_point = (norm_x, norm_y)
if last_point != current_point:
actual_path.append({"x": norm_x, "y": norm_y})
y_positions.append(norm_y)
last_point = current_point
if len(y_positions) > 2 and not pitching_detected:
if y_positions[-1] < y_positions[-2] and y_positions[-2] < y_positions[-3]:
pitching_detected = True
pitching_x = actual_path[-2]["x"]
pitching_y = actual_path[-2]["y"]
if len(actual_path) > 2 and not impact_detected:
speed_current = abs(y_positions[-1] - y_positions[-2])
speed_prev = abs(y_positions[-2] - y_positions[-3])
if speed_current < speed_prev * 0.3:
impact_detected = True
impact_x = actual_path[-1]["x"]
impact_y = actual_path[-1]["y"]
frame_count += 1
if frame_count > 50:
break
cap.release()
if not actual_path:
return None, None, "No ball detected in video"
if not pitching_detected:
pitching_x = actual_path[len(actual_path)//2]["x"]
pitching_y = actual_path[len(actual_path)//2]["y"]
if not impact_detected:
impact_x = actual_path[-1]["x"]
impact_y = actual_path[-1]["y"]
fps = cap.get(cv2.CAP_PROP_FPS) or 30
speed = (len(actual_path) / (frame_count / fps)) * 0.5
actual_path = smooth_trajectory(actual_path)
projected_path = [
{"x": impact_x, "y": impact_y},
{"x": impact_x + spin * 0.1, "y": 1.0}
]
pitching_status = "Inline" if 0.4 <= pitching_x <= 0.6 else "Outside Leg" if pitching_x < 0.4 else "Outside Off"
impact_status = "Inline" if 0.4 <= impact_x <= 0.6 else "Outside"
wicket_status = "Hitting" if 0.4 <= projected_path[-1]["x"] <= 0.6 else "Missing"
return actual_path, projected_path, pitching_x, pitching_y, impact_x, impact_y, speed, spin, pitching_status, impact_status, wicket_status
@app.route('/')
def index():
return render_template('index.html')
@app.route('/analyze', methods=['POST'])
def analyze():
if 'video' not in request.files:
return jsonify({'error': 'No video uploaded'}), 400
file = request.files['video']
if file.filename == '' or not allowed_file(file.filename):
return jsonify({'error': 'Invalid file'}), 400
filename = secure_filename(file.filename)
video_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(video_path)
result = process_video(video_path)
if result[0] is None:
os.remove(video_path)
return jsonify({'error': result[2]}), 400
actual_path, projected_path, pitching_x, pitching_y, impact_x, impact_y, speed, spin, pitching_status, impact_status, wicket_status = result
features = np.array([[pitching_x, pitching_y, impact_x, impact_y, speed, spin]])
prediction = model.predict(features)[0]
confidence = min(model.predict_proba(features)[0][prediction], 0.99)
decision = "Out" if prediction == 1 else "Not Out"
os.remove(video_path)
return jsonify({
'actual_path': actual_path,
'projected_path': projected_path,
'decision': decision,
'confidence': round(confidence, 2),
'pitching': {'x': pitching_x, 'y': pitching_y, 'status': pitching_status},
'impact': {'x': impact_x, 'y': impact_y, 'status': impact_status},
'wicket': wicket_status
})
@app.route('/analyze_data', methods=['POST'])
def analyze_data():
data = request.get_json()
actual_path = data['actual_path']
projected_path = data['projected_path']
pitching = data['pitching']
impact = data['impact']
speed = data['speed']
spin = data['spin']
pitching_x = pitching['x']
pitching_y = pitching['y']
impact_x = impact['x']
impact_y = impact['y']
pitching_status = "Inline" if 0.4 <= pitching_x <= 0.6 else "Outside Leg" if pitching_x < 0.4 else "Outside Off"
impact_status = "Inline" if 0.4 <= impact_x <= 0.6 else "Outside"
wicket_status = "Hitting" if 0.4 <= projected_path[-1]["x"] <= 0.6 else "Missing"
features = np.array([[pitching_x, pitching_y, impact_x, impact_y, speed, spin]])
prediction = model.predict(features)[0]
confidence = min(model.predict_proba(features)[0][prediction], 0.99)
decision = "Out" if prediction == 1 else "Not Out"
return jsonify({
'actual_path': actual_path,
'projected_path': projected_path,
'decision': decision,
'confidence': round(confidence, 2),
'pitching': {'x': pitching_x, 'y': pitching_y, 'status': pitching_status},
'impact': {'x': impact_x, 'y': impact_y, 'status': impact_status},
'wicket': wicket_status
})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860, debug=True)
|