Upload folder using huggingface_hub
Browse files- .gitattributes +3 -0
- README.md +92 -0
- __pycache__/miner.cpython-312.pyc +0 -0
- __pycache__/pitch.cpython-312.pyc +0 -0
- config.yml +22 -0
- hrnetv2_w48.yaml +35 -0
- keypoint +3 -0
- miner.py +561 -0
- objdetect.onnx +3 -0
- osnet_ain.pyc +0 -0
- osnet_model.pth.tar-100 +3 -0
- pitch.py +688 -0
- team_cluster.pyc +0 -0
- utils.pyc +0 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,6 @@ 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
|
| 37 |
+
keypoint filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
osnet_model.pth.tar-100 filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚀 Example Chute for Turbovision 🪂
|
| 2 |
+
|
| 3 |
+
This repository demonstrates how to deploy a **Chute** via the **Turbovision CLI**, hosted on **Hugging Face Hub**.
|
| 4 |
+
It serves as a minimal example showcasing the required structure and workflow for integrating machine learning models, preprocessing, and orchestration into a reproducible Chute environment.
|
| 5 |
+
|
| 6 |
+
## Repository Structure
|
| 7 |
+
The following two files **must be present** (in their current locations) for a successful deployment — their content can be modified as needed:
|
| 8 |
+
|
| 9 |
+
| File | Purpose |
|
| 10 |
+
|------|----------|
|
| 11 |
+
| `miner.py` | Defines the ML model type(s), orchestration, and all pre/postprocessing logic. |
|
| 12 |
+
| `config.yml` | Specifies machine configuration (e.g., GPU type, memory, environment variables). |
|
| 13 |
+
|
| 14 |
+
Other files — e.g., model weights, utility scripts, or dependencies — are **optional** and can be included as needed for your model. Note: Any required assets must be defined or contained **within this repo**, which is fully open-source, since all network-related operations (downloading challenge data, weights, etc.) are disabled **inside the Chute**
|
| 15 |
+
|
| 16 |
+
## Overview
|
| 17 |
+
|
| 18 |
+
Below is a high-level diagram showing the interaction between Huggingface, Chutes and Turbovision:
|
| 19 |
+
|
| 20 |
+

