CRICKET / code /tests /synthetic.py
d9993r's picture
Add files using upload-large-folder tool
14c58d8 verified
Raw History Blame Contribute Delete
6.91 kB
"""A synthetic 'nets video' with known ground truth, plus a FakeVision backend
that reads the frame number encoded in the pixels and returns the exact
skeletons/ball that were drawn. Lets the full pipeline run with no models.
Ground truth per delivery (dt = time relative to release):
run-up start -2.2 s, back-foot contact -0.30 s, front-foot contact -0.12 s,
release 0, bounce +0.45 s, bat contact +0.70 s."""
import math
import cv2
import numpy as np
W, H, FPS, DUR = 640, 360, 30, 40.0
RELEASES = [8.0, 20.0, 32.0]
CUTS = [14.0, 26.0]
RUNUP_LEAD, BFC_LEAD, FFC_LEAD = 2.2, 0.30, 0.12
BOUNCE_AFTER, CONTACT_AFTER = 0.45, 0.70
TRIGGER_AFTER, SHOT_END_AFTER = 0.10, 0.95 # batter: trigger move, end of shot follow-through
TORSO = 60.0
BATTER_BOX = [361, 137, 401, 227]
def nearest_release(t):
return min(RELEASES, key=lambda r: abs(r - t))
def _x0(dt):
return 320 + np.clip(dt, -RUNUP_LEAD, -BFC_LEAD) * 150 + BFC_LEAD * 150
def skeleton(t):
"""Right-arm bowler seen from behind. Returns (17,3) keypoints."""
r = nearest_release(t)
dt = t - r
x0 = _x0(dt)
hip_y, sh_y = 250.0, 250.0 - TORSO
k = np.zeros((17, 3)); k[:, 2] = 0.9
k[0] = [x0, sh_y - 25, .9]
k[5] = [x0 - 22, sh_y, .9]; k[6] = [x0 + 22, sh_y, .9]
k[11] = [x0 - 15, hip_y, .9]; k[12] = [x0 + 15, hip_y, .9]
phi = math.pi + math.pi * math.tanh(dt / 0.12) if abs(dt) < 1.5 else 0.15 * math.sin(6 * t)
L = TORSO
k[8] = [k[6, 0] + 0.5 * L * math.sin(phi), sh_y + 0.5 * L * math.cos(phi), .9]
k[10] = [k[6, 0] + L * math.sin(phi) * 0.98, sh_y + L * math.cos(phi), .9]
k[7] = [k[5, 0] - 5, sh_y + 30, .9]; k[9] = [k[5, 0] - 6, sh_y + 58, .9]
running = -RUNUP_LEAD <= dt < -BFC_LEAD
swing = 18 * math.sin(10 * t) if running else 0.0
front_planted = -FFC_LEAD <= dt <= 0.6
front_in_air = -BFC_LEAD <= dt < -FFC_LEAD # front leg reaching forward
fx = k[11, 0] - 6 + (swing if running else 0) + (30 * (dt + BFC_LEAD) / (BFC_LEAD - FFC_LEAD) if front_in_air else 0)
if front_planted:
fx = k[11, 0] - 6 + 30
k[13] = [k[11, 0] - 4, hip_y + 45, .9]; k[15] = [fx, hip_y + 90, .9]
k[14] = [k[12, 0] + 4, hip_y + 45, .9]; k[16] = [k[12, 0] + 6 - swing, hip_y + 90, .9]
return k
def batter_skeleton(t=None):
x1, y1, x2, y2 = BATTER_BOX
cx = (x1 + x2) / 2
dt = (t - nearest_release(t)) if t is not None else -9
if TRIGGER_AFTER <= dt < TRIGGER_AFTER + 0.12: # trigger: small step across
cx += 60 * (dt - TRIGGER_AFTER)
elif dt >= TRIGGER_AFTER + 0.12:
cx += 60 * 0.12
k = np.zeros((17, 3)); k[:, 2] = 0.8
k[0] = [cx, y1 + 8, .8]; k[5] = [cx - 8, y1 + 22, .8]; k[6] = [cx + 8, y1 + 22, .8]
k[7] = [cx - 10, y1 + 40, .8]; k[8] = [cx + 10, y1 + 40, .8]
sw = 0.0 # bat swing: hands sweep through contact
if CONTACT_AFTER - 0.25 <= dt <= SHOT_END_AFTER - 0.05:
sw = math.sin(math.pi * (dt - (CONTACT_AFTER - 0.25)) / (SHOT_END_AFTER - 0.05 - (CONTACT_AFTER - 0.25)))
k[9] = [cx - 10 + 40 * sw, y1 + 55 - 30 * sw, .8]; k[10] = [cx + 10 + 40 * sw, y1 + 55 - 30 * sw, .8]
k[11] = [cx - 6, y1 + 50, .8]; k[12] = [cx + 6, y1 + 50, .8]
k[13] = [cx - 7, y1 + 70, .8]; k[14] = [cx + 7, y1 + 70, .8]
k[15] = [cx - 8, y2 - 2, .8]; k[16] = [cx + 8, y2 - 2, .8]
return k
def ball(t):
r = nearest_release(t)
dt = t - r
if not (0.03 <= dt <= 1.0):
return None
sx, sy = skeleton(r)[10, :2]
if dt <= BOUNCE_AFTER:
return sx + 20 * dt, sy - 30 + 260 * dt
bx, by = sx + 20 * BOUNCE_AFTER, sy - 30 + 260 * BOUNCE_AFTER
if dt <= CONTACT_AFTER:
d = dt - BOUNCE_AFTER
return bx + 120 * d, by - 140 * d
cx, cy = bx + 120 * (CONTACT_AFTER - BOUNCE_AFTER), by - 140 * (CONTACT_AFTER - BOUNCE_AFTER)
d = dt - CONTACT_AFTER
return cx - 200 * d, cy - 20 * d
def encode_index(img, idx):
for b in range(16):
img[0:8, b * 8:(b + 1) * 8] = 255 if (idx >> b) & 1 else 0
def decode_index(img):
return sum((1 << b) for b in range(16) if img[4, b * 8 + 4].mean() > 127)
def background(t):
return [(60, 130, 60), (90, 90, 150), (70, 140, 90)][sum(t >= c for c in CUTS)]
def make_audio(path, sr=16000):
"""Quiet noise plus a sharp 'crack' at every bat contact."""
import wave
rng = np.random.default_rng(1)
a = rng.normal(0, 0.01, int(DUR * sr))
for r in RELEASES:
i = int((r + CONTACT_AFTER) * sr)
a[i:i + 240] += rng.normal(0, 0.6, 240) * np.exp(-np.arange(240) / 50)
pcm = (np.clip(a, -1, 1) * 32767).astype(np.int16)
with wave.open(str(path), "wb") as w:
w.setnchannels(1); w.setsampwidth(2); w.setframerate(sr); w.writeframes(pcm.tobytes())
def make_video(path, with_audio=True):
import shutil, subprocess, tempfile
from pathlib import Path
path = Path(path)
if with_audio and shutil.which("ffmpeg"):
tmp = Path(tempfile.mkdtemp())
_make_frames(tmp / "v.mp4"); make_audio(tmp / "a.wav")
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", str(tmp / "v.mp4"), "-i", str(tmp / "a.wav"),
"-c:v", "copy", "-c:a", "aac", "-shortest", str(path)], check=True)
shutil.rmtree(tmp)
else:
_make_frames(path)
def _make_frames(path):
vw = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), FPS, (W, H))
for i in range(int(DUR * FPS)):
t = i / FPS
img = np.zeros((H, W, 3), np.uint8); img[:] = background(t)
cv2.rectangle(img, (280, 120), (360, 359), (120, 170, 200), -1)
for k in (skeleton(t), batter_skeleton(t)):
for a, b in [(5, 7), (7, 9), (6, 8), (8, 10), (5, 6), (5, 11), (6, 12), (11, 12),
(11, 13), (13, 15), (12, 14), (14, 16)]:
cv2.line(img, tuple(map(int, k[a, :2])), tuple(map(int, k[b, :2])), (30, 30, 30), 3)
bl = ball(t)
if bl:
cv2.circle(img, (int(bl[0]), int(bl[1])), 4, (245, 245, 245), -1)
encode_index(img, i)
vw.write(img)
vw.release()
class FakeVision:
name = "fake"
versions = {"pose": "synthetic", "ball": "synthetic", "device": "cpu", "half": False, "format": "synthetic"}
def pose(self, frame, imgsz=640, conf=0.25):
t = decode_index(frame) / FPS
k = skeleton(t)
box = [k[:, 0].min() - 10, k[:, 1].min() - 10, k[:, 0].max() + 10, k[:, 1].max() + 10]
bk = batter_skeleton(t)
bbox = [bk[:, 0].min() - 8, BATTER_BOX[1], bk[:, 0].max() + 8, BATTER_BOX[3]]
return [{"box": box, "conf": 0.9, "kpts": k}, {"box": bbox, "conf": 0.8, "kpts": bk}]
def bats(self, frame, imgsz=960, conf=0.2):
return []
def balls(self, frame, imgsz=1280, conf=0.1):
b = ball(decode_index(frame) / FPS)
return [(b[0], b[1], 0.6)] if b else []