Spaces:
Sleeping
Sleeping
Create lbw_detector.py
Browse files- lbw_detector.py +76 -0
lbw_detector.py
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from ultralytics import YOLO
|
2 |
+
import cv2
|
3 |
+
import numpy as np
|
4 |
+
import os
|
5 |
+
|
6 |
+
# Load YOLO model (custom-trained or pretrained with compatible classes)
|
7 |
+
model = YOLO("yolov8n.pt") # Replace with "lbw_yolov8.pt" if custom-trained
|
8 |
+
|
9 |
+
# Target class IDs — update based on your custom model class mapping
|
10 |
+
CLASS_NAMES = {
|
11 |
+
0: "ball",
|
12 |
+
1: "bat",
|
13 |
+
2: "pad",
|
14 |
+
3: "stump",
|
15 |
+
4: "player"
|
16 |
+
}
|
17 |
+
|
18 |
+
def detect_lbw_event(frames):
|
19 |
+
"""
|
20 |
+
Detects ball, bat, stump, and pad in each frame.
|
21 |
+
Identifies impact and prepares coordinates for trajectory modeling.
|
22 |
+
|
23 |
+
Returns:
|
24 |
+
dict: {
|
25 |
+
"ball_positions": [x, y] list per frame,
|
26 |
+
"impact_frame": int,
|
27 |
+
"impact_type": str,
|
28 |
+
"objects_per_frame": [
|
29 |
+
{"ball": (x, y), "pad": (x, y), ...}
|
30 |
+
]
|
31 |
+
}
|
32 |
+
"""
|
33 |
+
ball_positions = []
|
34 |
+
impact_frame = -1
|
35 |
+
impact_type = None
|
36 |
+
objects_per_frame = []
|
37 |
+
|
38 |
+
for idx, frame in enumerate(frames):
|
39 |
+
results = model(frame)[0]
|
40 |
+
frame_objects = {}
|
41 |
+
|
42 |
+
for det in results.boxes.data:
|
43 |
+
x1, y1, x2, y2, conf, cls = det.cpu().numpy()
|
44 |
+
class_id = int(cls)
|
45 |
+
class_name = CLASS_NAMES.get(class_id, "unknown")
|
46 |
+
center_x = int((x1 + x2) / 2)
|
47 |
+
center_y = int((y1 + y2) / 2)
|
48 |
+
frame_objects[class_name] = (center_x, center_y)
|
49 |
+
|
50 |
+
if class_name == "ball":
|
51 |
+
ball_positions.append((idx, center_x, center_y))
|
52 |
+
|
53 |
+
objects_per_frame.append(frame_objects)
|
54 |
+
|
55 |
+
# Basic impact logic: ball overlaps pad or bat
|
56 |
+
if "ball" in frame_objects and ("pad" in frame_objects or "bat" in frame_objects):
|
57 |
+
bx, by = frame_objects["ball"]
|
58 |
+
if "pad" in frame_objects:
|
59 |
+
px, py = frame_objects["pad"]
|
60 |
+
if abs(bx - px) < 30 and abs(by - py) < 30:
|
61 |
+
impact_frame = idx
|
62 |
+
impact_type = "pad"
|
63 |
+
break
|
64 |
+
if "bat" in frame_objects:
|
65 |
+
tx, ty = frame_objects["bat"]
|
66 |
+
if abs(bx - tx) < 30 and abs(by - ty) < 30:
|
67 |
+
impact_frame = idx
|
68 |
+
impact_type = "bat"
|
69 |
+
break
|
70 |
+
|
71 |
+
return {
|
72 |
+
"ball_positions": ball_positions,
|
73 |
+
"impact_frame": impact_frame,
|
74 |
+
"impact_type": impact_type,
|
75 |
+
"objects_per_frame": objects_per_frame
|
76 |
+
}
|