delvek commited on
Commit
d262279
·
verified ·
1 Parent(s): e5c1b0e

Versalit Match-Analytics: pesos, código e model card

Browse files
.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
+ demo/match-events.gif filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
16
+
17
+ Copyright 2026 Delvek de Sousa · Versalit — https://versalit.ia.br
README.md ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - pt
5
+ - en
6
+ library_name: pytorch
7
+ pipeline_tag: object-detection
8
+ tags:
9
+ - sports-analytics
10
+ - football
11
+ - event-camera
12
+ - dvs
13
+ - spiking-neural-network
14
+ - snn
15
+ - neuromorphic
16
+ - kalman-filter
17
+ - pytorch
18
+ - from-scratch
19
+ - versalit
20
+ ---
21
+
22
+ # Versalit Match-Analytics · análise de partida de futebol com pipeline neuromórfica
23
+
24
+ <p align="center"><strong>Versalit</strong> &mdash; engenharia de IA e software em produção</p>
25
+
26
+ Pipeline de análise de futebol sem YOLO e sem modelo pré-treinado: o vídeo vira eventos de uma câmera neuromórfica simulada, uma **Spiking Neural Network** decide o que é jogador, um filtro de Kalman mantém a identidade de cada um, o k-means separa os times pela cor do uniforme e uma homografia leva tudo para um radar 2D, em metros, com zonas de controle de cada time.
27
+
28
+ **Autor:** Delvek de Sousa — Engenheiro de IA & Pesquisador da UFPA
29
+
30
+ Página do modelo, com explicação completa: [versalit.ia.br/modelos/match-analytics.html](https://versalit.ia.br/modelos/match-analytics.html)
31
+
32
+ > **English summary.** Football analytics built on simulated event-camera (DVS) data: event clustering gives exact positions, a 595K-parameter spiking network keeps only player blobs (**97.1%** agreement with rule-based auto-labels on 6,506 held-out blobs), a from-scratch Kalman tracker keeps IDs, from-scratch k-means splits teams by jersey colour, and a 4-point homography drives a 2D radar with Voronoi control zones and distance covered per team. An experimental end-to-end SNN detector (CenterNet-style, 186K params) is included: precision 0.85 / recall 0.31 on a clip outside its training data. Apache-2.0.
33
+
34
+ <p align="center"><img src="demo/match-events.gif" alt="Match-Analytics: eventos DVS dos jogadores com ID e cor do time, radar 2D com zonas de controle e distância percorrida por time" width="90%"></p>
35
+
36
+ <sub>O que a pipeline enxerga: eventos ON/OFF (ciano e magenta), jogadores com ID e cor do time, radar com zonas de controle (Voronoi) e distância percorrida por time. Esta versão da demonstração não mostra a imagem da transmissão original.</sub>
37
+
38
+ | dado | valor |
39
+ |------|-------|
40
+ | Tarefa | posição, identidade e time de cada jogador + radar 2D |
41
+ | Classificador de jogador | SNN, 595.154 parâmetros, 10 passos de tempo |
42
+ | Acerto do classificador | **97,1%** de concordância com os auto-rótulos (6.506 aglomerados de teste) |
43
+ | Detector ponta a ponta (experimental) | SNN estilo CenterNet, 185.603 parâmetros, precisão 0,85 / recall 0,31 |
44
+ | Rótulos | automáticos, nenhuma anotação manual |
45
+ | Licença | Apache-2.0 |
46
+
47
+ ---
48
+
49
+ ## Como funciona
50
+
51
+ ```
52
+ vídeo → eventos DVS (com compensação do movimento da câmera por correlação de fase)
53
+ → aglomerados de eventos = posições
54
+ → SNN classifica cada aglomerado: jogador ou ruído
55
+ → filtro de Kalman [x, y, vx, vy] com custo de cor e forma = ID por jogador
56
+ → k-means na cor do uniforme (tronco, sem o verde do gramado) = times
57
+ → homografia de 4 pontos → posição em metros → radar 2D + zonas de Voronoi + distância por time
58
+ ```
59
+
60
+ | etapa | implementação |
61
+ |---|---|
62
+ | Eventos | DVS simulado: contraste em log-intensidade, referência adaptativa |
63
+ | Jogador ou ruído | **SNN** (2 convoluções + LIF, camada densa de 128, saída acumulando potencial) |
64
+ | Rastreamento | filtro de Kalman escrito do zero |
65
+ | Times | k-means escrito do zero, em RGB |
66
+ | Radar | homografia calibrada com 4 pontos do campo (arquivos `calib_*.json`) |
67
+
68
+ ## Métricas
69
+
70
+ **Classificador de jogador:** 15% de teste, sorteado dos 43.377 aglomerados auto-rotulados.
71
+
72
+ | | valor |
73
+ |---|---|
74
+ | **Concordância geral** | **97,1%** |
75
+ | Jogador | 96,8% |
76
+ | Ruído | 97,4% |
77
+
78
+ Os rótulos vêm de uma regra (jogador = dentro do campo e com proporção de pessoa). Os 97,1% medem o quanto a SNN reproduz essa regra, não uma comparação com anotação humana.
79
+
80
+ **Detector ponta a ponta (experimental):** treinado com auto-rótulos de três clipes e avaliado em 600 quadros de um quarto clipe, fora do treino: **precisão 0,85, recall 0,31**. Ele acerta quando aponta um jogador, mas perde a maioria: jogador parado não gera evento, e o detector não tem como vê-lo. Por isso a demonstração usa o caminho aglomerado + classificador.
81
+
82
+ ---
83
+
84
+ ## Uso rápido
85
+
86
+ ```bash
87
+ git clone https://huggingface.co/delvek/versalit-match-analytics
88
+ cd versalit-match-analytics
89
+ pip install -r requirements.txt
90
+
91
+ # partida + radar + estatísticas (calibre a homografia do seu vídeo em um calib_*.json)
92
+ python -m src.demo_match partida.mp4 --calib calib_m02.json --use-events -o saida.mp4
93
+ ```
94
+
95
+ ### Calibração
96
+
97
+ Cada `calib_*.json` liga 4 pontos da imagem (pixels) a 4 pontos do campo (metros, 105×68):
98
+
99
+ ```json
100
+ {"src": [[18, 162], [854, 92], [854, 338], [58, 468]],
101
+ "dst": [[0, 0], [105, 0], [105, 68], [0, 68]]}
102
+ ```
103
+
104
+ ### Treinar de novo
105
+
106
+ ```bash
107
+ python -m src.harvest_players "partida.mp4:0.3:0.4" # aglomerados auto-rotulados → data_players/players.npz
108
+ python -m src.train_player # classificador de jogador
109
+ python -m src.auto_label partida.mp4 # auto-rótulos para o detector
110
+ python -m src.train_detector --epochs 40 # detector ponta a ponta (experimental)
111
+ python eval_detector.py outro_clipe.mp4 # precisão e recall contra os auto-rótulos
112
+ ```
113
+
114
+ Os vídeos e os dados derivados usados no treino original não são redistribuídos aqui; use vídeos que você tenha direito de usar.
115
+
116
+ ---
117
+
118
+ ## Estrutura do repositório
119
+
120
+ ```
121
+ src/events.py simulador de câmera de eventos (DVS)
122
+ src/auto_label.py aglomerados de eventos e auto-rótulos
123
+ src/player_snn.py SNN classificadora de jogador
124
+ src/snn_detector.py detector SNN ponta a ponta (experimental)
125
+ src/tracker.py filtro de Kalman, associação e compensação de câmera
126
+ src/teams.py k-means de cor de uniforme
127
+ src/homography.py homografia e desenho do campo
128
+ src/demo_match.py pipeline completa
129
+ checkpoints/ player_snn.pt e snn_detector.pt
130
+ calib_m02.json, calib_f04.json
131
+ ```
132
+
133
+ ## Limitações
134
+
135
+ - Jogador parado não gera evento. O Kalman segura a trilha por alguns quadros; o detector ponta a ponta simplesmente não o vê.
136
+ - Os rótulos são automáticos: o classificador herda os acertos e os erros da regra.
137
+ - A homografia é calibrada à mão para cada enquadramento; câmera que dá zoom ou muda de plano precisa de recalibração.
138
+ - Jogadores colados viram um aglomerado só, e times com uniformes de cor parecida confundem o k-means.
139
+
140
+ ---
141
+
142
+ ## Citação
143
+
144
+ ```bibtex
145
+ @misc{versalit2026match,
146
+ title = {Versalit Match-Analytics: análise de futebol com pipeline neuromórfica},
147
+ author = {de Sousa, Delvek},
148
+ year = {2026},
149
+ url = {https://huggingface.co/delvek/versalit-match-analytics}
150
+ }
151
+ ```
152
+
153
+ ## Links
154
+
155
+ - **Modelos abertos da Versalit:** [versalit.ia.br/modelos](https://versalit.ia.br/modelos/)
156
+ - **Mesma série neuromórfica:** [SNN-OCR](https://huggingface.co/delvek/versalit-snn-ocr) · [SNN-Tracker](https://huggingface.co/delvek/versalit-snn-tracker) · [SNN-Forecast](https://huggingface.co/delvek/versalit-snn-forecast)
157
+ - **Coleção no Hugging Face:** [Versalit · Modelos abertos](https://huggingface.co/collections/delvek/versalit-modelos-abertos-6b0b97b74d46769c4e036f25)
158
+
159
+ ---
160
+
161
+ <p align="center">
162
+ Feito pela <strong>Versalit</strong> &mdash; engenharia de IA e software em produção.<br>
163
+ <strong>Delvek de Sousa</strong> &mdash; Engenheiro de IA &amp; Pesquisador da UFPA<br>
164
+ <a href="https://versalit.ia.br">versalit.ia.br</a>
165
+ </p>
calib_f04.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"src": [[295, 55], [1280, 105], [1280, 720], [12, 715]], "dst": [[0, 0], [40, 0], [40, 20], [0, 20]]}
calib_m02.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"src": [[18, 162], [854, 92], [854, 338], [58, 468]], "dst": [[0, 0], [105, 0], [105, 68], [0, 68]]}
checkpoints/player_snn.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1a72d9e697b0ec6cf1ec6f2d18acd30c1bee32d04255304711a0731bbe11d345
3
+ size 2384375
checkpoints/snn_detector.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5ee609a4b9aaf112cfbce72cc9677ac94ad9d918b18cbee71ab3d7cff2b53e07
3
+ size 747353
demo/match-events.gif ADDED

Git LFS Details

  • SHA256: e233936f049c8d2c0e7d263bcc784ca81a4e1a6abe12e1cf4eb1b5089214f838
  • Pointer size: 132 Bytes
  • Size of remote file: 1.36 MB
eval_detector.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Avaliacao honesta: SNN vs auto-labels (proxy de ground truth).
2
+ Precision/recall por frame com matching por centroide."""
3
+ import sys
4
+ from collections import deque
5
+
6
+ import cv2
7
+ import numpy as np
8
+ import torch
9
+
10
+ from src.events import DVSSimulator
11
+ from src.auto_label import detect_blobs, window_features
12
+ from src.snn_detector import EventDetectorSNN, decode
13
+
14
+ model = EventDetectorSNN()
15
+ model.load_state_dict(torch.load("checkpoints/snn_detector.pt",
16
+ map_location="cpu", weights_only=False))
17
+ model.eval()
18
+ device = "cuda" if torch.cuda.is_available() else "cpu"
19
+ model.to(device)
20
+
21
+ VIDEO = sys.argv[1] if len(sys.argv) > 1 else "raw/c3.mp4" # python eval_detector.py video.mp4
22
+ cap = cv2.VideoCapture(VIDEO) # video fora do clip de demo
23
+ dvs = DVSSimulator(size=(320, 240))
24
+ trail = deque(maxlen=3)
25
+ tp = fp = fn = 0
26
+ nfr = 0
27
+ while nfr < 600:
28
+ ok, f = cap.read()
29
+ if not ok:
30
+ break
31
+ nfr += 1
32
+ trail.append(dvs.process(f))
33
+ acc = np.clip(sum(trail), -1, 1)
34
+ gt = detect_blobs(acc)
35
+ x = torch.from_numpy(window_features(trail)).unsqueeze(0).to(device)
36
+ with torch.no_grad():
37
+ phm, psz = model(x)
38
+ pred = decode(phm.cpu(), psz.cpu(), thr=0.4)
39
+
40
+ used = set()
41
+ for pb in pred:
42
+ pc = np.array([pb[0] + pb[2] / 2, pb[1] + pb[3] / 2])
43
+ best, bd = None, 30
44
+ for i, gb in enumerate(gt):
45
+ if i in used:
46
+ continue
47
+ gc = np.array([gb[0] + gb[2] / 2, gb[1] + gb[3] / 2])
48
+ d = np.linalg.norm(pc - gc)
49
+ if d < bd:
50
+ best, bd = i, d
51
+ if best is not None:
52
+ tp += 1
53
+ used.add(best)
54
+ else:
55
+ fp += 1
56
+ fn += len(gt) - len(used)
57
+ cap.release()
58
+ print(f"TP={tp} FP={fp} FN={fn}")
59
+ print(f"precision={tp / max(tp + fp, 1):.2f} recall={tp / max(tp + fn, 1):.2f}")
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ torch>=2.4
2
+ numpy>=1.26
3
+ opencv-python>=4.8
4
+ Pillow>=10
src/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
src/auto_label.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Auto-labeling: jogadores em movimento geram blobs de eventos densos
2
+ -> caixas pseudo-labels pro treino do detector SNN. Zero anotacao manual.
3
+
4
+ Uso: python -m src.auto_label raw/m01.mp4 [mais videos]
5
+ """
6
+ import sys
7
+ from collections import deque
8
+ from pathlib import Path
9
+
10
+ import cv2
11
+ import numpy as np
12
+
13
+ from .events import DVSSimulator
14
+
15
+ EV_W, EV_H = 320, 240
16
+ GRID = 16 # stride da heatmap (320x240 -> 20x15)
17
+ MAX_PER_VIDEO = 250
18
+
19
+
20
+ def detect_blobs(acc, min_area=18, dilate_k=5, min_density=0.10):
21
+ raw = (acc != 0).astype(np.uint8)
22
+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (dilate_k, dilate_k))
23
+ mask = cv2.dilate(raw, kernel)
24
+ n, labels, stats, cents = cv2.connectedComponentsWithStats(mask)
25
+ boxes = []
26
+ for i in range(1, n):
27
+ x, y, w, h, area = stats[i]
28
+ if area < min_area or w < 4 or h < 5:
29
+ continue
30
+ if raw[labels == i].mean() < min_density:
31
+ continue
32
+ boxes.append((x, y, w, h))
33
+ return boxes
34
+
35
+
36
+ def window_features(trail):
37
+ """Ultimos 3 frames de eventos -> (2,240,320)."""
38
+ acc = np.clip(sum(trail), -1, 1)
39
+ return np.stack([np.clip(acc, 0, 1), np.clip(-acc, 0, 1)]).astype(np.float32)
40
+
41
+
42
+ def boxes_to_heatmap(boxes):
43
+ """Centros -> heatmap Gaussiana (15x20) + size map (2x15x20)."""
44
+ gh, gw = EV_H // GRID, EV_W // GRID
45
+ hm = np.zeros((gh, gw), np.float32)
46
+ size = np.zeros((2, gh, gw), np.float32)
47
+ for (x, y, w, h) in boxes:
48
+ cx, cy = (x + w / 2) / GRID, (y + h / 2) / GRID
49
+ gx, gy = min(int(cx), gw - 1), min(int(cy), gh - 1)
50
+ for dy in range(-1, 2):
51
+ for dx in range(-1, 2):
52
+ j, i = gy + dy, gx + dx
53
+ if 0 <= j < gh and 0 <= i < gw:
54
+ hm[j, i] = max(hm[j, i],
55
+ np.exp(-(dx * dx + dy * dy) / 2))
56
+ size[0, gy, gx], size[1, gy, gx] = w / EV_W, h / EV_H
57
+ return hm, size
58
+
59
+
60
+ def main():
61
+ out_dir = Path("data")
62
+ out_dir.mkdir(exist_ok=True)
63
+ n_saved = 0
64
+ for spec in sys.argv[1:]:
65
+ # vid ou vid:start_frac:end_frac (fracao do video, ex: 0.2:0.3)
66
+ parts = spec.rsplit(":", 2)
67
+ vid = parts[0]
68
+ fr0, fr1 = (float(parts[1]), float(parts[2])) if len(parts) == 3 else (0.0, 1.0)
69
+ cap = cv2.VideoCapture(vid)
70
+ total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
71
+ cap.set(cv2.CAP_PROP_POS_FRAMES, int(total * fr0))
72
+ dvs = DVSSimulator(size=(EV_W, EV_H))
73
+ trail = deque(maxlen=3)
74
+ cnt = fi = 0
75
+ end = int(total * fr1)
76
+ while cnt < MAX_PER_VIDEO and fi + total * fr0 < end:
77
+ ok, f = cap.read()
78
+ if not ok:
79
+ break
80
+ fi += 1
81
+ trail.append(dvs.process(f))
82
+ acc = np.clip(sum(trail), -1, 1)
83
+ boxes = detect_blobs(acc)
84
+ if not (2 <= len(boxes) <= 22): # cena plausivel de jogo
85
+ continue
86
+ hm, size = boxes_to_heatmap(boxes)
87
+ tag = spec.replace(":", "-").replace("/", "_").replace("\\", "_")
88
+ np.savez_compressed(out_dir / f"{Path(tag).stem}_{fi:05d}",
89
+ x=window_features(trail), hm=hm, size=size)
90
+ cnt += 1
91
+ cap.release()
92
+ n_saved += cnt
93
+ print(f"{spec}: {cnt} amostras")
94
+ print(f"total: {n_saved}")
95
+
96
+
97
+ if __name__ == "__main__":
98
+ main()
src/demo_match.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Demo de partida estilo videogame:
2
+ video full-frame -> olhos SNN nos jogadores -> radar inset com Voronoi.
3
+
4
+ Uso: python -m src.demo_match raw/clip.mp4 --calib calib_m02.json -o demo/match.mp4
5
+ """
6
+ import argparse
7
+ from collections import deque
8
+ from pathlib import Path
9
+
10
+ import cv2
11
+ import numpy as np
12
+ import torch
13
+
14
+ from .events import DVSSimulator
15
+ from .auto_label import detect_blobs, window_features
16
+ from .snn_detector import EventDetectorSNN, decode
17
+ from .player_snn import PlayerSNN, crop_events
18
+ from .tracker import Tracker, global_shift
19
+ from .teams import TeamClassifier, jersey_color
20
+ from .homography import Homography, draw_pitch, PITCH_W, PITCH_H
21
+
22
+ EV_W, EV_H = 320, 240
23
+ OUT_W, OUT_H = 1280, 720
24
+ TEAM_COLORS = [(0, 165, 255), (255, 80, 200)] # laranja / rosa
25
+ REF_COLOR = (200, 200, 200)
26
+ RADAR_W, RADAR_H = 420, 252
27
+
28
+
29
+ def voronoi_overlay(pitch_img, players):
30
+ """Colore regiao de controle por time (voronoi por jogador)."""
31
+ if not players:
32
+ return
33
+ h, w = pitch_img.shape[:2]
34
+ yy, xx = np.mgrid[0:h, 0:w]
35
+ best_d = np.full((h, w), 1e18)
36
+ best_t = np.zeros((h, w), np.int8)
37
+ for (px, py, team) in players:
38
+ d = (xx - px) ** 2 + (yy - py) ** 2
39
+ upd = d < best_d
40
+ best_d[upd] = d[upd]
41
+ best_t[upd] = team
42
+ ov = pitch_img.copy()
43
+ for tm, col in enumerate(TEAM_COLORS):
44
+ m = best_t == tm
45
+ ov[m] = (ov[m] * 0.45 + np.array(col) * 0.55).astype(np.uint8)
46
+ return ov
47
+
48
+
49
+ def main():
50
+ ap = argparse.ArgumentParser()
51
+ ap.add_argument("video")
52
+ ap.add_argument("--calib", default=None)
53
+ ap.add_argument("-o", "--out", default="demo/match.mp4")
54
+ ap.add_argument("--use-events", action="store_true")
55
+ args = ap.parse_args()
56
+
57
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
58
+ ck = Path("checkpoints/player_snn.pt")
59
+ use_snn = args.use_events and ck.exists()
60
+ model = None
61
+ if use_snn:
62
+ model = PlayerSNN().to(device)
63
+ model.load_state_dict(torch.load(ck, map_location="cpu",
64
+ weights_only=False))
65
+ model.eval()
66
+
67
+ cap = cv2.VideoCapture(args.video)
68
+ fps = cap.get(cv2.CAP_PROP_FPS) or 25
69
+ out = cv2.VideoWriter(args.out, cv2.VideoWriter_fourcc(*"mp4v"),
70
+ fps, (OUT_W, OUT_H))
71
+ dvs = DVSSimulator(size=(EV_W, EV_H))
72
+ tracker = Tracker(max_dist=35, max_misses=20, min_hits=4,
73
+ w_color=0.6, w_shape=0.4)
74
+ prev_gray = None
75
+ cum = np.zeros(2)
76
+ trail = deque(maxlen=3)
77
+ homo = Homography(args.calib)
78
+ teams = TeamClassifier()
79
+
80
+ dist = {}
81
+ last_pos = {}
82
+ team_assign = {}
83
+ fit_frames = 250
84
+ fit_colors = []
85
+
86
+ while True:
87
+ ok, frame = cap.read()
88
+ if not ok:
89
+ break
90
+ # ego-motion: deslocamento global da camera em EV-space
91
+ gray = cv2.resize(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY),
92
+ (EV_W, EV_H)).astype(np.float32) / 255.0
93
+ shift = global_shift(prev_gray, gray) if prev_gray is not None else (0.0, 0.0)
94
+ prev_gray = gray
95
+ trail.append(dvs.process(frame))
96
+ # janela ponderada: o frame recente domina (posicao atual, nao atrasada)
97
+ w = [0.55, 0.30, 0.15][-len(trail):] if len(trail) < 3 else [0.55, 0.30, 0.15]
98
+ acc = np.clip(sum(e * ww for e, ww in zip(list(trail)[::-1], w)), -1, 1)
99
+
100
+ # clustering de eventos = posicoes exatas; SNN filtra jogador vs ruido
101
+ boxes = detect_blobs(acc)
102
+ if use_snn and boxes:
103
+ xs = torch.stack([crop_events(acc, b) for b in boxes]).to(device)
104
+ with torch.no_grad():
105
+ keep = model(xs).argmax(1).cpu().numpy()
106
+ kept = [b for b, k in zip(boxes, keep) if k == 1]
107
+ # oclusao/flicker: blob perto de um track existente passa direto
108
+ for b, k in zip(boxes, keep):
109
+ if k == 1:
110
+ continue
111
+ cx, cy = b[0] + b[2] / 2, b[1] + b[3] / 2
112
+ if any(np.linalg.norm(t.centroid - (cx, cy)) < 22
113
+ for t in tracker.tracks):
114
+ kept.append(b)
115
+ boxes = kept
116
+ # so o campo: pe do blob em cima de grama (verde) + proporcao humana
117
+ small = cv2.resize(frame, (EV_W, EV_H))
118
+ def on_pitch(b):
119
+ fx_, fy_ = int(b[0] + b[2] / 2), int(b[1] + b[3])
120
+ if not (0 <= fy_ < EV_H and 0 <= fx_ < EV_W):
121
+ return False
122
+ px = small[max(0, fy_ - 3):fy_ + 2, max(0, fx_ - 3):fx_ + 3]
123
+ if px.size == 0:
124
+ return False
125
+ g = px.astype(np.float32)
126
+ return (g[:, :, 1] - 0.5 * (g[:, :, 0] + g[:, :, 2])).mean() > 12
127
+ boxes = [b for b in boxes
128
+ if b[1] + b[3] > EV_H * 0.25 and b[3] >= b[2] * 0.8
129
+ and b[2] <= 60 and b[3] <= 90
130
+ and EV_W * 0.02 < b[0] + b[2] / 2 < EV_W * 0.98
131
+ and on_pitch(b)]
132
+ merged = []
133
+ for b in sorted(boxes, key=lambda b: -(b[2] * b[3])):
134
+ cx, cy = b[0] + b[2] / 2, b[1] + b[3] / 2
135
+ if not any((cx - (m[0] + m[2] / 2)) ** 2 + (cy - (m[1] + m[3] / 2)) ** 2 < 12 ** 2
136
+ for m in merged):
137
+ merged.append(b)
138
+
139
+ fw, fh = frame.shape[1], frame.shape[0] # px do frame original
140
+ fx, fy = fw / EV_W, fh / EV_H # ev-space -> frame px
141
+ view = cv2.resize(frame, (OUT_W, OUT_H))
142
+ # cor do uniforme por box -> entra no custo de matching
143
+ # (box esta em espaco estabilizado -> +cum = coordenada no frame)
144
+ colors = [jersey_color(frame, ((b[0] + cum[0]) * fx, (b[1] + cum[1]) * fy,
145
+ b[2] * fx, b[3] * fy))
146
+ for b in merged]
147
+ tracks = tracker.step(merged, colors=colors) # ja estabilizado
148
+ kx, ky = OUT_W / EV_W, OUT_H / EV_H # ev-space -> canvas
149
+ players_radar = []
150
+
151
+ for t in tracks:
152
+ x, y, w, h = t.box
153
+ foot_x, foot_y = (x + w / 2) * kx, (y + h) * ky
154
+ col = jersey_color(view, ((x + cum[0]) * kx, (y + cum[1]) * ky,
155
+ w * kx, h * ky))
156
+ if fit_frames > 0 and col is not None:
157
+ fit_colors.append(col)
158
+ if col is not None:
159
+ vote = teams.predict(col)
160
+ if vote >= 0:
161
+ t.team_votes = getattr(t, "team_votes", []) + [vote]
162
+ t.team_votes = t.team_votes[-15:]
163
+ if getattr(t, "team_votes", None):
164
+ team = max(set(t.team_votes), key=t.team_votes.count)
165
+ team_assign[t.id] = team
166
+ else:
167
+ team = team_assign.get(t.id, -1)
168
+ color = TEAM_COLORS[team] if team >= 0 else REF_COLOR
169
+
170
+ if t.misses > 12:
171
+ continue
172
+ ex, ey = int((x + w / 2 + cum[0]) * kx), int((y + h - h * 0.15 + cum[1]) * ky)
173
+ pts = [(int((c[0] + cum[0]) * kx), int((c[1] + cum[1]) * ky))
174
+ for c in t.trail[-12:]]
175
+ for a, b in zip(pts, pts[1:]):
176
+ if abs(a[0] - b[0]) + abs(a[1] - b[1]) < 80: # sem saltos
177
+ cv2.line(view, a, b, color, 2)
178
+ cv2.ellipse(view, (ex, ey), (16, 9), 0, 0, 360, color, 3)
179
+ cv2.circle(view, (ex, ey), 5, color, -1)
180
+ cv2.ellipse(view, (ex, ey), (16, 9), 0, 0, 360, (255, 255, 255), 1)
181
+ cv2.putText(view, str(t.id), (ex + 20, ey - 12),
182
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
183
+
184
+ m = homo.map((x + w / 2 + cum[0]) * fx, (y + h + cum[1]) * fy)
185
+ if m:
186
+ rx = int(m[0] / PITCH_W * RADAR_W)
187
+ ry = int(m[1] / PITCH_H * RADAR_H)
188
+ players_radar.append((rx, ry, team))
189
+ if t.id in last_pos:
190
+ d = np.linalg.norm(np.array(m) - last_pos[t.id])
191
+ if d < 3:
192
+ dist[t.id] = dist.get(t.id, 0) + d * (105 / PITCH_W)
193
+ last_pos[t.id] = np.array(m)
194
+
195
+ fit_frames -= 1
196
+ if fit_frames == 0 and fit_colors:
197
+ teams.fit(fit_colors)
198
+ print("times calibrados:", len(fit_colors), "amostras")
199
+
200
+ # radar inset bottom-right com voronoi
201
+ radar = cv2.resize(draw_pitch()[80:320], (RADAR_W, RADAR_H))
202
+ radar = voronoi_overlay(radar, players_radar) if players_radar else radar
203
+ for (rx, ry, team) in players_radar:
204
+ c = TEAM_COLORS[team] if team >= 0 else REF_COLOR
205
+ cv2.circle(radar, (rx, ry), 5, c, -1)
206
+ cv2.circle(radar, (rx, ry), 6, (255, 255, 255), 1)
207
+ view[OUT_H - RADAR_H - 14:OUT_H - 14, OUT_W - RADAR_W - 14:OUT_W - 14] = radar
208
+ cv2.rectangle(view, (OUT_W - RADAR_W - 14, OUT_H - RADAR_H - 14),
209
+ (OUT_W - 14, OUT_H - 14), (255, 255, 255), 1)
210
+
211
+ # header stats
212
+ a_dist = sum(d for tid, d in dist.items() if team_assign.get(tid) == 0)
213
+ b_dist = sum(d for tid, d in dist.items() if team_assign.get(tid) == 1)
214
+ hud = np.zeros((64, OUT_W, 3), np.uint8)
215
+ cv2.putText(hud, "MATCH ANALYTICS | SNN events + Kalman", (20, 40),
216
+ cv2.FONT_HERSHEY_SIMPLEX, 0.9, (220, 220, 220), 2)
217
+ cv2.putText(hud, f"Time A {a_dist:.0f}m", (OUT_W - 420, 40),
218
+ cv2.FONT_HERSHEY_SIMPLEX, 0.8, TEAM_COLORS[0], 2)
219
+ cv2.putText(hud, f"Time B {b_dist:.0f}m", (OUT_W - 200, 40),
220
+ cv2.FONT_HERSHEY_SIMPLEX, 0.8, TEAM_COLORS[1], 2)
221
+ view[:64] = cv2.addWeighted(view[:64], 0.35, hud, 0.65, 0)
222
+
223
+ out.write(view)
224
+
225
+ cap.release()
226
+ out.release()
227
+ print(f"salvo: {args.out}")
228
+
229
+
230
+ if __name__ == "__main__":
231
+ main()
src/events.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Simulador DVS: frames -> eventos ON/OFF por contraste temporal."""
2
+ import cv2
3
+ import numpy as np
4
+
5
+
6
+ class DVSSimulator:
7
+ def __init__(self, size=(320, 240), threshold=0.15):
8
+ self.size = size
9
+ self.th = threshold
10
+ self.ref = None
11
+
12
+ def reset(self):
13
+ self.ref = None
14
+
15
+ def process(self, frame):
16
+ g = cv2.resize(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY),
17
+ self.size).astype(np.float32) / 255.0
18
+ if self.ref is None:
19
+ self.ref = g
20
+ return np.zeros(self.size[::-1], np.float32)
21
+ diff = np.log(g + 1e-3) - np.log(self.ref + 1e-3)
22
+ self.ref = 0.95 * self.ref + 0.05 * g # referencia adaptativa
23
+ ev = np.clip(diff / self.th, -1, 1).astype(np.float32)
24
+ ev[np.abs(ev) < 0.3] = 0
25
+ return ev
src/harvest_players.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Coleta blobs de eventos com auto-label por posicao:
2
+ dentro do campo = jogador (1); fora (arquibancada, placas, bordas) = ruido (0).
3
+
4
+ Uso: python -m src.harvest_players "raw/m02.mp4:0.3:0.4" ...
5
+ """
6
+ import sys
7
+ from collections import deque
8
+ from pathlib import Path
9
+
10
+ import cv2
11
+ import numpy as np
12
+
13
+ from .events import DVSSimulator
14
+ from .auto_label import detect_blobs
15
+ from .player_snn import crop_events
16
+
17
+ EV_W, EV_H = 320, 240
18
+ MAX = 400
19
+
20
+
21
+ def label_of(box):
22
+ """Jogador = dentro do campo E proporcao de pessoa (h>w, tamanho ok).
23
+ Fora, gigante/achatado/grudado = ruido."""
24
+ x, y, w, h = box
25
+ cy = y + h
26
+ inside = cy > EV_H * 0.25 and EV_W * 0.03 < x + w / 2 < EV_W * 0.97
27
+ person_shape = (8 <= h <= 55 and 4 <= w <= 30 and h >= w * 0.9)
28
+ return 1 if (inside and person_shape) else 0
29
+
30
+
31
+ def main():
32
+ out = Path("data_players")
33
+ out.mkdir(exist_ok=True)
34
+ X, Y = [], []
35
+ for spec in sys.argv[1:]:
36
+ parts = spec.rsplit(":", 2)
37
+ vid = parts[0]
38
+ fr0, fr1 = (float(parts[1]), float(parts[2])) if len(parts) == 3 else (0.0, 1.0)
39
+ cap = cv2.VideoCapture(vid)
40
+ total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
41
+ cap.set(cv2.CAP_PROP_POS_FRAMES, int(total * fr0))
42
+ dvs = DVSSimulator(size=(EV_W, EV_H))
43
+ trail = deque(maxlen=3)
44
+ cnt = fi = 0
45
+ while cnt < MAX and fi + total * fr0 < total * fr1:
46
+ ok, f = cap.read()
47
+ if not ok:
48
+ break
49
+ fi += 1
50
+ trail.append(dvs.process(f))
51
+ acc = np.clip(sum(trail), -1, 1)
52
+ boxes = detect_blobs(acc)
53
+ if not boxes:
54
+ continue
55
+ for b in boxes:
56
+ X.append(crop_events(acc, b).numpy())
57
+ Y.append(label_of(b))
58
+ cnt += 1
59
+ cap.release()
60
+ print(f"{spec}: {len(Y)} blobs")
61
+ np.savez_compressed(out / "players.npz",
62
+ x=np.stack(X), y=np.array(Y))
63
+ u, c = np.unique(Y, return_counts=True)
64
+ print(dict(zip(u.tolist(), c.tolist())), "total:", len(Y))
65
+
66
+
67
+ if __name__ == "__main__":
68
+ main()
src/homography.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Homografia: pontos calibrados do campo -> mapa 2D do radar.
2
+
3
+ Calibra uma vez por video (pontos visuais no frame), depois projeta
4
+ o pe de cada jogador pro espaco do campo (unidades arbitrarias 100x60).
5
+ """
6
+ import json
7
+ from pathlib import Path
8
+
9
+ import cv2
10
+ import numpy as np
11
+
12
+ PITCH_W, PITCH_H = 100, 60 # canvas do radar
13
+
14
+
15
+ class Homography:
16
+ def __init__(self, calib_path=None):
17
+ self.H = None
18
+ if calib_path and Path(calib_path).exists():
19
+ d = json.loads(Path(calib_path).read_text())
20
+ src = np.array(d["src"], np.float32)
21
+ dst = np.array(d["dst"], np.float32) * [PITCH_W / 105.0, PITCH_H / 68.0]
22
+ self.H, _ = cv2.findHomography(src, dst)
23
+
24
+ def map(self, x, y):
25
+ if self.H is None:
26
+ return None
27
+ p = self.H @ np.array([x, y, 1.0])
28
+ return float(p[0] / p[2]), float(p[1] / p[2])
29
+
30
+
31
+ def draw_pitch():
32
+ """Radar 2D do campo num canvas 400x400 (campo 400x240 centralizado)."""
33
+ sc = 4
34
+ img = np.zeros((400, 400, 3), np.uint8)
35
+ y0 = (400 - PITCH_H * sc) // 2
36
+ pitch = np.zeros((PITCH_H * sc, PITCH_W * sc, 3), np.uint8)
37
+ pitch[:, :] = (0, 90, 0)
38
+ W, H = PITCH_W * sc, PITCH_H * sc
39
+ white = (200, 255, 200)
40
+ cv2.rectangle(pitch, (0, 0), (W - 1, H - 1), white, 1)
41
+ cv2.line(pitch, (W // 2, 0), (W // 2, H), white, 1)
42
+ cv2.circle(pitch, (W // 2, H // 2), int(9.15 * sc), white, 1)
43
+ box_h = int(20 * sc)
44
+ for x0 in (0, W - int(16.5 * sc)):
45
+ cv2.rectangle(pitch, (x0, H // 2 - box_h), (x0 + int(16.5 * sc), H // 2 + box_h), white, 1)
46
+ img[y0:y0 + pitch.shape[0]] = pitch
47
+ cv2.putText(img, "radar 2D", (10, 390), cv2.FONT_HERSHEY_SIMPLEX, 0.7,
48
+ (255, 255, 255), 2)
49
+ return img
src/player_snn.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SNN classificadora de blobs de eventos: JOGADOR vs RUIDO.
2
+
3
+ Entrada: crop de eventos 2x48x48 (ON/OFF) — mesma base LIF da serie.
4
+ """
5
+ import numpy as np
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+
10
+ CLASSES = ["ruido", "jogador"]
11
+
12
+
13
+ class SpikeFn(torch.autograd.Function):
14
+ @staticmethod
15
+ def forward(ctx, v_mem, v_th=1.0):
16
+ ctx.save_for_backward(v_mem)
17
+ ctx.v_th = v_th
18
+ return (v_mem >= v_th).float()
19
+
20
+ @staticmethod
21
+ def backward(ctx, grad_out):
22
+ (v_mem,) = ctx.saved_tensors
23
+ x = torch.pi * (v_mem - ctx.v_th)
24
+ return grad_out / (1.0 + x * x), None
25
+
26
+
27
+ class LIF(nn.Module):
28
+ def __init__(self, beta=0.85, v_th=1.0):
29
+ super().__init__()
30
+ self.beta, self.v_th = beta, v_th
31
+
32
+ def forward(self, x, mem):
33
+ mem = self.beta * mem + x
34
+ s = SpikeFn.apply(mem, self.v_th)
35
+ return s, mem * (1.0 - s)
36
+
37
+
38
+ class PlayerSNN(nn.Module):
39
+ def __init__(self, num_steps=10):
40
+ super().__init__()
41
+ self.num_steps = num_steps
42
+ self.conv1 = nn.Conv2d(2, 16, 3, stride=2, padding=1) # 24
43
+ self.lif1 = LIF()
44
+ self.conv2 = nn.Conv2d(16, 32, 3, stride=2, padding=1) # 12
45
+ self.lif2 = LIF(v_th=0.8)
46
+ self.fc1 = nn.Linear(32 * 12 * 12, 128)
47
+ self.lif3 = LIF(v_th=0.6)
48
+ self.fc2 = nn.Linear(128, 2)
49
+ self.lif4 = LIF(v_th=1e9)
50
+ nn.init.normal_(self.fc1.weight, std=0.08)
51
+
52
+ def forward(self, x):
53
+ B = x.size(0)
54
+ m1 = torch.zeros(B, 16, 24, 24, device=x.device)
55
+ m2 = torch.zeros(B, 32, 12, 12, device=x.device)
56
+ m3 = torch.zeros(B, 128, device=x.device)
57
+ m4 = torch.zeros(B, 2, device=x.device)
58
+ acc = 0.0
59
+ for _ in range(self.num_steps):
60
+ s, m1 = self.lif1(self.conv1(x), m1)
61
+ s, m2 = self.lif2(self.conv2(s), m2)
62
+ s, m3 = self.lif3(self.fc1(s.flatten(1)), m3)
63
+ _, m4 = self.lif4(self.fc2(s), m4)
64
+ acc = acc + m4
65
+ return acc / self.num_steps
66
+
67
+
68
+ def crop_events(events, box, size=48, pad=4):
69
+ H, W = events.shape
70
+ x, y, w, h = box
71
+ x0 = int(np.clip(x - pad, 0, W - 1))
72
+ y0 = int(np.clip(y - pad, 0, H - 1))
73
+ x1 = int(np.clip(x + w + pad, x0 + 1, W))
74
+ y1 = int(np.clip(y + h + pad, y0 + 1, H))
75
+ c = events[y0:y1, x0:x1]
76
+ on = torch.from_numpy((c > 0).astype("float32"))
77
+ off = torch.from_numpy((c < 0).astype("float32"))
78
+ on = F.interpolate(on[None, None], (size, size), mode="bilinear")[0, 0]
79
+ off = F.interpolate(off[None, None], (size, size), mode="bilinear")[0, 0]
80
+ return torch.stack([on, off])
src/snn_detector.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Detector SNN de jogadores em stream de eventos.
2
+
3
+ Encoder conv-LIF (do zero) -> heatmap de centros + regressao de
4
+ tamanho. Sem anchors, sem NMS classico: pico local na heatmap = centro.
5
+ """
6
+ import numpy as np
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+
11
+
12
+ class SpikeFn(torch.autograd.Function):
13
+ @staticmethod
14
+ def forward(ctx, v_mem, v_th=1.0):
15
+ ctx.save_for_backward(v_mem)
16
+ ctx.v_th = v_th
17
+ return (v_mem >= v_th).float()
18
+
19
+ @staticmethod
20
+ def backward(ctx, grad_out):
21
+ (v_mem,) = ctx.saved_tensors
22
+ x = torch.pi * (v_mem - ctx.v_th)
23
+ return grad_out / (1.0 + x * x), None
24
+
25
+
26
+ class LIF(nn.Module):
27
+ def __init__(self, beta=0.85, v_th=1.0):
28
+ super().__init__()
29
+ self.beta, self.v_th = beta, v_th
30
+
31
+ def forward(self, x, mem):
32
+ mem = self.beta * mem + x
33
+ s = SpikeFn.apply(mem, self.v_th)
34
+ return s, mem * (1.0 - s)
35
+
36
+
37
+ class EventDetectorSNN(nn.Module):
38
+ """(B,2,240,320) -> heatmap (B,1,15,20) + size (B,2,15,20).
39
+
40
+ stride 16 total (4 convs stride 2)."""
41
+ def __init__(self, num_steps=8):
42
+ super().__init__()
43
+ self.num_steps = num_steps
44
+ self.c1 = nn.Conv2d(2, 32, 3, stride=2, padding=1) # 120x160
45
+ self.l1 = LIF()
46
+ self.c2 = nn.Conv2d(32, 64, 3, stride=2, padding=1) # 60x80
47
+ self.l2 = LIF(v_th=0.8)
48
+ self.c3 = nn.Conv2d(64, 96, 3, stride=2, padding=1) # 30x40
49
+ self.l3 = LIF(v_th=0.6)
50
+ self.c4 = nn.Conv2d(96, 128, 3, stride=2, padding=1) # 15x20
51
+ self.l4 = LIF(v_th=0.5)
52
+ self.hm_head = nn.Conv2d(128, 1, 1)
53
+ self.sz_head = nn.Conv2d(128, 2, 1)
54
+
55
+ def forward(self, x):
56
+ B = x.size(0)
57
+ m1 = torch.zeros(B, 32, 120, 160, device=x.device)
58
+ m2 = torch.zeros(B, 64, 60, 80, device=x.device)
59
+ m3 = torch.zeros(B, 96, 30, 40, device=x.device)
60
+ m4 = torch.zeros(B, 128, 15, 20, device=x.device)
61
+ acc = 0.0
62
+ for _ in range(self.num_steps):
63
+ s, m1 = self.l1(self.c1(x), m1)
64
+ s, m2 = self.l2(self.c2(s), m2)
65
+ s, m3 = self.l3(self.c3(s), m3)
66
+ s, m4 = self.l4(self.c4(s), m4)
67
+ acc = acc + m4
68
+ feat = acc / self.num_steps # membrana media = ativacao
69
+ return torch.sigmoid(self.hm_head(feat)), torch.sigmoid(self.sz_head(feat))
70
+
71
+
72
+ def decode(hm, size, k=8, thr=0.35):
73
+ """Pico local na heatmap -> boxes em px (320x240 space)."""
74
+ h2 = hm.reshape(1, 1, *hm.shape[-2:])
75
+ hm_p = F.max_pool2d(h2, 3, stride=1, padding=1)[0, 0]
76
+ flat_hm = hm.reshape(*hm.shape[-2:])
77
+ flat_sz = size.reshape(2, *size.shape[-2:])
78
+ peaks = (flat_hm == hm_p) & (flat_hm > thr)
79
+ idx = peaks.nonzero()
80
+ scores = flat_hm[peaks]
81
+ top = scores.argsort(descending=True)[:k]
82
+ boxes = []
83
+ for t in top:
84
+ gy, gx = idx[t].tolist()
85
+ w = max(8, float(flat_sz[0, gy, gx]) * 320)
86
+ h = max(12, float(flat_sz[1, gy, gx]) * 240)
87
+ cx, cy = (gx + 0.5) * 16, (gy + 0.5) * 16
88
+ boxes.append((cx - w / 2, cy - h / 2, w, h))
89
+ return boxes
src/teams.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Classificacao de time por cor do uniforme — kmeans do zero."""
2
+ import numpy as np
3
+ import cv2
4
+
5
+
6
+ def kmeans(X, k=3, iters=20, seed=0):
7
+ """kmeans em RGB. Retorna labels e centroides."""
8
+ rng = np.random.default_rng(seed)
9
+ C = X[rng.choice(len(X), k, replace=False)].astype(np.float32)
10
+ for _ in range(iters):
11
+ d = ((X[:, None] - C[None]) ** 2).sum(2)
12
+ lab = d.argmin(1)
13
+ for j in range(k):
14
+ if (lab == j).any():
15
+ C[j] = X[lab == j].mean(0)
16
+ return lab, C
17
+
18
+
19
+ def jersey_color(frame, box):
20
+ """Cor dominante do torso (regiao central superior do box),
21
+ excluindo verde do campo."""
22
+ x, y, w, h = [int(v) for v in box]
23
+ x0, x1 = max(0, x + w // 4), x + 3 * w // 4
24
+ y0, y1 = max(0, y + h // 8), y + h // 2
25
+ patch = frame[y0:y1, x0:x1]
26
+ if patch.size == 0:
27
+ return None
28
+ px = patch.reshape(-1, 3).astype(np.float32) # BGR
29
+ # remove pixels esverdeados (campo)
30
+ non_green = ~((px[:, 1] > px[:, 0] + 20) & (px[:, 1] > px[:, 2] + 10))
31
+ px = px[non_green]
32
+ if len(px) < 4:
33
+ return None
34
+ return px.mean(0)
35
+
36
+
37
+ class TeamClassifier:
38
+ """Fit numa colecao de cores de uniforme -> 2 clusters + ref."""
39
+
40
+ def __init__(self):
41
+ self.centers = None
42
+ self.names = ["time A", "time B"]
43
+
44
+ def fit(self, colors):
45
+ colors = np.array([c for c in colors if c is not None])
46
+ if len(colors) < 6:
47
+ return False
48
+ lab, C = kmeans(colors, k=min(3, len(colors)), iters=30)
49
+ # descarta o cluster mais parecido com verde (campo)
50
+ greenness = C[:, 1] - (C[:, 0] + C[:, 2]) / 2
51
+ keep = np.argsort(greenness)[:2]
52
+ self.centers = C[keep]
53
+ return True
54
+
55
+ def predict(self, color):
56
+ if color is None or self.centers is None:
57
+ return -1
58
+ return int(((self.centers - color) ** 2).sum(1).argmin())
src/tracker.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tracker multi-objeto robusto, do zero.
2
+
3
+ - Kalman [x,y,vx,vy] por jogador
4
+ - Compensacao de ego-motion: shift global estimado por phase correlation
5
+ entre frames consecutivos (camera broadcast pan/tilt)
6
+ - Matching por custo combinado: distancia + cor do uniforme + forma da caixa
7
+ """
8
+ import cv2
9
+ import numpy as np
10
+
11
+
12
+ class Kalman:
13
+ def __init__(self, x, y):
14
+ self.X = np.array([x, y, 0.0, 0.0])
15
+ self.P = np.diag([10.0, 10.0, 50.0, 50.0])
16
+ self.F = np.array([[1, 0, 1, 0], [0, 1, 0, 1],
17
+ [0, 0, 1, 0], [0, 0, 0, 1]], float)
18
+ self.H = np.array([[1, 0, 0, 0], [0, 1, 0, 0]], float)
19
+ self.Q = np.diag([0.5, 0.5, 2.0, 2.0])
20
+ self.R = np.eye(2) * 4.0
21
+
22
+ def predict(self):
23
+ self.X = self.F @ self.X
24
+ self.P = self.F @ self.P @ self.F.T + self.Q
25
+ return self.X[:2]
26
+
27
+ def update(self, z):
28
+ S = self.H @ self.P @ self.H.T + self.R
29
+ K = self.P @ self.H.T @ np.linalg.inv(S)
30
+ self.X = self.X + K @ (np.asarray(z) - self.H @ self.X)
31
+ self.P = (np.eye(4) - K @ self.H) @ self.P
32
+
33
+
34
+ class Track:
35
+ _next_id = 0
36
+
37
+ def __init__(self, box):
38
+ self.id = Track._next_id
39
+ Track._next_id += 1
40
+ self.box = np.array(box, float)
41
+ self.kf = Kalman(*self.centroid)
42
+ self.trail = [self.centroid]
43
+ self.color = None # cor media do uniforme (BGR)
44
+ self.team_votes = []
45
+ self.hits, self.misses = 1, 0
46
+
47
+ @property
48
+ def centroid(self):
49
+ x, y, w, h = self.box
50
+ return np.array([x + w / 2, y + h / 2])
51
+
52
+ def predict(self, shift=(0.0, 0.0)):
53
+ c = self.kf.predict()
54
+ self.box[:2] = c - self.box[2:] / 2
55
+ self.box[0] += shift[0] # compensa movimento da camera
56
+ self.box[1] += shift[1]
57
+ self.misses += 1
58
+
59
+ def update(self, box):
60
+ self.kf.update([box[0] + box[2] / 2, box[1] + box[3] / 2])
61
+ self.box = 0.5 * self.box + 0.5 * np.array(box, float)
62
+ self.trail.append(self.centroid.copy())
63
+ if len(self.trail) > 40:
64
+ self.trail.pop(0)
65
+ self.hits += 1
66
+ self.misses = 0
67
+
68
+ def add_color(self, c):
69
+ if c is None:
70
+ return
71
+ self.color = c if self.color is None else 0.9 * self.color + 0.1 * c
72
+
73
+ def color_dist(self, c):
74
+ if self.color is None or c is None:
75
+ return 0.0
76
+ return min(float(np.linalg.norm(self.color - c)) / 100.0, 2.0)
77
+
78
+
79
+ def global_shift(prev_gray, gray):
80
+ """Phase correlation -> deslocamento global (dx, dy)."""
81
+ d, _ = cv2.phaseCorrelate(prev_gray, gray)
82
+ return d
83
+
84
+
85
+ class Tracker:
86
+ def __init__(self, max_dist=30, max_misses=15, min_hits=5,
87
+ w_color=1.5, w_shape=0.5):
88
+ self.tracks = []
89
+ self.max_dist, self.max_misses, self.min_hits = \
90
+ max_dist, max_misses, min_hits
91
+ self.w_color, self.w_shape = w_color, w_shape
92
+
93
+ def _cost(self, t, box, color):
94
+ x, y, w, h = box
95
+ d = np.linalg.norm(t.centroid - (x + w / 2, y + h / 2))
96
+ if d > self.max_dist:
97
+ return None
98
+ c = t.color_dist(color)
99
+ tw, th = t.box[2], t.box[3]
100
+ s = abs(np.log((w + 1e-3) / (tw + 1e-3))) + abs(np.log((h + 1e-3) / (th + 1e-3)))
101
+ return d + self.w_color * c + self.w_shape * s
102
+
103
+ def step(self, boxes, colors=None, shift=(0.0, 0.0)):
104
+ colors = colors or [None] * len(boxes)
105
+ for t in self.tracks:
106
+ t.predict(shift)
107
+
108
+ # matching guloso por custo combinado
109
+ pairs = []
110
+ for ti, t in enumerate(self.tracks):
111
+ for i in range(len(boxes)):
112
+ c = self._cost(t, boxes[i], colors[i])
113
+ if c is not None:
114
+ pairs.append((c, ti, i))
115
+ pairs.sort()
116
+ used_t, used_b = set(), set()
117
+ for c, ti, i in pairs:
118
+ if ti in used_t or i in used_b:
119
+ continue
120
+ used_t.add(ti)
121
+ used_b.add(i)
122
+ self.tracks[ti].update(boxes[i])
123
+ self.tracks[ti].add_color(colors[i])
124
+
125
+ for i in range(len(boxes)):
126
+ if i not in used_b:
127
+ t = Track(boxes[i])
128
+ t.add_color(colors[i])
129
+ self.tracks.append(t)
130
+
131
+ self.tracks = [t for t in self.tracks if t.misses <= self.max_misses]
132
+ return [t for t in self.tracks if t.hits >= self.min_hits]
src/train_detector.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Treino do detector SNN nos auto-labels. Uso: python -m src.train_detector"""
2
+ import argparse
3
+ from pathlib import Path
4
+
5
+ import numpy as np
6
+ import torch
7
+ import torch.nn as nn
8
+ from torch.utils.data import Dataset, DataLoader, random_split
9
+
10
+ from .snn_detector import EventDetectorSNN
11
+
12
+
13
+ class DetDataset(Dataset):
14
+ def __init__(self, root="data"):
15
+ self.files = sorted(Path(root).glob("*.npz"))
16
+ if not self.files:
17
+ raise SystemExit("sem dados — rode src.auto_label")
18
+
19
+ def __len__(self):
20
+ return len(self.files)
21
+
22
+ def __getitem__(self, i):
23
+ d = np.load(self.files[i])
24
+ return (torch.from_numpy(d["x"]), torch.from_numpy(d["hm"]),
25
+ torch.from_numpy(d["size"]), torch.tensor(float("size" in d)))
26
+
27
+
28
+ def focal_loss(pred, target, alpha=2, beta=4):
29
+ """Focal loss de heatmap (CornerNet-style)."""
30
+ pos = target == 1
31
+ neg = ~pos
32
+ pred = torch.clamp(pred, 1e-4, 1 - 1e-4)
33
+ loss = -((1 - pred) ** alpha * torch.log(pred) * pos
34
+ + (1 - target) ** beta * pred ** alpha * torch.log(1 - pred) * neg)
35
+ return loss.sum() / max(pos.sum(), 1)
36
+
37
+
38
+ def main():
39
+ ap = argparse.ArgumentParser()
40
+ ap.add_argument("--epochs", type=int, default=40)
41
+ ap.add_argument("--batch-size", type=int, default=16)
42
+ ap.add_argument("--lr", type=float, default=1e-3)
43
+ ap.add_argument("--cpu", action="store_true")
44
+ args = ap.parse_args()
45
+
46
+ device = torch.device("cuda" if torch.cuda.is_available()
47
+ and not args.cpu else "cpu")
48
+ ds = DetDataset()
49
+ n_te = max(1, int(0.15 * len(ds)))
50
+ tr, te = random_split(ds, [len(ds) - n_te, n_te],
51
+ generator=torch.Generator().manual_seed(0))
52
+ dl = DataLoader(tr, batch_size=args.batch_size, shuffle=True)
53
+ dl_te = DataLoader(te, batch_size=32)
54
+ print(f"device={device} train={len(tr)} test={len(te)}")
55
+
56
+ model = EventDetectorSNN().to(device)
57
+ opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=1e-4)
58
+
59
+ best = 1e9
60
+ for ep in range(1, args.epochs + 1):
61
+ model.train()
62
+ for x, hm, sz, _ in dl:
63
+ x, hm, sz = x.to(device), hm.to(device), sz.to(device)
64
+ phm, psz = model(x)
65
+ loss = focal_loss(phm.squeeze(1), hm)
66
+ pos = hm > 0.5 # (B,15,20) celulas com centro
67
+ if pos.any():
68
+ loss = loss + 2.0 * nn.functional.l1_loss(
69
+ psz.permute(0, 2, 3, 1)[pos], sz.permute(0, 2, 3, 1)[pos])
70
+ opt.zero_grad(set_to_none=True)
71
+ loss.backward()
72
+ opt.step()
73
+ model.eval()
74
+ tl = 0.0
75
+ with torch.no_grad():
76
+ for x, hm, sz, _ in dl_te:
77
+ x, hm, sz = x.to(device), hm.to(device), sz.to(device)
78
+ phm, psz = model(x)
79
+ tl += focal_loss(phm.squeeze(1), hm).item()
80
+ tl /= len(dl_te)
81
+ if tl < best:
82
+ best = tl
83
+ torch.save(model.state_dict(), "checkpoints/snn_detector.pt")
84
+ if ep % 5 == 0 or ep == 1:
85
+ print(f"epoch {ep}: test_loss={tl:.4f} (best={best:.4f})")
86
+ print(f"salvo | best={best:.4f}")
87
+
88
+
89
+ if __name__ == "__main__":
90
+ main()
src/train_player.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Treino da SNN classificadora de blobs. Uso: python -m src.train_player"""
2
+ import argparse
3
+ import numpy as np
4
+ import torch
5
+ import torch.nn as nn
6
+ from torch.utils.data import Dataset, DataLoader, random_split
7
+
8
+ from .player_snn import PlayerSNN
9
+
10
+
11
+ class DS(Dataset):
12
+ def __init__(self):
13
+ d = np.load("data_players/players.npz")
14
+ self.x = torch.from_numpy(d["x"])
15
+ self.y = torch.from_numpy(d["y"]).long()
16
+
17
+ def __len__(self):
18
+ return len(self.y)
19
+
20
+ def __getitem__(self, i):
21
+ return self.x[i], self.y[i]
22
+
23
+
24
+ def main():
25
+ ap = argparse.ArgumentParser()
26
+ ap.add_argument("--epochs", type=int, default=25)
27
+ ap.add_argument("--cpu", action="store_true")
28
+ args = ap.parse_args()
29
+ device = torch.device("cuda" if torch.cuda.is_available()
30
+ and not args.cpu else "cpu")
31
+ ds = DS()
32
+ n_te = max(1, int(0.15 * len(ds)))
33
+ tr, te = random_split(ds, [len(ds) - n_te, n_te],
34
+ generator=torch.Generator().manual_seed(0))
35
+ dl = DataLoader(tr, batch_size=256, shuffle=True)
36
+ dl_te = DataLoader(te, batch_size=256)
37
+ print(f"train={len(tr)} test={len(te)} device={device}")
38
+
39
+ model = PlayerSNN().to(device)
40
+ opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-4)
41
+ w = torch.tensor([1.2, 1.0], device=device)
42
+ crit = nn.CrossEntropyLoss(weight=w)
43
+ best = 0.0
44
+ for ep in range(1, args.epochs + 1):
45
+ model.train()
46
+ for x, y in dl:
47
+ x, y = x.to(device), y.to(device)
48
+ loss = crit(model(x), y)
49
+ opt.zero_grad(set_to_none=True)
50
+ loss.backward()
51
+ opt.step()
52
+ model.eval()
53
+ acc = 0.0
54
+ with torch.no_grad():
55
+ for x, y in dl_te:
56
+ acc += (model(x.to(device)).argmax(1) == y.to(device)).float().mean().item()
57
+ acc /= len(dl_te)
58
+ if acc > best:
59
+ best = acc
60
+ torch.save(model.state_dict(), "checkpoints/player_snn.pt")
61
+ if ep % 5 == 0 or ep == 1:
62
+ print(f"epoch {ep}: acc={acc:.3f} best={best:.3f}")
63
+ print(f"salvo | best_acc={best:.3f}")
64
+
65
+
66
+ if __name__ == "__main__":
67
+ main()