|
| 21 |
+
|
| 22 |
+
## Local Testing
|
| 23 |
+
After editing the `config.yml` and `miner.py` and saving it into your Huggingface Repo, you will want to test it works locally.
|
| 24 |
+
|
| 25 |
+
1. Copy the file `scorevision/chute_tmeplate/turbovision_chute.py.j2` as a python file called `my_chute.py` and fill in the missing variables:
|
| 26 |
+
```python
|
| 27 |
+
HF_REPO_NAME = "{{ huggingface_repository_name }}"
|
| 28 |
+
HF_REPO_REVISION = "{{ huggingface_repository_revision }}"
|
| 29 |
+
CHUTES_USERNAME = "{{ chute_username }}"
|
| 30 |
+
CHUTE_NAME = "{{ chute_name }}"
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
2. Run the following command to build the chute locally (Caution: there are known issues with the docker location when running this on a mac)
|
| 34 |
+
```bash
|
| 35 |
+
chutes build my_chute:chute --local --public
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
3. Run the name of the docker image just built (i.e. `CHUTE_NAME`) and enter it
|
| 39 |
+
```bash
|
| 40 |
+
docker run -p 8000:8000 -e CHUTES_EXECUTION_CONTEXT=REMOTE -it <image-name> /bin/bash
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
4. Run the file from within the container
|
| 44 |
+
```bash
|
| 45 |
+
chutes run my_chute:chute --dev --debug
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
5. In another terminal, test the local endpoints to ensure there are no bugs
|
| 49 |
+
```bash
|
| 50 |
+
curl -X POST http://localhost:8000/health -d '{}'
|
| 51 |
+
curl -X POST http://localhost:8000/predict -d '{"url": "https://scoredata.me/2025_03_14/35ae7a/h1_0f2ca0.mp4","meta": {}}'
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
## Live Testing
|
| 55 |
+
1. If you have any chute with the same name (ie from a previous deployment), ensure you delete that first (or you will get an error when trying to build).
|
| 56 |
+
```bash
|
| 57 |
+
chutes chutes list
|
| 58 |
+
```
|
| 59 |
+
Take note of the chute id that you wish to delete (if any)
|
| 60 |
+
```bash
|
| 61 |
+
chutes chutes delete <chute-id>
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
You should also delete its associated image
|
| 65 |
+
```bash
|
| 66 |
+
chutes images list
|
| 67 |
+
```
|
| 68 |
+
Take note of the chute image id
|
| 69 |
+
```bash
|
| 70 |
+
chutes images delete <chute-image-id>
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
2. Use Turbovision's CLI to build, deploy and commit on-chain (Note: you can skip the on-chain commit using `--no-commit`. You can also specify a past huggingface revision to point to using `--revision` and/or the local files you want to upload to your huggingface repo using `--model-path`)
|
| 74 |
+
```bash
|
| 75 |
+
sv -vv push
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
3. When completed, warm up the chute (if its cold 🧊). (You can confirm its status using `chutes chutes list` or `chutes chutes get <chute-id>` if you already know its id). Note: Warming up can sometimes take a while but if the chute runs without errors (should be if you've tested locally first) and there are sufficient nodes (i.e. machines) available matching the `config.yml` you specified, the chute should become hot 🔥!
|
| 79 |
+
```bash
|
| 80 |
+
chutes warmup <chute-id>
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
4. Test the chute's endpoints
|
| 84 |
+
```bash
|
| 85 |
+
curl -X POST https://<YOUR-CHUTE-SLUG>.chutes.ai/health -d '{}' -H "Authorization: Bearer $CHUTES_API_KEY"
|
| 86 |
+
curl -X POST https://<YOUR-CHUTE-SLUG>.chutes.ai/predict -d '{"url": "https://scoredata.me/2025_03_14/35ae7a/h1_0f2ca0.mp4","meta": {}}' -H "Authorization: Bearer $CHUTES_API_KEY"
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
5. Test what your chute would get on a validator (this also applies any validation/integrity checks which may fail if you did not use the Turbovision CLI above to deploy the chute)
|
| 90 |
+
```bash
|
| 91 |
+
sv -vv run-once
|
| 92 |
+
```
|
__pycache__/miner.cpython-312.pyc
ADDED
|
Binary file (24.9 kB). View file
|
|
|
__pycache__/pitch.cpython-312.pyc
ADDED
|
Binary file (31.3 kB). View file
|
|
|
config.yml
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Image:
|
| 2 |
+
from_base: parachutes/python:3.12
|
| 3 |
+
run_command:
|
| 4 |
+
- pip install --upgrade setuptools wheel
|
| 5 |
+
- pip install "ultralytics==8.3.222" "opencv-python-headless" "numpy" "pydantic"
|
| 6 |
+
- pip install "tensorflow" "torch==2.7.1" "torchvision==0.22.1" "torch-tensorrt==2.7"
|
| 7 |
+
set_workdir: /app
|
| 8 |
+
|
| 9 |
+
NodeSelector:
|
| 10 |
+
gpu_count: 1
|
| 11 |
+
min_vram_gb_per_gpu: 16
|
| 12 |
+
exclude:
|
| 13 |
+
- "5090"
|
| 14 |
+
- b200
|
| 15 |
+
- h200
|
| 16 |
+
- mi300x
|
| 17 |
+
|
| 18 |
+
Chute:
|
| 19 |
+
timeout_seconds: 900
|
| 20 |
+
concurrency: 4
|
| 21 |
+
max_instances: 5
|
| 22 |
+
scaling_threshold: 0.5
|
hrnetv2_w48.yaml
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MODEL:
|
| 2 |
+
IMAGE_SIZE: [960, 540]
|
| 3 |
+
NUM_JOINTS: 58
|
| 4 |
+
PRETRAIN: ''
|
| 5 |
+
EXTRA:
|
| 6 |
+
FINAL_CONV_KERNEL: 1
|
| 7 |
+
STAGE1:
|
| 8 |
+
NUM_MODULES: 1
|
| 9 |
+
NUM_BRANCHES: 1
|
| 10 |
+
BLOCK: BOTTLENECK
|
| 11 |
+
NUM_BLOCKS: [4]
|
| 12 |
+
NUM_CHANNELS: [64]
|
| 13 |
+
FUSE_METHOD: SUM
|
| 14 |
+
STAGE2:
|
| 15 |
+
NUM_MODULES: 1
|
| 16 |
+
NUM_BRANCHES: 2
|
| 17 |
+
BLOCK: BASIC
|
| 18 |
+
NUM_BLOCKS: [4, 4]
|
| 19 |
+
NUM_CHANNELS: [48, 96]
|
| 20 |
+
FUSE_METHOD: SUM
|
| 21 |
+
STAGE3:
|
| 22 |
+
NUM_MODULES: 4
|
| 23 |
+
NUM_BRANCHES: 3
|
| 24 |
+
BLOCK: BASIC
|
| 25 |
+
NUM_BLOCKS: [4, 4, 4]
|
| 26 |
+
NUM_CHANNELS: [48, 96, 192]
|
| 27 |
+
FUSE_METHOD: SUM
|
| 28 |
+
STAGE4:
|
| 29 |
+
NUM_MODULES: 3
|
| 30 |
+
NUM_BRANCHES: 4
|
| 31 |
+
BLOCK: BASIC
|
| 32 |
+
NUM_BLOCKS: [4, 4, 4, 4]
|
| 33 |
+
NUM_CHANNELS: [48, 96, 192, 384]
|
| 34 |
+
FUSE_METHOD: SUM
|
| 35 |
+
|
keypoint
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7ea78fa76aaf94976a8eca428d6e3c59697a93430cba1a4603e20284b61f5113
|
| 3 |
+
size 264964645
|
miner.py
ADDED
|
@@ -0,0 +1,561 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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os
|
| 5 |
+
|
| 6 |
+
from numpy import ndarray
|
| 7 |
+
import numpy as np
|
| 8 |
+
from pydantic import BaseModel
|
| 9 |
+
import cv2
|
| 10 |
+
|
| 11 |
+
import onnxruntime as ort
|
| 12 |
+
from torchvision.ops import batched_nms
|
| 13 |
+
from ultralytics import YOLO
|
| 14 |
+
from team_cluster import TeamClassifier
|
| 15 |
+
from utils import (
|
| 16 |
+
BoundingBox,
|
| 17 |
+
Constants,
|
| 18 |
+
suppress_small_contained_boxes,
|
| 19 |
+
classify_teams_batch,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
| 23 |
+
|
| 24 |
+
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
|
| 25 |
+
os.environ["OMP_NUM_THREADS"] = "16"
|
| 26 |
+
os.environ["TF_NUM_INTRAOP_THREADS"] = "16"
|
| 27 |
+
os.environ["TF_NUM_INTEROP_THREADS"] = "2"
|
| 28 |
+
os.environ["CUDA_LAUNCH_BLOCKING"] = "0"
|
| 29 |
+
os.environ["ORT_LOGGING_LEVEL"] = "3"
|
| 30 |
+
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0"
|
| 31 |
+
|
| 32 |
+
import logging
|
| 33 |
+
import tensorflow as tf
|
| 34 |
+
from tensorflow.keras import mixed_precision
|
| 35 |
+
import torch._dynamo
|
| 36 |
+
import torch
|
| 37 |
+
# import torch_tensorrt
|
| 38 |
+
import gc
|
| 39 |
+
from ultralytics import YOLO
|
| 40 |
+
from pitch import process_batch_input, get_cls_net
|
| 41 |
+
import yaml
|
| 42 |
+
|
| 43 |
+
logging.getLogger("tensorflow").setLevel(logging.ERROR)
|
| 44 |
+
tf.config.threading.set_intra_op_parallelism_threads(16)
|
| 45 |
+
tf.config.threading.set_inter_op_parallelism_threads(2)
|
| 46 |
+
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
|
| 47 |
+
tf.get_logger().setLevel("ERROR")
|
| 48 |
+
tf.autograph.set_verbosity(0)
|
| 49 |
+
mixed_precision.set_global_policy("mixed_float16")
|
| 50 |
+
tf.config.optimizer.set_jit(True)
|
| 51 |
+
torch._dynamo.config.suppress_errors = True
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class BoundingBox(BaseModel):
|
| 55 |
+
x1: int
|
| 56 |
+
y1: int
|
| 57 |
+
x2: int
|
| 58 |
+
y2: int
|
| 59 |
+
cls_id: int
|
| 60 |
+
conf: float
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class TVFrameResult(BaseModel):
|
| 64 |
+
frame_id: int
|
| 65 |
+
boxes: List[BoundingBox]
|
| 66 |
+
keypoints: List[Tuple[int, int]]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class Miner:
|
| 70 |
+
QUASI_TOTAL_IOA: float = 0.90
|
| 71 |
+
SMALL_CONTAINED_IOA: float = 0.85
|
| 72 |
+
SMALL_RATIO_MAX: float = 0.50
|
| 73 |
+
SINGLE_PLAYER_HUE_PIVOT: float = 90.0
|
| 74 |
+
|
| 75 |
+
# Use constants from utils
|
| 76 |
+
SMALL_CONTAINED_IOA = Constants.SMALL_CONTAINED_IOA
|
| 77 |
+
SMALL_RATIO_MAX = Constants.SMALL_RATIO_MAX
|
| 78 |
+
SINGLE_PLAYER_HUE_PIVOT = Constants.SINGLE_PLAYER_HUE_PIVOT
|
| 79 |
+
CORNER_INDICES = Constants.CORNER_INDICES
|
| 80 |
+
KEYPOINTS_CONFIDENCE = Constants.KEYPOINTS_CONFIDENCE
|
| 81 |
+
CORNER_CONFIDENCE = Constants.CORNER_CONFIDENCE
|
| 82 |
+
GOALKEEPER_POSITION_MARGIN = Constants.GOALKEEPER_POSITION_MARGIN
|
| 83 |
+
MIN_SAMPLES_FOR_FIT = 16 # Minimum player crops needed before fitting TeamClassifier
|
| 84 |
+
MAX_SAMPLES_FOR_FIT = 500 # Maximum samples to avoid overfitting
|
| 85 |
+
|
| 86 |
+
def __init__(self, path_hf_repo: Path) -> None:
|
| 87 |
+
try:
|
| 88 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 89 |
+
print(device)
|
| 90 |
+
|
| 91 |
+
providers = [
|
| 92 |
+
'CUDAExecutionProvider',
|
| 93 |
+
'CPUExecutionProvider'
|
| 94 |
+
]
|
| 95 |
+
model_path = path_hf_repo / "objdetect.onnx"
|
| 96 |
+
session = ort.InferenceSession(model_path, providers=providers)
|
| 97 |
+
|
| 98 |
+
input_name = session.get_inputs()[0].name
|
| 99 |
+
height = width = 640
|
| 100 |
+
dummy = np.zeros((1, 3, height, width), dtype=np.float32)
|
| 101 |
+
session.run(None, {input_name: dummy})
|
| 102 |
+
model = session
|
| 103 |
+
self.bbox_model = model
|
| 104 |
+
|
| 105 |
+
print("BBox Model Loaded")
|
| 106 |
+
|
| 107 |
+
team_model_path = path_hf_repo / "osnet_model.pth.tar-100"
|
| 108 |
+
self.team_classifier = TeamClassifier(
|
| 109 |
+
device=device,
|
| 110 |
+
batch_size=32,
|
| 111 |
+
model_name=str(team_model_path)
|
| 112 |
+
)
|
| 113 |
+
print("Team Classifier Loaded")
|
| 114 |
+
|
| 115 |
+
# Team classification state
|
| 116 |
+
self.team_classifier_fitted = False
|
| 117 |
+
self.player_crops_for_fit = []
|
| 118 |
+
|
| 119 |
+
model_kp_path = path_hf_repo / 'keypoint'
|
| 120 |
+
config_kp_path = path_hf_repo / 'hrnetv2_w48.yaml'
|
| 121 |
+
cfg_kp = yaml.safe_load(open(config_kp_path, 'r'))
|
| 122 |
+
|
| 123 |
+
loaded_state_kp = torch.load(model_kp_path, map_location=device)
|
| 124 |
+
model = get_cls_net(cfg_kp)
|
| 125 |
+
model.load_state_dict(loaded_state_kp)
|
| 126 |
+
model.to(device)
|
| 127 |
+
model.eval()
|
| 128 |
+
|
| 129 |
+
# @torch.inference_mode()
|
| 130 |
+
# def run_inference(model, input_tensor: torch.Tensor):
|
| 131 |
+
# input_tensor = input_tensor.to(device).to(memory_format=torch.channels_last)
|
| 132 |
+
# output = model.module().forward(input_tensor)
|
| 133 |
+
# return output
|
| 134 |
+
|
| 135 |
+
# run_inference(model_kp, torch.randn(8, 3, 540, 960, device=device, dtype=torch.float32))
|
| 136 |
+
self.keypoints_model = model
|
| 137 |
+
self.kp_threshold = 0.1
|
| 138 |
+
self.pitch_batch_size = 8
|
| 139 |
+
self.health = "✅ Miner initialized successfully"
|
| 140 |
+
print("✅ Keypoints Model Loaded")
|
| 141 |
+
except Exception as e:
|
| 142 |
+
self.health = "❌ Miner initialization failed: " + str(e)
|
| 143 |
+
print(self.health)
|
| 144 |
+
|
| 145 |
+
def __repr__(self) -> str:
|
| 146 |
+
return (
|
| 147 |
+
f"BBox Model: {type(self.bbox_model).__name__}\n"
|
| 148 |
+
f"Keypoints Model: {type(self.keypoints_model).__name__}"
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
def _handle_multiple_goalkeepers(self, boxes: List[BoundingBox]) -> List[BoundingBox]:
|
| 152 |
+
"""
|
| 153 |
+
Handle goalkeeper detection issues:
|
| 154 |
+
1. Fix misplaced goalkeepers (standing in middle of field)
|
| 155 |
+
2. Limit to maximum 2 goalkeepers (one from each team)
|
| 156 |
+
|
| 157 |
+
Returns:
|
| 158 |
+
Filtered list of boxes with corrected goalkeepers
|
| 159 |
+
"""
|
| 160 |
+
# Step 1: Fix misplaced goalkeepers first
|
| 161 |
+
# Convert goalkeepers in middle of field to regular players
|
| 162 |
+
boxes = self._fix_misplaced_goalkeepers(boxes)
|
| 163 |
+
|
| 164 |
+
# Step 2: Handle multiple goalkeepers (after fixing misplaced ones)
|
| 165 |
+
gk_idxs = [i for i, bb in enumerate(boxes) if int(bb.cls_id) == 1]
|
| 166 |
+
if len(gk_idxs) <= 2:
|
| 167 |
+
return boxes
|
| 168 |
+
|
| 169 |
+
# Sort goalkeepers by confidence (highest first)
|
| 170 |
+
gk_idxs_sorted = sorted(gk_idxs, key=lambda i: boxes[i].conf, reverse=True)
|
| 171 |
+
keep_gk_idxs = set(gk_idxs_sorted[:2]) # Keep top 2 goalkeepers
|
| 172 |
+
|
| 173 |
+
# Create new list keeping only top 2 goalkeepers
|
| 174 |
+
filtered_boxes = []
|
| 175 |
+
for i, box in enumerate(boxes):
|
| 176 |
+
if int(box.cls_id) == 1:
|
| 177 |
+
# Only keep the top 2 goalkeepers by confidence
|
| 178 |
+
if i in keep_gk_idxs:
|
| 179 |
+
filtered_boxes.append(box)
|
| 180 |
+
# Skip extra goalkeepers
|
| 181 |
+
else:
|
| 182 |
+
# Keep all non-goalkeeper boxes
|
| 183 |
+
filtered_boxes.append(box)
|
| 184 |
+
|
| 185 |
+
return filtered_boxes
|
| 186 |
+
|
| 187 |
+
def _fix_misplaced_goalkeepers(self, boxes: List[BoundingBox]) -> List[BoundingBox]:
|
| 188 |
+
"""
|
| 189 |
+
"""
|
| 190 |
+
gk_idxs = [i for i, bb in enumerate(boxes) if int(bb.cls_id) == 1]
|
| 191 |
+
player_idxs = [i for i, bb in enumerate(boxes) if int(bb.cls_id) == 2]
|
| 192 |
+
|
| 193 |
+
if len(gk_idxs) == 0 or len(player_idxs) < 2:
|
| 194 |
+
return boxes
|
| 195 |
+
|
| 196 |
+
updated_boxes = boxes.copy()
|
| 197 |
+
|
| 198 |
+
for gk_idx in gk_idxs:
|
| 199 |
+
if boxes[gk_idx].conf < 0.3:
|
| 200 |
+
updated_boxes[gk_idx].cls_id = 2
|
| 201 |
+
|
| 202 |
+
return updated_boxes
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def _pre_process_img(self, frames: List[np.ndarray], scale: float = 640.0) -> np.ndarray:
|
| 206 |
+
"""
|
| 207 |
+
Preprocess images for ONNX inference.
|
| 208 |
+
|
| 209 |
+
Args:
|
| 210 |
+
frames: List of BGR frames
|
| 211 |
+
scale: Target scale for resizing
|
| 212 |
+
|
| 213 |
+
Returns:
|
| 214 |
+
Preprocessed numpy array ready for ONNX inference
|
| 215 |
+
"""
|
| 216 |
+
imgs = np.stack([cv2.resize(frame, (int(scale), int(scale))) for frame in frames])
|
| 217 |
+
imgs = imgs.transpose(0, 3, 1, 2) # BHWC to BCHW
|
| 218 |
+
imgs = imgs.astype(np.float32) / 255.0 # Normalize to [0, 1]
|
| 219 |
+
return imgs
|
| 220 |
+
|
| 221 |
+
def _post_process_output(self, outputs: np.ndarray, x_scale: float, y_scale: float,
|
| 222 |
+
conf_thresh: float = 0.6, nms_thresh: float = 0.55) -> List[List[Tuple]]:
|
| 223 |
+
"""
|
| 224 |
+
Post-process ONNX model outputs to get detections.
|
| 225 |
+
|
| 226 |
+
Args:
|
| 227 |
+
outputs: Raw ONNX model outputs
|
| 228 |
+
x_scale: X-axis scaling factor
|
| 229 |
+
y_scale: Y-axis scaling factor
|
| 230 |
+
conf_thresh: Confidence threshold
|
| 231 |
+
nms_thresh: NMS threshold
|
| 232 |
+
|
| 233 |
+
Returns:
|
| 234 |
+
List of detections for each frame: [(box, conf, class_id), ...]
|
| 235 |
+
"""
|
| 236 |
+
B, C, N = outputs.shape
|
| 237 |
+
outputs = torch.from_numpy(outputs)
|
| 238 |
+
outputs = outputs.permute(0, 2, 1) # B,C,N -> B,N,C
|
| 239 |
+
|
| 240 |
+
boxes = outputs[..., :4]
|
| 241 |
+
class_scores = 1 / (1 + torch.exp(-outputs[..., 4:])) # Sigmoid activation
|
| 242 |
+
conf, class_id = class_scores.max(dim=2)
|
| 243 |
+
|
| 244 |
+
mask = conf > conf_thresh
|
| 245 |
+
|
| 246 |
+
# Special handling for balls - keep best one even with lower confidence
|
| 247 |
+
for i in range(class_id.shape[0]): # loop over batch
|
| 248 |
+
# Find detections that are balls
|
| 249 |
+
ball_mask = class_id[i] == 0
|
| 250 |
+
ball_idx = ball_mask.nonzero(as_tuple=True)[0]
|
| 251 |
+
if ball_idx.numel() > 0:
|
| 252 |
+
# Pick the one with the highest confidence
|
| 253 |
+
best_ball_idx = ball_idx[conf[i, ball_idx].argmax()]
|
| 254 |
+
if conf[i, best_ball_idx] >= 0.55: # apply confidence threshold
|
| 255 |
+
mask[i, best_ball_idx] = True
|
| 256 |
+
|
| 257 |
+
batch_idx, pred_idx = mask.nonzero(as_tuple=True)
|
| 258 |
+
|
| 259 |
+
if len(batch_idx) == 0:
|
| 260 |
+
return [[] for _ in range(B)]
|
| 261 |
+
|
| 262 |
+
boxes = boxes[batch_idx, pred_idx]
|
| 263 |
+
conf = conf[batch_idx, pred_idx]
|
| 264 |
+
class_id = class_id[batch_idx, pred_idx]
|
| 265 |
+
|
| 266 |
+
# Convert from center format to xyxy format
|
| 267 |
+
x, y, w, h = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
|
| 268 |
+
x1 = (x - w / 2) * x_scale
|
| 269 |
+
y1 = (y - h / 2) * y_scale
|
| 270 |
+
x2 = (x + w / 2) * x_scale
|
| 271 |
+
y2 = (y + h / 2) * y_scale
|
| 272 |
+
boxes_xyxy = torch.stack([x1, y1, x2, y2], dim=1)
|
| 273 |
+
|
| 274 |
+
# Apply batched NMS
|
| 275 |
+
max_coord = 1e4
|
| 276 |
+
offset = batch_idx.to(boxes_xyxy) * max_coord
|
| 277 |
+
boxes_for_nms = boxes_xyxy + offset[:, None]
|
| 278 |
+
|
| 279 |
+
keep = batched_nms(boxes_for_nms, conf, batch_idx, nms_thresh)
|
| 280 |
+
|
| 281 |
+
boxes_final = boxes_xyxy[keep]
|
| 282 |
+
conf_final = conf[keep]
|
| 283 |
+
class_final = class_id[keep]
|
| 284 |
+
batch_final = batch_idx[keep]
|
| 285 |
+
|
| 286 |
+
# Group results by batch
|
| 287 |
+
results = [[] for _ in range(B)]
|
| 288 |
+
for b in range(B):
|
| 289 |
+
mask_b = batch_final == b
|
| 290 |
+
if mask_b.sum() == 0:
|
| 291 |
+
continue
|
| 292 |
+
results[b] = list(zip(boxes_final[mask_b].numpy(),
|
| 293 |
+
conf_final[mask_b].numpy(),
|
| 294 |
+
class_final[mask_b].numpy()))
|
| 295 |
+
return results
|
| 296 |
+
|
| 297 |
+
def _ioa(self, a: BoundingBox, b: BoundingBox) -> float:
|
| 298 |
+
inter = self._intersect_area(a, b)
|
| 299 |
+
aa = self._area(a)
|
| 300 |
+
if aa <= 0:
|
| 301 |
+
return 0.0
|
| 302 |
+
return inter / aa
|
| 303 |
+
|
| 304 |
+
def suppress_small_contained(self, boxes: List[BoundingBox]) -> List[BoundingBox]:
|
| 305 |
+
if len(boxes) <= 1:
|
| 306 |
+
return boxes
|
| 307 |
+
keep = [True] * len(boxes)
|
| 308 |
+
areas = [self._area(bb) for bb in boxes]
|
| 309 |
+
for i in range(len(boxes)):
|
| 310 |
+
if not keep[i]:
|
| 311 |
+
continue
|
| 312 |
+
for j in range(len(boxes)):
|
| 313 |
+
if i == j or not keep[j]:
|
| 314 |
+
continue
|
| 315 |
+
ai, aj = areas[i], areas[j]
|
| 316 |
+
if ai == 0 or aj == 0:
|
| 317 |
+
continue
|
| 318 |
+
if ai <= aj:
|
| 319 |
+
ratio = ai / aj
|
| 320 |
+
if ratio <= self.SMALL_RATIO_MAX:
|
| 321 |
+
ioa_i_in_j = self._ioa(boxes[i], boxes[j])
|
| 322 |
+
if ioa_i_in_j >= self.SMALL_CONTAINED_IOA:
|
| 323 |
+
keep[i] = False
|
| 324 |
+
break
|
| 325 |
+
else:
|
| 326 |
+
ratio = aj / ai
|
| 327 |
+
if ratio <= self.SMALL_RATIO_MAX:
|
| 328 |
+
ioa_j_in_i = self._ioa(boxes[j], boxes[i])
|
| 329 |
+
if ioa_j_in_i >= self.SMALL_CONTAINED_IOA:
|
| 330 |
+
keep[j] = False
|
| 331 |
+
return [bb for bb, k in zip(boxes, keep) if k]
|
| 332 |
+
|
| 333 |
+
def _detect_objects_batch(self, batch_images: List[ndarray], offset: int) -> Dict[int, List[BoundingBox]]:
|
| 334 |
+
"""
|
| 335 |
+
Phase 1: Object detection for all frames in batch.
|
| 336 |
+
Returns detected objects with players still having class_id=2 (before team classification).
|
| 337 |
+
|
| 338 |
+
Args:
|
| 339 |
+
batch_images: List of images to process
|
| 340 |
+
offset: Frame offset for numbering
|
| 341 |
+
|
| 342 |
+
Returns:
|
| 343 |
+
Dictionary mapping frame_id to list of detected boxes
|
| 344 |
+
"""
|
| 345 |
+
bboxes: Dict[int, List[BoundingBox]] = {}
|
| 346 |
+
|
| 347 |
+
if len(batch_images) == 0:
|
| 348 |
+
return bboxes
|
| 349 |
+
|
| 350 |
+
print(f"Processing batch of {len(batch_images)} images")
|
| 351 |
+
|
| 352 |
+
# Get original image dimensions for scaling
|
| 353 |
+
height, width = batch_images[0].shape[:2]
|
| 354 |
+
scale = 640.0
|
| 355 |
+
x_scale = width / scale
|
| 356 |
+
y_scale = height / scale
|
| 357 |
+
|
| 358 |
+
# Memory optimization: Process smaller batches if needed
|
| 359 |
+
max_batch_size = 32 # Reduce batch size further to prevent memory issues
|
| 360 |
+
if len(batch_images) > max_batch_size:
|
| 361 |
+
print(f"Large batch detected ({len(batch_images)} images), splitting into smaller batches of {max_batch_size}")
|
| 362 |
+
# Process in smaller chunks
|
| 363 |
+
all_bboxes = {}
|
| 364 |
+
for chunk_start in range(0, len(batch_images), max_batch_size):
|
| 365 |
+
chunk_end = min(chunk_start + max_batch_size, len(batch_images))
|
| 366 |
+
chunk_images = batch_images[chunk_start:chunk_end]
|
| 367 |
+
chunk_offset = offset + chunk_start
|
| 368 |
+
print(f"Processing chunk {chunk_start//max_batch_size + 1}: images {chunk_start}-{chunk_end-1}")
|
| 369 |
+
chunk_bboxes = self._detect_objects_batch(chunk_images, chunk_offset)
|
| 370 |
+
all_bboxes.update(chunk_bboxes)
|
| 371 |
+
return all_bboxes
|
| 372 |
+
|
| 373 |
+
# Preprocess images for ONNX inference
|
| 374 |
+
imgs = self._pre_process_img(batch_images, scale)
|
| 375 |
+
actual_batch_size = len(batch_images)
|
| 376 |
+
|
| 377 |
+
# Handle batch size mismatch - pad if needed
|
| 378 |
+
model_batch_size = self.bbox_model.get_inputs()[0].shape[0]
|
| 379 |
+
print(f"Model input shape: {self.bbox_model.get_inputs()[0].shape}, batch_size: {model_batch_size}")
|
| 380 |
+
|
| 381 |
+
if model_batch_size is not None:
|
| 382 |
+
try:
|
| 383 |
+
# Handle dynamic batch size (None, -1, 'None')
|
| 384 |
+
if str(model_batch_size) in ['None', '-1'] or model_batch_size == -1:
|
| 385 |
+
model_batch_size = None
|
| 386 |
+
else:
|
| 387 |
+
model_batch_size = int(model_batch_size)
|
| 388 |
+
except (ValueError, TypeError):
|
| 389 |
+
model_batch_size = None
|
| 390 |
+
|
| 391 |
+
print(f"Processed model_batch_size: {model_batch_size}, actual_batch_size: {actual_batch_size}")
|
| 392 |
+
|
| 393 |
+
if model_batch_size and actual_batch_size < model_batch_size:
|
| 394 |
+
padding_size = model_batch_size - actual_batch_size
|
| 395 |
+
dummy_img = np.zeros((1, 3, int(scale), int(scale)), dtype=np.float32)
|
| 396 |
+
padding = np.repeat(dummy_img, padding_size, axis=0)
|
| 397 |
+
imgs = np.vstack([imgs, padding])
|
| 398 |
+
|
| 399 |
+
# ONNX inference with error handling
|
| 400 |
+
try:
|
| 401 |
+
input_name = self.bbox_model.get_inputs()[0].name
|
| 402 |
+
import time
|
| 403 |
+
start_time = time.time()
|
| 404 |
+
outputs = self.bbox_model.run(None, {input_name: imgs})[0]
|
| 405 |
+
inference_time = time.time() - start_time
|
| 406 |
+
print(f"Inference time: {inference_time:.3f}s for {actual_batch_size} images")
|
| 407 |
+
|
| 408 |
+
# Remove padded results if we added padding
|
| 409 |
+
if model_batch_size and isinstance(model_batch_size, int) and actual_batch_size < model_batch_size:
|
| 410 |
+
outputs = outputs[:actual_batch_size]
|
| 411 |
+
|
| 412 |
+
# Post-process outputs to get detections
|
| 413 |
+
raw_results = self._post_process_output(np.array(outputs), x_scale, y_scale)
|
| 414 |
+
|
| 415 |
+
except Exception as e:
|
| 416 |
+
print(f"Error during ONNX inference: {e}")
|
| 417 |
+
return bboxes
|
| 418 |
+
|
| 419 |
+
if not raw_results:
|
| 420 |
+
return bboxes
|
| 421 |
+
|
| 422 |
+
# Convert raw results to BoundingBox objects and apply processing
|
| 423 |
+
for frame_idx_in_batch, frame_detections in enumerate(raw_results):
|
| 424 |
+
if not frame_detections:
|
| 425 |
+
continue
|
| 426 |
+
|
| 427 |
+
# Convert to BoundingBox objects
|
| 428 |
+
boxes: List[BoundingBox] = []
|
| 429 |
+
for box, conf, cls_id in frame_detections:
|
| 430 |
+
x1, y1, x2, y2 = box
|
| 431 |
+
if int(cls_id) < 4:
|
| 432 |
+
boxes.append(
|
| 433 |
+
BoundingBox(
|
| 434 |
+
x1=int(x1),
|
| 435 |
+
y1=int(y1),
|
| 436 |
+
x2=int(x2),
|
| 437 |
+
y2=int(y2),
|
| 438 |
+
cls_id=int(cls_id),
|
| 439 |
+
conf=float(conf),
|
| 440 |
+
)
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
# Handle footballs - keep only the best one
|
| 444 |
+
footballs = [bb for bb in boxes if int(bb.cls_id) == 0]
|
| 445 |
+
if len(footballs) > 1:
|
| 446 |
+
best_ball = max(footballs, key=lambda b: b.conf)
|
| 447 |
+
boxes = [bb for bb in boxes if int(bb.cls_id) != 0]
|
| 448 |
+
boxes.append(best_ball)
|
| 449 |
+
|
| 450 |
+
# Remove overlapping small boxes
|
| 451 |
+
boxes = suppress_small_contained_boxes(boxes, self.SMALL_CONTAINED_IOA, self.SMALL_RATIO_MAX)
|
| 452 |
+
|
| 453 |
+
# Handle goalkeeper detection issues:
|
| 454 |
+
# 1. Fix misplaced goalkeepers (convert to players if standing in middle)
|
| 455 |
+
# 2. Allow up to 2 goalkeepers maximum (one from each team)
|
| 456 |
+
# Goalkeepers remain class_id = 1 (no team assignment)
|
| 457 |
+
boxes = self._handle_multiple_goalkeepers(boxes)
|
| 458 |
+
|
| 459 |
+
# Store results (players still have class_id=2, will be classified in phase 2)
|
| 460 |
+
frame_id = offset + frame_idx_in_batch
|
| 461 |
+
bboxes[frame_id] = boxes
|
| 462 |
+
|
| 463 |
+
return bboxes
|
| 464 |
+
|
| 465 |
+
def predict_batch(self, batch_images: List[ndarray], offset: int, n_keypoints: int) -> List[TVFrameResult]:
|
| 466 |
+
bboxes: Dict[int, List[BoundingBox]] = {}
|
| 467 |
+
|
| 468 |
+
bboxes = self._detect_objects_batch(batch_images, offset)
|
| 469 |
+
if bboxes:
|
| 470 |
+
bboxes, self.team_classifier_fitted, self.player_crops_for_fit = classify_teams_batch(
|
| 471 |
+
self.team_classifier,
|
| 472 |
+
self.team_classifier_fitted,
|
| 473 |
+
self.player_crops_for_fit,
|
| 474 |
+
batch_images,
|
| 475 |
+
bboxes,
|
| 476 |
+
offset,
|
| 477 |
+
self.MIN_SAMPLES_FOR_FIT,
|
| 478 |
+
self.MAX_SAMPLES_FOR_FIT,
|
| 479 |
+
self.SINGLE_PLAYER_HUE_PIVOT
|
| 480 |
+
)
|
| 481 |
+
self.team_classifier_fitted = False
|
| 482 |
+
self.player_crops_for_fit = []
|
| 483 |
+
|
| 484 |
+
pitch_batch_size = min(self.pitch_batch_size, len(batch_images))
|
| 485 |
+
keypoints: Dict[int, List[Tuple[int, int]]] = {}
|
| 486 |
+
while True:
|
| 487 |
+
# try:
|
| 488 |
+
gc.collect()
|
| 489 |
+
if torch.cuda.is_available():
|
| 490 |
+
tf.keras.backend.clear_session()
|
| 491 |
+
torch.cuda.empty_cache()
|
| 492 |
+
torch.cuda.synchronize()
|
| 493 |
+
device_str = "cuda" if torch.cuda.is_available() else "cpu"
|
| 494 |
+
keypoints_result = process_batch_input(
|
| 495 |
+
batch_images,
|
| 496 |
+
self.keypoints_model,
|
| 497 |
+
self.kp_threshold,
|
| 498 |
+
device_str,
|
| 499 |
+
batch_size=pitch_batch_size,
|
| 500 |
+
)
|
| 501 |
+
if keypoints_result is not None and len(keypoints_result) > 0:
|
| 502 |
+
for frame_number_in_batch, kp_dict in enumerate(keypoints_result):
|
| 503 |
+
if frame_number_in_batch >= len(batch_images):
|
| 504 |
+
break
|
| 505 |
+
frame_keypoints: List[Tuple[int, int]] = []
|
| 506 |
+
try:
|
| 507 |
+
height, width = batch_images[frame_number_in_batch].shape[:2]
|
| 508 |
+
if kp_dict is not None and isinstance(kp_dict, dict):
|
| 509 |
+
for idx in range(32):
|
| 510 |
+
x, y = 0, 0
|
| 511 |
+
kp_idx = idx + 1
|
| 512 |
+
if kp_idx in kp_dict:
|
| 513 |
+
try:
|
| 514 |
+
kp_data = kp_dict[kp_idx]
|
| 515 |
+
if isinstance(kp_data, dict) and "x" in kp_data and "y" in kp_data:
|
| 516 |
+
x = int(kp_data["x"] * width)
|
| 517 |
+
y = int(kp_data["y"] * height)
|
| 518 |
+
except (KeyError, TypeError, ValueError):
|
| 519 |
+
pass
|
| 520 |
+
frame_keypoints.append((x, y))
|
| 521 |
+
except (IndexError, ValueError, AttributeError):
|
| 522 |
+
frame_keypoints = [(0, 0)] * 32
|
| 523 |
+
if len(frame_keypoints) < n_keypoints:
|
| 524 |
+
frame_keypoints.extend([(0, 0)] * (n_keypoints - len(frame_keypoints)))
|
| 525 |
+
else:
|
| 526 |
+
frame_keypoints = frame_keypoints[:n_keypoints]
|
| 527 |
+
keypoints[offset + frame_number_in_batch] = frame_keypoints
|
| 528 |
+
print("✅ Keypoints predicted")
|
| 529 |
+
break
|
| 530 |
+
# except RuntimeError as e:
|
| 531 |
+
# print(self.pitch_batch_size)
|
| 532 |
+
# print(e)
|
| 533 |
+
# if "out of memory" in str(e):
|
| 534 |
+
# if self.pitch_batch_size == 1:
|
| 535 |
+
# break
|
| 536 |
+
# self.pitch_batch_size = self.pitch_batch_size // 2 if self.pitch_batch_size > 1 else 1
|
| 537 |
+
# pitch_batch_size = min(self.pitch_batch_size, len(batch_images))
|
| 538 |
+
# else:
|
| 539 |
+
# break
|
| 540 |
+
# except Exception as e:
|
| 541 |
+
# print(f"❌ Error during keypoints prediction: {e}")
|
| 542 |
+
# break
|
| 543 |
+
|
| 544 |
+
results: List[TVFrameResult] = []
|
| 545 |
+
for frame_number in range(offset, offset + len(batch_images)):
|
| 546 |
+
frame_boxes = bboxes.get(frame_number, [])
|
| 547 |
+
frame_keypoints = keypoints.get(frame_number, [(0, 0) for _ in range(n_keypoints)])
|
| 548 |
+
result = TVFrameResult(
|
| 549 |
+
frame_id=frame_number,
|
| 550 |
+
boxes=frame_boxes,
|
| 551 |
+
keypoints=frame_keypoints,
|
| 552 |
+
)
|
| 553 |
+
results.append(result)
|
| 554 |
+
|
| 555 |
+
gc.collect()
|
| 556 |
+
if torch.cuda.is_available():
|
| 557 |
+
tf.keras.backend.clear_session()
|
| 558 |
+
torch.cuda.empty_cache()
|
| 559 |
+
torch.cuda.synchronize()
|
| 560 |
+
|
| 561 |
+
return results
|
objdetect.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7b51470cb703f5a9a789df38674b67d4bbe7f8f31846d69dbc97ce484f790cf9
|
| 3 |
+
size 10245169
|
osnet_ain.pyc
ADDED
|
Binary file (24.2 kB). View file
|
|
|
osnet_model.pth.tar-100
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:64873ef0e8abf28df31facd113f27634e2d085a2dcf8d19123409b1d0e2566c8
|
| 3 |
+
size 36189526
|
pitch.py
ADDED
|
@@ -0,0 +1,688 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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):
|
| 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.from_numpy(np.stack(batch)).float()
|
| 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 |
+
# Get the device from the model itself
|
| 614 |
+
model_device = next(model.parameters()).device
|
| 615 |
+
print(model_device)
|
| 616 |
+
|
| 617 |
+
# Process all frames in optimally-sized batches
|
| 618 |
+
for i in range(0, num_frames, batch_size):
|
| 619 |
+
current_batch_size = min(batch_size, num_frames - i)
|
| 620 |
+
batch_frames = frames[i:i + current_batch_size]
|
| 621 |
+
|
| 622 |
+
# Fast preprocessing - create on CPU first
|
| 623 |
+
batch = preprocess_batch_fast(batch_frames)
|
| 624 |
+
b, c, h, w = batch.size()
|
| 625 |
+
|
| 626 |
+
# Move batch to model device
|
| 627 |
+
batch = batch.to(model_device)
|
| 628 |
+
|
| 629 |
+
with torch.no_grad():
|
| 630 |
+
heatmaps = model(batch)
|
| 631 |
+
|
| 632 |
+
# Ultra-fast keypoint extraction
|
| 633 |
+
kp_coords = extract_keypoints_from_heatmap_fast(heatmaps[:,:-1,:,:], scale=2, max_keypoints=1)
|
| 634 |
+
|
| 635 |
+
# Vectorized batch processing - no loops
|
| 636 |
+
batch_results = process_keypoints_vectorized(kp_coords, kp_threshold, 960, 540, current_batch_size)
|
| 637 |
+
results.extend(batch_results)
|
| 638 |
+
|
| 639 |
+
# Minimal cleanup
|
| 640 |
+
del heatmaps, kp_coords, batch
|
| 641 |
+
|
| 642 |
+
return results
|
| 643 |
+
|
| 644 |
+
# Keypoint mapping from detection indices to standard football pitch keypoint IDs
|
| 645 |
+
map_keypoints = {
|
| 646 |
+
1: 1, 2: 14, 3: 25, 4: 2, 5: 10, 6: 18, 7: 26, 8: 3, 9: 7, 10: 23,
|
| 647 |
+
11: 27, 20: 4, 21: 8, 22: 24, 23: 28, 24: 5, 25: 13, 26: 21, 27: 29,
|
| 648 |
+
28: 6, 29: 17, 30: 30, 31: 11, 32: 15, 33: 19, 34: 12, 35: 16, 36: 20,
|
| 649 |
+
45: 9, 50: 31, 52: 32, 57: 22
|
| 650 |
+
}
|
| 651 |
+
|
| 652 |
+
def get_mapped_keypoints(kp_points):
|
| 653 |
+
"""Apply keypoint mapping to detection results"""
|
| 654 |
+
mapped_points = {}
|
| 655 |
+
for key, value in kp_points.items():
|
| 656 |
+
if key in map_keypoints:
|
| 657 |
+
mapped_key = map_keypoints[key]
|
| 658 |
+
mapped_points[mapped_key] = value
|
| 659 |
+
# else:
|
| 660 |
+
# Keep unmapped keypoints with original key
|
| 661 |
+
# mapped_points[key] = value
|
| 662 |
+
return mapped_points
|
| 663 |
+
|
| 664 |
+
def process_batch_input(frames, model, kp_threshold, device, batch_size=8):
|
| 665 |
+
"""Process multiple input images in batch"""
|
| 666 |
+
# Batch inference
|
| 667 |
+
kp_results = inference_batch(frames, model, kp_threshold, device, batch_size)
|
| 668 |
+
kp_results = [get_mapped_keypoints(kp) for kp in kp_results]
|
| 669 |
+
# Draw results and save
|
| 670 |
+
# for i, (frame, kp_points, input_path) in enumerate(zip(frames, kp_results, valid_paths)):
|
| 671 |
+
# height, width = frame.shape[:2]
|
| 672 |
+
|
| 673 |
+
# # Apply mapping to get standard keypoint IDs
|
| 674 |
+
# mapped_kp_points = get_mapped_keypoints(kp_points)
|
| 675 |
+
|
| 676 |
+
# for key, value in mapped_kp_points.items():
|
| 677 |
+
# x = int(value['x'] * width)
|
| 678 |
+
# y = int(value['y'] * height)
|
| 679 |
+
# cv2.circle(frame, (x, y), 5, (0, 255, 0), -1) # Green circles
|
| 680 |
+
# cv2.putText(frame, str(key), (x+10, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
|
| 681 |
+
|
| 682 |
+
# # Save result
|
| 683 |
+
# output_path = input_path.replace('.png', '_result.png').replace('.jpg', '_result.jpg')
|
| 684 |
+
# cv2.imwrite(output_path, frame)
|
| 685 |
+
|
| 686 |
+
# print(f"Batch processing complete. Processed {len(frames)} images.")
|
| 687 |
+
|
| 688 |
+
return kp_results
|
team_cluster.pyc
ADDED
|
Binary file (7.62 kB). View file
|
|
|
utils.pyc
ADDED
|
Binary file (20.6 kB). View file
|
|
|