gloriforge commited on
Commit
dec6b55
·
verified ·
1 Parent(s): 1532889

Upload folder using huggingface_hub

Browse files
Files changed (7) hide show
  1. .gitattributes +1 -0
  2. SV_kp.engine +3 -0
  3. config.yml +38 -0
  4. miner.py +284 -0
  5. object-detection.onnx +3 -0
  6. pitch.py +679 -0
  7. player.py +388 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ SV_kp.engine filter=lfs diff=lfs merge=lfs -text
SV_kp.engine ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f99452eb79e064189e2758abd20a78845a5b639fc8b9c4bc650519c83e13e8db
3
+ size 368289641
config.yml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Image:
2
+ from_base: parachutes/python:3.12
3
+ run_command:
4
+ - pip install --upgrade setuptools wheel
5
+ - sudo apt install tensorrt python3-libnvinfer-dev
6
+ - pip install huggingface_hub==0.19.4 requests opencv-python-headless pydantic onnxruntime onnxruntime-gpu scikit-learn tensorflow torch-tensorrt==2.7 torch==2.7.1 torchvision==0.22.1 pyyaml
7
+
8
+ set_workdir: /app
9
+
10
+ NodeSelector:
11
+ gpu_count: 1
12
+ min_vram_gb_per_gpu: 24
13
+ # include:
14
+ # - a100
15
+ exclude:
16
+ - h100
17
+ - a100
18
+ - l40s
19
+ - mi300x
20
+ - b200
21
+ - h200
22
+ - h20
23
+ - h800
24
+ - h100_sxm
25
+ - h100_nvl
26
+ - a100_sxm
27
+ - a100_40gb_sxm
28
+ - a100_40gb
29
+ - l40
30
+ - pro_6000
31
+ - a6000_ada
32
+ - '5090'
33
+
34
+ Chute:
35
+ timeout_seconds: 300
36
+ concurrency: 2 # Reduced concurrency to limit memory usage
37
+ max_instances: 3 # Reduced max instances to limit memory usage
38
+ scaling_threshold: 0.7 # Higher threshold to reduce scaling frequency
miner.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ from numpy import ndarray
4
+ import numpy as np
5
+ from pydantic import BaseModel
6
+ import sys, os
7
+ sys.path.append(os.path.dirname(os.path.abspath(__file__)))
8
+
9
+ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
10
+ os.environ["OMP_NUM_THREADS"] = "16"
11
+ os.environ["TF_NUM_INTRAOP_THREADS"] = "16"
12
+ os.environ["TF_NUM_INTEROP_THREADS"] = "2"
13
+ os.environ['CUDA_LAUNCH_BLOCKING'] = '0'
14
+ # Suppress ONNX Runtime warnings
15
+ os.environ['ORT_LOGGING_LEVEL'] = '3'
16
+
17
+ import logging
18
+ logging.getLogger('tensorflow').setLevel(logging.ERROR)
19
+
20
+ import tensorflow as tf
21
+ tf.config.threading.set_intra_op_parallelism_threads(16)
22
+ tf.config.threading.set_inter_op_parallelism_threads(2)
23
+ os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
24
+ tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
25
+ tf.get_logger().setLevel('ERROR')
26
+ tf.autograph.set_verbosity(0)
27
+
28
+ from tensorflow.keras import mixed_precision
29
+ mixed_precision.set_global_policy('mixed_float16')
30
+ tf.config.optimizer.set_jit(True)
31
+
32
+ import torch._dynamo
33
+ torch._dynamo.config.suppress_errors = True
34
+ import onnxruntime as ort
35
+ import gc
36
+
37
+ import torch
38
+ import torch_tensorrt
39
+ import torchvision.transforms as T
40
+ import yaml
41
+ import cv2
42
+
43
+ from player import player_detection_result
44
+ from pitch import process_batch_input, get_cls_net, get_cls_net_l
45
+
46
+ class BoundingBox(BaseModel):
47
+ x1: int
48
+ y1: int
49
+ x2: int
50
+ y2: int
51
+ cls_id: int
52
+ conf: float
53
+
54
+
55
+ class TVFrameResult(BaseModel):
56
+ frame_id: int
57
+ boxes: list[BoundingBox]
58
+ keypoints: list[tuple[int, int]]
59
+
60
+ class Miner:
61
+ """
62
+ This class is responsible for:
63
+ - Loading ML models.
64
+ - Running batched predictions on images.
65
+ - Parsing ML model outputs into structured results (TVFrameResult).
66
+
67
+ This class can be modified, but it must have the following to be compatible with the chute:
68
+ - be named `Miner`
69
+ - have a `predict_batch` function with the inputs and outputs specified
70
+ - be stored in a file called `miner.py` which lives in the root of the HFHub repo
71
+ """
72
+
73
+ def __init__(self, path_hf_repo: Path) -> None:
74
+ """
75
+ Loads all ML models from the repository.
76
+ -----(Adjust as needed)----
77
+
78
+ Args:
79
+ path_hf_repo (Path):
80
+ Path to the downloaded HuggingFace Hub repository
81
+
82
+ Returns:
83
+ None
84
+ """
85
+ global torch
86
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
87
+
88
+ providers = [
89
+ 'CUDAExecutionProvider',
90
+ 'CPUExecutionProvider'
91
+
92
+ ]
93
+ # providers = [ 'CPUExecutionProvider']
94
+ model_path = path_hf_repo / "object-detection.onnx"
95
+ session = ort.InferenceSession(model_path, providers=providers)
96
+ input_name = session.get_inputs()[0].name
97
+ height = width = 640
98
+ dummy = np.zeros((1, 3, height, width), dtype=np.float32)
99
+ session.run(None, {input_name: dummy})
100
+ model = session
101
+ self.bbox_model = model
102
+ print(f"✅ BBox Model Loaded")
103
+
104
+ self.kp_threshold = 0.1
105
+ # self.lp_threshold = 0.7
106
+
107
+ model_kp_path = path_hf_repo / 'SV_kp.engine'
108
+ model_kp = torch_tensorrt.load(model_kp_path)
109
+
110
+ @torch.inference_mode()
111
+ def run_inference(model, input_tensor: torch.Tensor):
112
+ input_tensor = input_tensor.to(device).to(memory_format=torch.channels_last)
113
+ output = model.module().forward(input_tensor)
114
+ return output
115
+
116
+ run_inference(model_kp, torch.randn(8, 3, 540, 960, device=device, dtype=torch.float32))
117
+ # model_kp_path = path_hf_repo / 'SV_kp'
118
+ # model_lp_path = path_hf_repo / 'SV_lines'
119
+ # config_kp_path = path_hf_repo / 'hrnetv2_w48.yaml'
120
+ # config_lp_path = path_hf_repo / 'hrnetv2_w48_l.yaml'
121
+ # cfg_kp = yaml.safe_load(open(config_kp_path, 'r'))
122
+ # cfg_lp = yaml.safe_load(open(config_lp_path, 'r'))
123
+
124
+ # loaded_state_kp = torch.load(model_kp_path, map_location=device)
125
+ # model_kp = get_cls_net(cfg_kp)
126
+ # model_kp.load_state_dict(loaded_state_kp)
127
+ # model_kp.to(device)
128
+ # model_kp.eval()
129
+
130
+ # loaded_state_lp = torch.load(model_lp_path, map_location=device)
131
+ # model_lp = get_cls_net_l(cfg_lp)
132
+ # model_lp.load_state_dict(loaded_state_lp)
133
+ # model_lp.to(device)
134
+ # model_lp.eval()
135
+
136
+ # self.transform = T.Resize((540, 960))
137
+
138
+ self.keypoints_model = model_kp
139
+ # self.lines_model = model_lp
140
+
141
+ # print("🔥 Warming up compiled models...")
142
+ # self._warmup_models(device)
143
+
144
+ # Increase batch sizes for better GPU utilization
145
+ self.player_batch_size = 64 # Increased from 32
146
+ self.pitch_batch_size = 8 # Increased from 32
147
+ print(f"✅ Keypoints Model Loaded")
148
+
149
+ def __repr__(self) -> str:
150
+ return f"BBox Model: {type(self.bbox_model).__name__}\nKeypoints Model: {type(self.keypoints_model).__name__}"
151
+
152
+ def predict_batch(
153
+ self,
154
+ batch_images: list[ndarray],
155
+ offset: int,
156
+ n_keypoints: int,
157
+ ) -> list[TVFrameResult]:
158
+ player_batch_size = min(self.player_batch_size, len(batch_images))
159
+ bboxes: dict[int, list[BoundingBox]] = {}
160
+ while True:
161
+ try:
162
+ gc.collect()
163
+ if torch.cuda.is_available():
164
+ tf.keras.backend.clear_session()
165
+ torch.cuda.empty_cache()
166
+ torch.cuda.synchronize()
167
+ bbox_model_results, _, _, _ = player_detection_result(batch_images, player_batch_size, self.bbox_model)
168
+
169
+ if bbox_model_results is not None:
170
+ for frame_number_in_batch, detections in enumerate(bbox_model_results):
171
+ boxes = []
172
+ for detection in detections:
173
+ # Detection format from player.py: {"id": int, "bbox": [x1, y1, x2, y2], "class_id": int}
174
+ x1, y1, x2, y2 = detection["bbox"]
175
+ cls_id = detection["class_id"]
176
+ # Use a default confidence since it's not provided in the processed results
177
+ conf = detection["conf"] # Default confidence value
178
+
179
+ boxes.append(
180
+ BoundingBox(
181
+ x1=int(x1),
182
+ y1=int(y1),
183
+ x2=int(x2),
184
+ y2=int(y2),
185
+ cls_id=int(cls_id),
186
+ conf=float(conf),
187
+ )
188
+ )
189
+ bboxes[offset + frame_number_in_batch] = boxes
190
+ print("✅ BBoxes predicted")
191
+ break
192
+ except RuntimeError as e:
193
+ print(self.player_batch_size)
194
+ if 'out of memory' in str(e):
195
+ if self.player_batch_size == 1:
196
+ raise e
197
+ self.player_batch_size = self.player_batch_size // 2 if self.player_batch_size > 1 else 1
198
+ player_batch_size = min(self.player_batch_size, len(batch_images))
199
+ else:
200
+ raise e
201
+
202
+ pitch_batch_size = min(self.pitch_batch_size, len(batch_images))
203
+ keypoints: dict[int, list[tuple[int, int]]] = {}
204
+ while True:
205
+ try:
206
+ gc.collect()
207
+ if torch.cuda.is_available():
208
+ tf.keras.backend.clear_session()
209
+ torch.cuda.empty_cache()
210
+ torch.cuda.synchronize()
211
+ # Removed expensive memory clearing operations for speed
212
+ keypoints_result = process_batch_input(
213
+ batch_images,
214
+ self.keypoints_model,
215
+ self.kp_threshold,
216
+ 'cuda' if torch.cuda.is_available() else 'cpu',
217
+ batch_size=pitch_batch_size
218
+ )
219
+
220
+ if keypoints_result is not None:
221
+ for frame_number_in_batch, kp_dict in enumerate(keypoints_result):
222
+ frame_keypoints: list[tuple[int, int]] = []
223
+
224
+ # Get image dimensions for conversion from normalized to pixel coordinates
225
+ if frame_number_in_batch < len(batch_images):
226
+ height, width = batch_images[frame_number_in_batch].shape[:2]
227
+
228
+ for idx in range(32):
229
+ x, y = 0, 0
230
+ idx = idx + 1
231
+ if idx in kp_dict.keys():
232
+ kp_data = kp_dict[idx]
233
+ # Convert normalized coordinates to pixel coordinates
234
+ x = int(kp_data['x'] * width)
235
+ y = int(kp_data['y'] * height)
236
+ frame_keypoints.append((x, y))
237
+
238
+ # Pad or truncate to match expected number of keypoints
239
+ if len(frame_keypoints) < n_keypoints:
240
+ frame_keypoints.extend([(0, 0)] * (n_keypoints - len(frame_keypoints)))
241
+ else:
242
+ frame_keypoints = frame_keypoints[:n_keypoints]
243
+
244
+ keypoints[offset + frame_number_in_batch] = frame_keypoints
245
+
246
+ print("✅ Keypoints predicted")
247
+ break
248
+ except RuntimeError as e:
249
+ print(self.pitch_batch_size)
250
+ if 'out of memory' in str(e):
251
+ if self.pitch_batch_size == 1:
252
+ raise e
253
+ self.pitch_batch_size = self.pitch_batch_size // 2 if self.pitch_batch_size > 1 else 1
254
+ pitch_batch_size = min(self.pitch_batch_size, len(batch_images))
255
+ else:
256
+ raise e
257
+
258
+ # Combine results
259
+ results: list[TVFrameResult] = []
260
+ for i, frame_number in enumerate(range(offset, offset + len(batch_images))):
261
+ # Get the current frame
262
+ frame = batch_images[i] # Use index i for batch_images
263
+
264
+ # Get detection results for this frame
265
+ frame_boxes = bboxes.get(frame_number, [])
266
+ frame_keypoints = keypoints.get(frame_number, [(0, 0) for _ in range(n_keypoints)])
267
+
268
+ # Create result object
269
+ result = TVFrameResult(
270
+ frame_id=frame_number,
271
+ boxes=frame_boxes,
272
+ keypoints=frame_keypoints,
273
+ )
274
+ results.append(result)
275
+
276
+ print("✅ Combined results as TVFrameResult")
277
+
278
+ gc.collect()
279
+ if torch.cuda.is_available():
280
+ tf.keras.backend.clear_session()
281
+ torch.cuda.empty_cache()
282
+ torch.cuda.synchronize()
283
+
284
+ return results
object-detection.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:05112479be8cb59494e9ae23a57af43becd5aa1f448b0e5ed33fcb6b4c2bbbc3
3
+ size 273322667
pitch.py ADDED
@@ -0,0 +1,679 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+ from __future__ import division
3
+ from __future__ import print_function
4
+
5
+ import os
6
+ import sys
7
+ import time
8
+ from typing import List, Optional, Tuple
9
+
10
+ import cv2
11
+ import numpy as np
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+ import torchvision.transforms as T
16
+ import torchvision.transforms.functional as f
17
+ from pydantic import BaseModel
18
+
19
+ import logging
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ class BoundingBox(BaseModel):
24
+ x1: int
25
+ y1: int
26
+ x2: int
27
+ y2: int
28
+ cls_id: int
29
+ conf: float
30
+
31
+
32
+ class TVFrameResult(BaseModel):
33
+ frame_id: int
34
+ boxes: list[BoundingBox]
35
+ keypoints: list[tuple[int, int]]
36
+
37
+ BatchNorm2d = nn.BatchNorm2d
38
+ BN_MOMENTUM = 0.1
39
+
40
+ def conv3x3(in_planes, out_planes, stride=1):
41
+ """3x3 convolution with padding"""
42
+ return nn.Conv2d(in_planes, out_planes, kernel_size=3,
43
+ stride=stride, padding=1, bias=False)
44
+
45
+
46
+ class BasicBlock(nn.Module):
47
+ expansion = 1
48
+
49
+ def __init__(self, inplanes, planes, stride=1, downsample=None):
50
+ super(BasicBlock, self).__init__()
51
+ self.conv1 = conv3x3(inplanes, planes, stride)
52
+ self.bn1 = BatchNorm2d(planes, momentum=BN_MOMENTUM)
53
+ self.relu = nn.ReLU(inplace=True)
54
+ self.conv2 = conv3x3(planes, planes)
55
+ self.bn2 = BatchNorm2d(planes, momentum=BN_MOMENTUM)
56
+ self.downsample = downsample
57
+ self.stride = stride
58
+
59
+ def forward(self, x):
60
+ residual = x
61
+
62
+ out = self.conv1(x)
63
+ out = self.bn1(out)
64
+ out = self.relu(out)
65
+
66
+ out = self.conv2(out)
67
+ out = self.bn2(out)
68
+
69
+ if self.downsample is not None:
70
+ residual = self.downsample(x)
71
+
72
+ out += residual
73
+ out = self.relu(out)
74
+
75
+ return out
76
+
77
+
78
+ class Bottleneck(nn.Module):
79
+ expansion = 4
80
+
81
+ def __init__(self, inplanes, planes, stride=1, downsample=None):
82
+ super(Bottleneck, self).__init__()
83
+ self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
84
+ self.bn1 = BatchNorm2d(planes, momentum=BN_MOMENTUM)
85
+ self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
86
+ padding=1, bias=False)
87
+ self.bn2 = BatchNorm2d(planes, momentum=BN_MOMENTUM)
88
+ self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1,
89
+ bias=False)
90
+ self.bn3 = BatchNorm2d(planes * self.expansion,
91
+ momentum=BN_MOMENTUM)
92
+ self.relu = nn.ReLU(inplace=True)
93
+ self.downsample = downsample
94
+ self.stride = stride
95
+
96
+ def forward(self, x):
97
+ residual = x
98
+
99
+ out = self.conv1(x)
100
+ out = self.bn1(out)
101
+ out = self.relu(out)
102
+
103
+ out = self.conv2(out)
104
+ out = self.bn2(out)
105
+ out = self.relu(out)
106
+
107
+ out = self.conv3(out)
108
+ out = self.bn3(out)
109
+
110
+ if self.downsample is not None:
111
+ residual = self.downsample(x)
112
+
113
+ out += residual
114
+ out = self.relu(out)
115
+
116
+ return out
117
+
118
+
119
+ class HighResolutionModule(nn.Module):
120
+ def __init__(self, num_branches, blocks, num_blocks, num_inchannels,
121
+ num_channels, fuse_method, multi_scale_output=True):
122
+ super(HighResolutionModule, self).__init__()
123
+ self._check_branches(
124
+ num_branches, blocks, num_blocks, num_inchannels, num_channels)
125
+
126
+ self.num_inchannels = num_inchannels
127
+ self.fuse_method = fuse_method
128
+ self.num_branches = num_branches
129
+
130
+ self.multi_scale_output = multi_scale_output
131
+
132
+ self.branches = self._make_branches(
133
+ num_branches, blocks, num_blocks, num_channels)
134
+ self.fuse_layers = self._make_fuse_layers()
135
+ self.relu = nn.ReLU(inplace=True)
136
+
137
+ def _check_branches(self, num_branches, blocks, num_blocks,
138
+ num_inchannels, num_channels):
139
+ if num_branches != len(num_blocks):
140
+ error_msg = 'NUM_BRANCHES({}) <> NUM_BLOCKS({})'.format(
141
+ num_branches, len(num_blocks))
142
+ logger.error(error_msg)
143
+ raise ValueError(error_msg)
144
+
145
+ if num_branches != len(num_channels):
146
+ error_msg = 'NUM_BRANCHES({}) <> NUM_CHANNELS({})'.format(
147
+ num_branches, len(num_channels))
148
+ logger.error(error_msg)
149
+ raise ValueError(error_msg)
150
+
151
+ if num_branches != len(num_inchannels):
152
+ error_msg = 'NUM_BRANCHES({}) <> NUM_INCHANNELS({})'.format(
153
+ num_branches, len(num_inchannels))
154
+ logger.error(error_msg)
155
+ raise ValueError(error_msg)
156
+
157
+ def _make_one_branch(self, branch_index, block, num_blocks, num_channels,
158
+ stride=1):
159
+ downsample = None
160
+ if stride != 1 or \
161
+ self.num_inchannels[branch_index] != num_channels[branch_index] * block.expansion:
162
+ downsample = nn.Sequential(
163
+ nn.Conv2d(self.num_inchannels[branch_index],
164
+ num_channels[branch_index] * block.expansion,
165
+ kernel_size=1, stride=stride, bias=False),
166
+ BatchNorm2d(num_channels[branch_index] * block.expansion,
167
+ momentum=BN_MOMENTUM),
168
+ )
169
+
170
+ layers = []
171
+ layers.append(block(self.num_inchannels[branch_index],
172
+ num_channels[branch_index], stride, downsample))
173
+ self.num_inchannels[branch_index] = \
174
+ num_channels[branch_index] * block.expansion
175
+ for i in range(1, num_blocks[branch_index]):
176
+ layers.append(block(self.num_inchannels[branch_index],
177
+ num_channels[branch_index]))
178
+
179
+ return nn.Sequential(*layers)
180
+
181
+ def _make_branches(self, num_branches, block, num_blocks, num_channels):
182
+ branches = []
183
+
184
+ for i in range(num_branches):
185
+ branches.append(
186
+ self._make_one_branch(i, block, num_blocks, num_channels))
187
+
188
+ return nn.ModuleList(branches)
189
+
190
+ def _make_fuse_layers(self):
191
+ if self.num_branches == 1:
192
+ return None
193
+
194
+ num_branches = self.num_branches
195
+ num_inchannels = self.num_inchannels
196
+ fuse_layers = []
197
+ for i in range(num_branches if self.multi_scale_output else 1):
198
+ fuse_layer = []
199
+ for j in range(num_branches):
200
+ if j > i:
201
+ fuse_layer.append(nn.Sequential(
202
+ nn.Conv2d(num_inchannels[j],
203
+ num_inchannels[i],
204
+ 1,
205
+ 1,
206
+ 0,
207
+ bias=False),
208
+ BatchNorm2d(num_inchannels[i], momentum=BN_MOMENTUM)))
209
+ # nn.Upsample(scale_factor=2**(j-i), mode='nearest')))
210
+ elif j == i:
211
+ fuse_layer.append(None)
212
+ else:
213
+ conv3x3s = []
214
+ for k in range(i - j):
215
+ if k == i - j - 1:
216
+ num_outchannels_conv3x3 = num_inchannels[i]
217
+ conv3x3s.append(nn.Sequential(
218
+ nn.Conv2d(num_inchannels[j],
219
+ num_outchannels_conv3x3,
220
+ 3, 2, 1, bias=False),
221
+ BatchNorm2d(num_outchannels_conv3x3, momentum=BN_MOMENTUM)))
222
+ else:
223
+ num_outchannels_conv3x3 = num_inchannels[j]
224
+ conv3x3s.append(nn.Sequential(
225
+ nn.Conv2d(num_inchannels[j],
226
+ num_outchannels_conv3x3,
227
+ 3, 2, 1, bias=False),
228
+ BatchNorm2d(num_outchannels_conv3x3,
229
+ momentum=BN_MOMENTUM),
230
+ nn.ReLU(inplace=True)))
231
+ fuse_layer.append(nn.Sequential(*conv3x3s))
232
+ fuse_layers.append(nn.ModuleList(fuse_layer))
233
+
234
+ return nn.ModuleList(fuse_layers)
235
+
236
+ def get_num_inchannels(self):
237
+ return self.num_inchannels
238
+
239
+ def forward(self, x):
240
+ if self.num_branches == 1:
241
+ return [self.branches[0](x[0])]
242
+
243
+ for i in range(self.num_branches):
244
+ x[i] = self.branches[i](x[i])
245
+
246
+ x_fuse = []
247
+ for i in range(len(self.fuse_layers)):
248
+ y = x[0] if i == 0 else self.fuse_layers[i][0](x[0])
249
+ for j in range(1, self.num_branches):
250
+ if i == j:
251
+ y = y + x[j]
252
+ elif j > i:
253
+ y = y + F.interpolate(
254
+ self.fuse_layers[i][j](x[j]),
255
+ size=[x[i].shape[2], x[i].shape[3]],
256
+ mode='bilinear')
257
+ else:
258
+ y = y + self.fuse_layers[i][j](x[j])
259
+ x_fuse.append(self.relu(y))
260
+
261
+ return x_fuse
262
+
263
+
264
+ blocks_dict = {
265
+ 'BASIC': BasicBlock,
266
+ 'BOTTLENECK': Bottleneck
267
+ }
268
+
269
+
270
+ class HighResolutionNet(nn.Module):
271
+
272
+ def __init__(self, config, **kwargs):
273
+ self.inplanes = 64
274
+ extra = config['MODEL']['EXTRA']
275
+ super(HighResolutionNet, self).__init__()
276
+
277
+ # stem net
278
+ self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=3, stride=2, padding=1,
279
+ bias=False)
280
+ self.bn1 = BatchNorm2d(self.inplanes, momentum=BN_MOMENTUM)
281
+ self.conv2 = nn.Conv2d(self.inplanes, self.inplanes, kernel_size=3, stride=2, padding=1,
282
+ bias=False)
283
+ self.bn2 = BatchNorm2d(self.inplanes, momentum=BN_MOMENTUM)
284
+ self.relu = nn.ReLU(inplace=True)
285
+ self.sf = nn.Softmax(dim=1)
286
+ self.layer1 = self._make_layer(Bottleneck, 64, 64, 4)
287
+
288
+ self.stage2_cfg = extra['STAGE2']
289
+ num_channels = self.stage2_cfg['NUM_CHANNELS']
290
+ block = blocks_dict[self.stage2_cfg['BLOCK']]
291
+ num_channels = [
292
+ num_channels[i] * block.expansion for i in range(len(num_channels))]
293
+ self.transition1 = self._make_transition_layer(
294
+ [256], num_channels)
295
+ self.stage2, pre_stage_channels = self._make_stage(
296
+ self.stage2_cfg, num_channels)
297
+
298
+ self.stage3_cfg = extra['STAGE3']
299
+ num_channels = self.stage3_cfg['NUM_CHANNELS']
300
+ block = blocks_dict[self.stage3_cfg['BLOCK']]
301
+ num_channels = [
302
+ num_channels[i] * block.expansion for i in range(len(num_channels))]
303
+ self.transition2 = self._make_transition_layer(
304
+ pre_stage_channels, num_channels)
305
+ self.stage3, pre_stage_channels = self._make_stage(
306
+ self.stage3_cfg, num_channels)
307
+
308
+ self.stage4_cfg = extra['STAGE4']
309
+ num_channels = self.stage4_cfg['NUM_CHANNELS']
310
+ block = blocks_dict[self.stage4_cfg['BLOCK']]
311
+ num_channels = [
312
+ num_channels[i] * block.expansion for i in range(len(num_channels))]
313
+ self.transition3 = self._make_transition_layer(
314
+ pre_stage_channels, num_channels)
315
+ self.stage4, pre_stage_channels = self._make_stage(
316
+ self.stage4_cfg, num_channels, multi_scale_output=True)
317
+
318
+ self.upsample = nn.Upsample(scale_factor=2, mode='nearest')
319
+ final_inp_channels = sum(pre_stage_channels) + self.inplanes
320
+
321
+ self.head = nn.Sequential(nn.Sequential(
322
+ nn.Conv2d(
323
+ in_channels=final_inp_channels,
324
+ out_channels=final_inp_channels,
325
+ kernel_size=1),
326
+ BatchNorm2d(final_inp_channels, momentum=BN_MOMENTUM),
327
+ nn.ReLU(inplace=True),
328
+ nn.Conv2d(
329
+ in_channels=final_inp_channels,
330
+ out_channels=config['MODEL']['NUM_JOINTS'],
331
+ kernel_size=extra['FINAL_CONV_KERNEL']),
332
+ nn.Softmax(dim=1)))
333
+
334
+
335
+
336
+ def _make_head(self, x, x_skip):
337
+ x = self.upsample(x)
338
+ x = torch.cat([x, x_skip], dim=1)
339
+ x = self.head(x)
340
+
341
+ return x
342
+
343
+ def _make_transition_layer(
344
+ self, num_channels_pre_layer, num_channels_cur_layer):
345
+ num_branches_cur = len(num_channels_cur_layer)
346
+ num_branches_pre = len(num_channels_pre_layer)
347
+
348
+ transition_layers = []
349
+ for i in range(num_branches_cur):
350
+ if i < num_branches_pre:
351
+ if num_channels_cur_layer[i] != num_channels_pre_layer[i]:
352
+ transition_layers.append(nn.Sequential(
353
+ nn.Conv2d(num_channels_pre_layer[i],
354
+ num_channels_cur_layer[i],
355
+ 3,
356
+ 1,
357
+ 1,
358
+ bias=False),
359
+ BatchNorm2d(
360
+ num_channels_cur_layer[i], momentum=BN_MOMENTUM),
361
+ nn.ReLU(inplace=True)))
362
+ else:
363
+ transition_layers.append(None)
364
+ else:
365
+ conv3x3s = []
366
+ for j in range(i + 1 - num_branches_pre):
367
+ inchannels = num_channels_pre_layer[-1]
368
+ outchannels = num_channels_cur_layer[i] \
369
+ if j == i - num_branches_pre else inchannels
370
+ conv3x3s.append(nn.Sequential(
371
+ nn.Conv2d(
372
+ inchannels, outchannels, 3, 2, 1, bias=False),
373
+ BatchNorm2d(outchannels, momentum=BN_MOMENTUM),
374
+ nn.ReLU(inplace=True)))
375
+ transition_layers.append(nn.Sequential(*conv3x3s))
376
+
377
+ return nn.ModuleList(transition_layers)
378
+
379
+ def _make_layer(self, block, inplanes, planes, blocks, stride=1):
380
+ downsample = None
381
+ if stride != 1 or inplanes != planes * block.expansion:
382
+ downsample = nn.Sequential(
383
+ nn.Conv2d(inplanes, planes * block.expansion,
384
+ kernel_size=1, stride=stride, bias=False),
385
+ BatchNorm2d(planes * block.expansion, momentum=BN_MOMENTUM),
386
+ )
387
+
388
+ layers = []
389
+ layers.append(block(inplanes, planes, stride, downsample))
390
+ inplanes = planes * block.expansion
391
+ for i in range(1, blocks):
392
+ layers.append(block(inplanes, planes))
393
+
394
+ return nn.Sequential(*layers)
395
+
396
+ def _make_stage(self, layer_config, num_inchannels,
397
+ multi_scale_output=True):
398
+ num_modules = layer_config['NUM_MODULES']
399
+ num_branches = layer_config['NUM_BRANCHES']
400
+ num_blocks = layer_config['NUM_BLOCKS']
401
+ num_channels = layer_config['NUM_CHANNELS']
402
+ block = blocks_dict[layer_config['BLOCK']]
403
+ fuse_method = layer_config['FUSE_METHOD']
404
+
405
+ modules = []
406
+ for i in range(num_modules):
407
+ # multi_scale_output is only used last module
408
+ if not multi_scale_output and i == num_modules - 1:
409
+ reset_multi_scale_output = False
410
+ else:
411
+ reset_multi_scale_output = True
412
+ modules.append(
413
+ HighResolutionModule(num_branches,
414
+ block,
415
+ num_blocks,
416
+ num_inchannels,
417
+ num_channels,
418
+ fuse_method,
419
+ reset_multi_scale_output)
420
+ )
421
+ num_inchannels = modules[-1].get_num_inchannels()
422
+
423
+ return nn.Sequential(*modules), num_inchannels
424
+
425
+ def forward(self, x):
426
+ # h, w = x.size(2), x.size(3)
427
+ x = self.conv1(x)
428
+ x_skip = x.clone()
429
+ x = self.bn1(x)
430
+ x = self.relu(x)
431
+ x = self.conv2(x)
432
+ x = self.bn2(x)
433
+ x = self.relu(x)
434
+ x = self.layer1(x)
435
+
436
+ x_list = []
437
+ for i in range(self.stage2_cfg['NUM_BRANCHES']):
438
+ if self.transition1[i] is not None:
439
+ x_list.append(self.transition1[i](x))
440
+ else:
441
+ x_list.append(x)
442
+ y_list = self.stage2(x_list)
443
+
444
+ x_list = []
445
+ for i in range(self.stage3_cfg['NUM_BRANCHES']):
446
+ if self.transition2[i] is not None:
447
+ x_list.append(self.transition2[i](y_list[-1]))
448
+ else:
449
+ x_list.append(y_list[i])
450
+ y_list = self.stage3(x_list)
451
+
452
+ x_list = []
453
+ for i in range(self.stage4_cfg['NUM_BRANCHES']):
454
+ if self.transition3[i] is not None:
455
+ x_list.append(self.transition3[i](y_list[-1]))
456
+ else:
457
+ x_list.append(y_list[i])
458
+ x = self.stage4(x_list)
459
+
460
+ # Head Part
461
+ height, width = x[0].size(2), x[0].size(3)
462
+ x1 = F.interpolate(x[1], size=(height, width), mode='bilinear', align_corners=False)
463
+ x2 = F.interpolate(x[2], size=(height, width), mode='bilinear', align_corners=False)
464
+ x3 = F.interpolate(x[3], size=(height, width), mode='bilinear', align_corners=False)
465
+ x = torch.cat([x[0], x1, x2, x3], 1)
466
+ x = self._make_head(x, x_skip)
467
+
468
+ return x
469
+
470
+ def init_weights(self, pretrained=''):
471
+ for m in self.modules():
472
+ if isinstance(m, nn.Conv2d):
473
+ nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
474
+ #nn.init.normal_(m.weight, std=0.001)
475
+ #nn.init.constant_(m.bias, 0)
476
+ elif isinstance(m, nn.BatchNorm2d):
477
+ nn.init.constant_(m.weight, 1)
478
+ nn.init.constant_(m.bias, 0)
479
+ if pretrained != '':
480
+ if os.path.isfile(pretrained):
481
+ pretrained_dict = torch.load(pretrained)
482
+ model_dict = self.state_dict()
483
+ pretrained_dict = {k: v for k, v in pretrained_dict.items()
484
+ if k in model_dict.keys()}
485
+ model_dict.update(pretrained_dict)
486
+ self.load_state_dict(model_dict)
487
+ else:
488
+ sys.exit(f'Weights {pretrained} not found.')
489
+
490
+
491
+ def get_cls_net(config, pretrained='', **kwargs):
492
+ """Create keypoint detection model with softmax activation"""
493
+ model = HighResolutionNet(config, **kwargs)
494
+ model.init_weights(pretrained)
495
+ return model
496
+
497
+
498
+ def get_cls_net_l(config, pretrained='', **kwargs):
499
+ """Create line detection model with sigmoid activation"""
500
+ model = HighResolutionNet(config, **kwargs)
501
+ model.init_weights(pretrained)
502
+
503
+ # After loading weights, replace just the activation function
504
+ # The saved model expects the nested Sequential structure
505
+ inner_seq = model.head[0]
506
+ # Replace softmax (index 4) with sigmoid
507
+ model.head[0][4] = nn.Sigmoid()
508
+
509
+ return model
510
+
511
+ # Simplified utility functions - removed complex Gaussian generation functions
512
+ # These were mainly used for training data generation, not inference
513
+
514
+
515
+
516
+ # generate_gaussian_array_vectorized_dist_l function removed - not used in current implementation
517
+ @torch.inference_mode()
518
+ def run_inference(model, input_tensor: torch.Tensor, device):
519
+ input_tensor = input_tensor.to(device).to(memory_format=torch.channels_last)
520
+ output = model.module().forward(input_tensor)
521
+ return output
522
+
523
+ def preprocess_batch_fast(frames, device):
524
+ """Ultra-fast batch preprocessing using optimized tensor operations"""
525
+ target_size = (540, 960) # H, W format for model input
526
+ batch = []
527
+ for i, frame in enumerate(frames):
528
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
529
+ img = cv2.resize(frame_rgb, (target_size[1], target_size[0]))
530
+ img = img.astype(np.float32) / 255.0
531
+ img = np.transpose(img, (2, 0, 1)) # HWC -> CHW
532
+ batch.append(img)
533
+ batch = torch.tensor(np.stack(batch), dtype=torch.float32)
534
+
535
+ return batch
536
+
537
+ def extract_keypoints_from_heatmap(heatmap: torch.Tensor, scale: int = 2, max_keypoints: int = 1):
538
+ """Optimized keypoint extraction from heatmaps"""
539
+ batch_size, n_channels, height, width = heatmap.shape
540
+
541
+ # Find local maxima using max pooling (keep on GPU)
542
+ kernel = 3
543
+ pad = 1
544
+ max_pooled = F.max_pool2d(heatmap, kernel, stride=1, padding=pad)
545
+ local_maxima = (max_pooled == heatmap)
546
+ heatmap = heatmap * local_maxima
547
+
548
+ # Get top keypoints (keep on GPU longer)
549
+ scores, indices = torch.topk(heatmap.view(batch_size, n_channels, -1), max_keypoints, sorted=False)
550
+ y_coords = torch.div(indices, width, rounding_mode="floor")
551
+ x_coords = indices % width
552
+
553
+ # Optimized tensor operations
554
+ x_coords = x_coords * scale
555
+ y_coords = y_coords * scale
556
+
557
+ # Create result tensor directly on GPU
558
+ results = torch.stack([x_coords.float(), y_coords.float(), scores], dim=-1)
559
+
560
+ return results
561
+
562
+
563
+ def extract_keypoints_from_heatmap_fast(heatmap: torch.Tensor, scale: int = 2, max_keypoints: int = 1):
564
+ """Ultra-fast keypoint extraction optimized for speed"""
565
+ batch_size, n_channels, height, width = heatmap.shape
566
+
567
+ # Simplified local maxima detection (faster but slightly less accurate)
568
+ max_pooled = F.max_pool2d(heatmap, 3, stride=1, padding=1)
569
+ local_maxima = (max_pooled == heatmap)
570
+
571
+ # Apply mask and get top keypoints in one go
572
+ masked_heatmap = heatmap * local_maxima
573
+ flat_heatmap = masked_heatmap.view(batch_size, n_channels, -1)
574
+ scores, indices = torch.topk(flat_heatmap, max_keypoints, dim=-1, sorted=False)
575
+
576
+ # Vectorized coordinate calculation
577
+ y_coords = torch.div(indices, width, rounding_mode="floor") * scale
578
+ x_coords = (indices % width) * scale
579
+
580
+ # Stack results efficiently
581
+ results = torch.stack([x_coords.float(), y_coords.float(), scores], dim=-1)
582
+ return results
583
+
584
+
585
+ def process_keypoints_vectorized(kp_coords, kp_threshold, w, h, batch_size):
586
+ """Ultra-fast vectorized keypoint processing"""
587
+ batch_results = []
588
+
589
+ # Convert to numpy once for faster CPU operations
590
+ kp_np = kp_coords.cpu().numpy()
591
+
592
+ for batch_idx in range(batch_size):
593
+ kp_dict = {}
594
+ # Vectorized threshold check
595
+ valid_kps = kp_np[batch_idx, :, 0, 2] > kp_threshold
596
+ valid_indices = np.where(valid_kps)[0]
597
+
598
+ for ch_idx in valid_indices:
599
+ x = float(kp_np[batch_idx, ch_idx, 0, 0]) / w
600
+ y = float(kp_np[batch_idx, ch_idx, 0, 1]) / h
601
+ p = float(kp_np[batch_idx, ch_idx, 0, 2])
602
+ kp_dict[ch_idx + 1] = {'x': x, 'y': y, 'p': p}
603
+
604
+ batch_results.append(kp_dict)
605
+
606
+ return batch_results
607
+
608
+ def inference_batch(frames, model, kp_threshold, device, batch_size=8):
609
+ """Optimized batch inference for multiple frames"""
610
+ results = []
611
+ num_frames = len(frames)
612
+
613
+ # Process all frames in optimally-sized batches
614
+ for i in range(0, num_frames, batch_size):
615
+ current_batch_size = min(batch_size, num_frames - i)
616
+ batch_frames = frames[i:i + current_batch_size]
617
+
618
+ # Fast preprocessing
619
+ batch = preprocess_batch_fast(batch_frames, device)
620
+
621
+ heatmaps = run_inference(model, batch, device)
622
+
623
+ # Ultra-fast keypoint extraction
624
+ kp_coords = extract_keypoints_from_heatmap_fast(heatmaps[:,:-1,:,:], scale=2, max_keypoints=1)
625
+
626
+ # Vectorized batch processing - no loops
627
+ batch_results = process_keypoints_vectorized(kp_coords, kp_threshold, 960, 540, current_batch_size)
628
+ results.extend(batch_results)
629
+
630
+ # Minimal cleanup
631
+ del heatmaps, kp_coords, batch
632
+
633
+ return results
634
+
635
+ # Keypoint mapping from detection indices to standard football pitch keypoint IDs
636
+ map_keypoints = {
637
+ 1: 1, 2: 14, 3: 25, 4: 2, 5: 10, 6: 18, 7: 26, 8: 3, 9: 7, 10: 23,
638
+ 11: 27, 20: 4, 21: 8, 22: 24, 23: 28, 24: 5, 25: 13, 26: 21, 27: 29,
639
+ 28: 6, 29: 17, 30: 30, 31: 11, 32: 15, 33: 19, 34: 12, 35: 16, 36: 20,
640
+ 45: 9, 50: 31, 52: 32, 57: 22
641
+ }
642
+
643
+ def get_mapped_keypoints(kp_points):
644
+ """Apply keypoint mapping to detection results"""
645
+ mapped_points = {}
646
+ for key, value in kp_points.items():
647
+ if key in map_keypoints:
648
+ mapped_key = map_keypoints[key]
649
+ mapped_points[mapped_key] = value
650
+ # else:
651
+ # Keep unmapped keypoints with original key
652
+ # mapped_points[key] = value
653
+ return mapped_points
654
+
655
+ def process_batch_input(frames, model, kp_threshold, device, batch_size=8):
656
+ """Process multiple input images in batch"""
657
+ # Batch inference
658
+ kp_results = inference_batch(frames, model, kp_threshold, device, batch_size)
659
+ kp_results = [get_mapped_keypoints(kp) for kp in kp_results]
660
+ # Draw results and save
661
+ # for i, (frame, kp_points, input_path) in enumerate(zip(frames, kp_results, valid_paths)):
662
+ # height, width = frame.shape[:2]
663
+
664
+ # # Apply mapping to get standard keypoint IDs
665
+ # mapped_kp_points = get_mapped_keypoints(kp_points)
666
+
667
+ # for key, value in mapped_kp_points.items():
668
+ # x = int(value['x'] * width)
669
+ # y = int(value['y'] * height)
670
+ # cv2.circle(frame, (x, y), 5, (0, 255, 0), -1) # Green circles
671
+ # cv2.putText(frame, str(key), (x+10, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
672
+
673
+ # # Save result
674
+ # output_path = input_path.replace('.png', '_result.png').replace('.jpg', '_result.jpg')
675
+ # cv2.imwrite(output_path, frame)
676
+
677
+ # print(f"Batch processing complete. Processed {len(frames)} images.")
678
+
679
+ return kp_results
player.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from sklearn.cluster import KMeans
4
+ import warnings
5
+ import time
6
+
7
+ import torch
8
+ from torchvision.ops import batched_nms
9
+ from numpy import ndarray
10
+ # Suppress ALL runtime and sklearn warnings
11
+ warnings.filterwarnings('ignore', category=RuntimeWarning)
12
+ warnings.filterwarnings('ignore', category=FutureWarning)
13
+ warnings.filterwarnings('ignore', category=UserWarning)
14
+
15
+ # Suppress sklearn warnings specifically
16
+ import logging
17
+ logging.getLogger('sklearn').setLevel(logging.ERROR)
18
+
19
+ def get_grass_color(img):
20
+ # Convert image to HSV color space
21
+ hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
22
+
23
+ # Define range of green color in HSV
24
+ lower_green = np.array([30, 40, 40])
25
+ upper_green = np.array([80, 255, 255])
26
+
27
+ # Threshold the HSV image to get only green colors
28
+ mask = cv2.inRange(hsv, lower_green, upper_green)
29
+
30
+ # Calculate the mean value of the pixels that are not masked
31
+ masked_img = cv2.bitwise_and(img, img, mask=mask)
32
+ grass_color = cv2.mean(img, mask=mask)
33
+ return grass_color[:3]
34
+
35
+ def get_players_boxes(frame, result):
36
+ players_imgs = []
37
+ players_boxes = []
38
+ for (box, score, cls) in result:
39
+ label = int(cls)
40
+ if label == 0:
41
+ x1, y1, x2, y2 = box.astype(int)
42
+ player_img = frame[y1: y2, x1: x2]
43
+ players_imgs.append(player_img)
44
+ players_boxes.append([box, score, cls])
45
+ return players_imgs, players_boxes
46
+
47
+ def get_kits_colors(players, grass_hsv=None, frame=None):
48
+ kits_colors = []
49
+ if grass_hsv is None:
50
+ grass_color = get_grass_color(frame)
51
+ grass_hsv = cv2.cvtColor(np.uint8([[list(grass_color)]]), cv2.COLOR_BGR2HSV)
52
+
53
+ for player_img in players:
54
+ # Skip empty or invalid images
55
+ if player_img is None or player_img.size == 0 or len(player_img.shape) != 3:
56
+ continue
57
+
58
+ # Convert image to HSV color space
59
+ hsv = cv2.cvtColor(player_img, cv2.COLOR_BGR2HSV)
60
+
61
+ # Define range of green color in HSV
62
+ lower_green = np.array([grass_hsv[0, 0, 0] - 10, 40, 40])
63
+ upper_green = np.array([grass_hsv[0, 0, 0] + 10, 255, 255])
64
+
65
+ # Threshold the HSV image to get only green colors
66
+ mask = cv2.inRange(hsv, lower_green, upper_green)
67
+
68
+ # Bitwise-AND mask and original image
69
+ mask = cv2.bitwise_not(mask)
70
+ upper_mask = np.zeros(player_img.shape[:2], np.uint8)
71
+ upper_mask[0:player_img.shape[0]//2, 0:player_img.shape[1]] = 255
72
+ mask = cv2.bitwise_and(mask, upper_mask)
73
+
74
+ kit_color = np.array(cv2.mean(player_img, mask=mask)[:3])
75
+
76
+ kits_colors.append(kit_color)
77
+ return kits_colors
78
+
79
+ def get_kits_classifier(kits_colors):
80
+ if len(kits_colors) == 0:
81
+ return None
82
+ if len(kits_colors) == 1:
83
+ # Only one kit color, create a dummy classifier
84
+ return None
85
+ kits_kmeans = KMeans(n_clusters=2)
86
+ kits_kmeans.fit(kits_colors)
87
+ return kits_kmeans
88
+
89
+ def classify_kits(kits_classifer, kits_colors):
90
+ if kits_classifer is None or len(kits_colors) == 0:
91
+ return np.array([0]) # Default to team 0
92
+ team = kits_classifer.predict(kits_colors)
93
+ return team
94
+
95
+ def get_left_team_label(players_boxes, kits_colors, kits_clf):
96
+ left_team_label = 0
97
+ team_0 = []
98
+ team_1 = []
99
+
100
+ for i in range(len(players_boxes)):
101
+ x1, y1, x2, y2 = players_boxes[i][0].astype(int)
102
+ team = classify_kits(kits_clf, [kits_colors[i]]).item()
103
+ if team == 0:
104
+ team_0.append(np.array([x1]))
105
+ else:
106
+ team_1.append(np.array([x1]))
107
+
108
+ team_0 = np.array(team_0)
109
+ team_1 = np.array(team_1)
110
+
111
+ # Safely calculate averages with fallback for empty arrays
112
+ avg_team_0 = np.average(team_0) if len(team_0) > 0 else 0
113
+ avg_team_1 = np.average(team_1) if len(team_1) > 0 else 0
114
+
115
+ if avg_team_0 - avg_team_1 > 0:
116
+ left_team_label = 1
117
+
118
+ return left_team_label
119
+
120
+ def check_box_boundaries(boxes, img_height, img_width):
121
+ """
122
+ Check if bounding boxes are within image boundaries and clip them if necessary.
123
+
124
+ Args:
125
+ boxes: numpy array of shape (N, 4) with [x1, y1, x2, y2] format
126
+ img_height: height of the image
127
+ img_width: width of the image
128
+
129
+ Returns:
130
+ valid_boxes: numpy array of valid boxes within boundaries
131
+ valid_indices: indices of valid boxes
132
+ """
133
+ x1, y1, x2, y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
134
+
135
+ # Check if boxes are within boundaries
136
+ valid_mask = (x1 >= 0) & (y1 >= 0) & (x2 < img_width) & (y2 < img_height) & (x1 < x2) & (y1 < y2)
137
+
138
+ if not np.any(valid_mask):
139
+ return np.array([]), np.array([])
140
+
141
+ valid_boxes = boxes[valid_mask]
142
+ valid_indices = np.where(valid_mask)[0]
143
+
144
+ # Clip boxes to image boundaries
145
+ valid_boxes[:, 0] = np.clip(valid_boxes[:, 0], 0, img_width - 1) # x1
146
+ valid_boxes[:, 1] = np.clip(valid_boxes[:, 1], 0, img_height - 1) # y1
147
+ valid_boxes[:, 2] = np.clip(valid_boxes[:, 2], 0, img_width - 1) # x2
148
+ valid_boxes[:, 3] = np.clip(valid_boxes[:, 3], 0, img_height - 1) # y2
149
+
150
+ return valid_boxes, valid_indices
151
+
152
+ def process_team_identification_batch(frames, results, kits_clf, left_team_label, grass_hsv):
153
+ """
154
+ Process team identification and label formatting for batch results.
155
+
156
+ Args:
157
+ frames: list of frames
158
+ results: list of detection results for each frame
159
+ kits_clf: trained kit classifier
160
+ left_team_label: label for left team
161
+ grass_hsv: grass color in HSV format
162
+
163
+ Returns:
164
+ processed_results: list of processed results with team identification
165
+ """
166
+ processed_results = []
167
+
168
+ for frame_idx, frame in enumerate(frames):
169
+ frame_results = []
170
+ frame_detections = results[frame_idx]
171
+
172
+ if not frame_detections:
173
+ processed_results.append([])
174
+ continue
175
+
176
+ # Extract player boxes and images
177
+ players_imgs = []
178
+ players_boxes = []
179
+ player_indices = []
180
+
181
+ for idx, (box, score, cls) in enumerate(frame_detections):
182
+ label = int(cls)
183
+ if label == 0: # Player detection
184
+ x1, y1, x2, y2 = box.astype(int)
185
+
186
+ # Check boundaries
187
+ if (x1 >= 0 and y1 >= 0 and x2 < frame.shape[1] and y2 < frame.shape[0] and x1 < x2 and y1 < y2):
188
+ player_img = frame[y1:y2, x1:x2]
189
+ if player_img.size > 0: # Ensure valid image
190
+ players_imgs.append(player_img)
191
+ players_boxes.append([box, score, cls])
192
+ player_indices.append(idx)
193
+
194
+ # Initialize player team mapping
195
+ player_team_map = {}
196
+
197
+ # Process team identification if we have players
198
+ if players_imgs and kits_clf is not None:
199
+ kits_colors = get_kits_colors(players_imgs, grass_hsv)
200
+ teams = classify_kits(kits_clf, kits_colors)
201
+
202
+ # Create mapping from player index to team
203
+ for i, team in enumerate(teams):
204
+ player_team_map[player_indices[i]] = team.item()
205
+
206
+ id = 0
207
+ # Process all detections with team identification
208
+ for idx, (box, score, cls) in enumerate(frame_detections):
209
+ label = int(cls)
210
+ x1, y1, x2, y2 = box.astype(int)
211
+
212
+ # Check boundaries
213
+ valid_boxes, valid_indices = check_box_boundaries(
214
+ np.array([[x1, y1, x2, y2]]), frame.shape[0], frame.shape[1]
215
+ )
216
+
217
+ if len(valid_boxes) == 0:
218
+ continue
219
+
220
+ x1, y1, x2, y2 = valid_boxes[0].astype(int)
221
+
222
+ # Apply team identification logic
223
+ if label == 0: # Player
224
+ if players_imgs and kits_clf is not None and idx in player_team_map:
225
+ team = player_team_map[idx]
226
+ if team == left_team_label:
227
+ final_label = 6 # Player-L (Left team)
228
+ else:
229
+ final_label = 7 # Player-R (Right team)
230
+ else:
231
+ final_label = 6 # Default player label
232
+
233
+ elif label == 1: # Goalkeeper
234
+ final_label = 1 # GK
235
+
236
+ elif label == 2: # Ball
237
+ final_label = 0 # Ball
238
+
239
+ elif label == 3 or label == 4: # Referee or other
240
+ final_label = 3 # Referee
241
+
242
+ else:
243
+ final_label = int(label) # Keep original label, ensure it's int
244
+
245
+ frame_results.append({
246
+ "id": int(id),
247
+ "bbox": [int(x1), int(y1), int(x2), int(y2)],
248
+ "class_id": int(final_label),
249
+ "conf": float(score)
250
+ })
251
+ id = id + 1
252
+
253
+ processed_results.append(frame_results)
254
+
255
+ return processed_results
256
+
257
+ def convert_numpy_types(obj):
258
+ """Convert numpy types to native Python types for JSON serialization."""
259
+ if isinstance(obj, np.integer):
260
+ return int(obj)
261
+ elif isinstance(obj, np.floating):
262
+ return float(obj)
263
+ elif isinstance(obj, np.ndarray):
264
+ return obj.tolist()
265
+ elif isinstance(obj, dict):
266
+ return {key: convert_numpy_types(value) for key, value in obj.items()}
267
+ elif isinstance(obj, list):
268
+ return [convert_numpy_types(item) for item in obj]
269
+ else:
270
+ return obj
271
+
272
+ def pre_process_img(frames, scale):
273
+ imgs = np.stack([cv2.resize(frame, (int(scale), int(scale))) for frame in frames])
274
+ imgs = imgs.transpose(0, 3, 1, 2)
275
+ imgs = imgs.astype(np.float32) / 255.0 # Normalize
276
+ return imgs
277
+
278
+ def post_process_output(outputs, x_scale, y_scale, conf_thresh=0.6, nms_thresh=0.75):
279
+ B, C, N = outputs.shape
280
+ outputs = torch.from_numpy(outputs)
281
+ outputs = outputs.permute(0, 2, 1)
282
+ boxes = outputs[..., :4]
283
+ class_scores = 1 / (1 + torch.exp(-outputs[..., 4:]))
284
+ conf, class_id = class_scores.max(dim=2)
285
+
286
+ mask = conf > conf_thresh
287
+
288
+ for i in range(class_id.shape[0]): # loop over batch
289
+ # Find detections that are balls
290
+ ball_idx = np.where(class_id[i] == 2)[0]
291
+ if ball_idx.size > 0:
292
+ # Pick the one with the highest confidence
293
+ top = ball_idx[np.argmax(conf[i, ball_idx])]
294
+ if conf[i, top] > 0.55: # apply confidence threshold
295
+ mask[i, top] = True
296
+
297
+ # ball_mask = (class_id == 2) & (conf > 0.51)
298
+ # mask = mask | ball_mask
299
+
300
+ batch_idx, pred_idx = mask.nonzero(as_tuple=True)
301
+
302
+ if len(batch_idx) == 0:
303
+ return [[] for _ in range(B)]
304
+
305
+ boxes = boxes[batch_idx, pred_idx]
306
+ conf = conf[batch_idx, pred_idx]
307
+ class_id = class_id[batch_idx, pred_idx]
308
+
309
+ x, y, w, h = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
310
+ x1 = (x - w / 2) * x_scale
311
+ y1 = (y - h / 2) * y_scale
312
+ x2 = (x + w / 2) * x_scale
313
+ y2 = (y + h / 2) * y_scale
314
+ boxes_xyxy = torch.stack([x1, y1, x2, y2], dim=1)
315
+
316
+ max_coord = 1e4
317
+ offset = batch_idx.to(boxes_xyxy) * max_coord
318
+ boxes_for_nms = boxes_xyxy + offset[:, None]
319
+
320
+ keep = batched_nms(boxes_for_nms, conf, batch_idx, nms_thresh)
321
+
322
+ boxes_final = boxes_xyxy[keep]
323
+ conf_final = conf[keep]
324
+ class_final = class_id[keep]
325
+ batch_final = batch_idx[keep]
326
+
327
+ results = [[] for _ in range(B)]
328
+ for b in range(B):
329
+ mask_b = batch_final == b
330
+ if mask_b.sum() == 0:
331
+ continue
332
+ results[b] = list(zip(boxes_final[mask_b].numpy(),
333
+ conf_final[mask_b].numpy(),
334
+ class_final[mask_b].numpy()))
335
+ return results
336
+
337
+ def player_detection_result(frames: list[ndarray], batch_size, model, kits_clf=None, left_team_label=None, grass_hsv=None):
338
+ start_time = time.time()
339
+ # input_layer = model.input(0)
340
+ # output_layer = model.output(0)
341
+ height, width = frames[0].shape[:2]
342
+ scale = 640.0
343
+ x_scale = width / scale
344
+ y_scale = height / scale
345
+
346
+ # infer_queue = AsyncInferQueue(model, len(frames))
347
+
348
+ infer_time = time.time()
349
+ kits_clf = kits_clf
350
+ left_team_label = left_team_label
351
+ grass_hsv = grass_hsv
352
+ results = []
353
+ for i in range(0, len(frames), batch_size):
354
+ if i + batch_size > len(frames):
355
+ batch_size = len(frames) - i
356
+ batch_frames = frames[i:i + batch_size]
357
+ imgs = pre_process_img(batch_frames, scale)
358
+
359
+ input_name = model.get_inputs()[0].name
360
+ outputs = model.run(None, {input_name: imgs})[0]
361
+ raw_results = post_process_output(np.array(outputs), x_scale, y_scale)
362
+
363
+ if kits_clf is None or left_team_label is None or grass_hsv is None:
364
+ # Use first frame to initialize team classification
365
+ first_frame = batch_frames[0]
366
+ first_frame_results = raw_results[0] if raw_results else []
367
+
368
+ if first_frame_results:
369
+ players_imgs, players_boxes = get_players_boxes(first_frame, first_frame_results)
370
+ if players_imgs:
371
+ grass_color = get_grass_color(first_frame)
372
+ grass_hsv = cv2.cvtColor(np.uint8([[list(grass_color)]]), cv2.COLOR_BGR2HSV)
373
+ kits_colors = get_kits_colors(players_imgs, grass_hsv)
374
+ if kits_colors: # Only proceed if we have valid kit colors
375
+ kits_clf = get_kits_classifier(kits_colors)
376
+ if kits_clf is not None:
377
+ left_team_label = int(get_left_team_label(players_boxes, kits_colors, kits_clf))
378
+
379
+ # Process team identification and boundary checking
380
+ processed_results = process_team_identification_batch(
381
+ batch_frames, raw_results, kits_clf, left_team_label, grass_hsv
382
+ )
383
+
384
+ processed_results = convert_numpy_types(processed_results)
385
+ results.extend(processed_results)
386
+
387
+ # Return the same format as before for compatibility
388
+ return results, kits_clf, left_team_label, grass_hsv