Skip to content
ishaanzeePublic

About

analyze basketball shot selection / shooting form using comp vision

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

ballform

A basketball video analyzer that runs on your machine. It looks at a single shooter's mechanics, or at the geometry of a game possession: who had the ball, who the primary defender was, how much space there was at release, and whether the shot went in.

The numbers are review signals, not a scouting department in a box. Compare clips from the same camera, watch the annotated video, and if the tracker is unsure the report says so.

demo

Full demo

Ballform game review: tracked players, calibrated court lines and a detected make game review with court calibration

simple metrics advanced metrics
Before shot details After shot details

what it does

  • Tracks players and the ball with multi-person pose, a basketball-trained RF-DETR detector, motion and jersey appearance.
  • Finds the rim by itself, follows it through pans, zooms and cuts, and calls makes from the rim crossing plus net motion.
  • Picks the shooter and the nearest contesting defender, then scores the shot with a transparent formula: 65% separation + 35% contest clearance.
  • Labels shot types: jump shot, floater, layup, dunk, tip.
  • Court calibration maps the floor so distances, zones and spacing come out in feet. On broadcast footage it is found automatically from the whole clip; you can also mark or adjust the court landmarks yourself.
  • Ball flight in feet for jump shots on a calibrated court: release height, top of the arc, entry angle, and whether the shot came down short or long of the rim's centre.
  • Court map: with a calibrated court, a top-down view beside the review video shows where every tracked player is on the floor, moving with the video.
  • Form mode reports 2D release timing, launch angle, elbow angle and upper-arm elevation for comparing your own reps. A shot is found from the ball's arc or, when the ball is lost, from the shooting arm alone.
  • Free-throw player match measures your free throws from a side-on clip, finds which of 27 NBA players' free-throw form is closest and says what to change to look more like one of them. It describes resemblance, not quality.
  • Annotated review video with tracking, court lines and a pulse on makes.

Everything runs locally. Clips and reports stay in data/jobs/.

run it

Python 3.11 or 3.12 and uv:

uv sync --extra dev --python 3.12
uv run uvicorn app.main:app --reload

Open http://127.0.0.1:8000. The first run downloads the pose and detection weights into models/. The first game analysis on a fixed camera (courtside or elevated) also downloads a detector retrained for fixed cameras (121 MB, checked against a pinned SHA-256); if that fails, the analysis runs on the standard detector and its result says so (details). ffmpeg is worth installing for clean H.264 review videos; on a Mac it uses the hardware encoder.

faster on Apple silicon (optional)

Both speedups are optional. Without them everything still runs, just slower, and the results page says which one is missing.

Faster ball detector. An MLX + Metal port of the same model from kernelopt, 28.5 ms per call versus 48.4 ms as measured in Ballform, with identical detections. (kernelopt's README reports 28.2 ms versus 50.9 ms; that is a separate benchmark on full 1920×1080 frames.)

uv pip install --python .venv/bin/python "fast-rfdetr @ git+https://github.com/ishaanzee/kernelopt"

Pose on the Neural Engine. A one-time export, about 1.5x faster per frame, with small fp16 differences.

YOLO_AUTOINSTALL=False uv run --with onnx --with onnxslim --with onnxconverter-common \
    python scripts/export_pose_coreml.py yolo26s-pose yolo26m-pose

A plain uv sync removes the detector package again. Use uv sync --inexact, or rerun the install.

analysis speed

Game analysis has three speed settings, chosen per clip on the page (Analysis speed), with the speed form field of POST /api/jobs, or for every job with BALLFORM_SPEED:

setting what it does
accurate (default) every frame at 30 fps, every view
balanced 30 fps while a shot is going up or reaching a rim, 15 fps the rest of the time
fast the same with 7.5 fps the rest of the time

The faster two find a few fewer shots, and apply to moving-camera footage only (a fixed camera runs in full under any setting). What each costs, and what every other speed lever was measured to cost, is in docs/performance.md. The setting a job ran with is saved in its settings.json and reported as analysis_speed in the result.

upload from an iPhone

Install Tailscale on the Mac and the iPhone, sign into the same account, then:

uv run ballform-share --network tailscale

Scan the QR code with the iPhone camera. The video still runs on the Mac; Tailscale is only the encrypted pipe. Use --network lan if both devices are on the same Wi-Fi.

jobs and disk space

Clips are analyzed one at a time, in the order they were uploaded; a waiting clip shows how many are ahead of it. The analysis runs in a process of its own, so the page, uploads and downloads stay responsive while it works. If the server is stopped mid-analysis, that clip is reported as interrupted and needs uploading again.

Every upload, review video and report is kept in data/jobs/ until you remove it. To see what a limit would remove, then remove it:

uv run ballform-clean-jobs --max-age-days 30 --max-gb 20            # dry run: lists the jobs
uv run ballform-clean-jobs --max-age-days 30 --max-gb 20 --delete

--max-age-days removes jobs untouched for that long; --max-gb then removes the oldest until the folder is under that size. To have the server apply the same limits at startup and after each analysis, set BALLFORM_JOBS_MAX_AGE_DAYS and/or BALLFORM_JOBS_MAX_GB; with neither set it deletes nothing. Jobs referenced under eval/ (label CSVs, staging, baselines, reruns), jobs with a .keep file in their folder and jobs from the last 24 hours are always kept.

picking a camera profile

profile use it for
Stationary courtside (default) fixed camera at court level, cleanest make/miss
Pickup / elevated wide view fixed, wide, elevated camera
Moving broadcast + tracked rim NBA and other broadcast footage with pans and zooms

Tips for a good clip: keep the shooter, ball and rim visible, shoot at 60 fps and 1080p, and don't digitally zoom mid-possession. Short continuous half-court possessions work best. More in docs/cameras-and-clips.md.

how it works

Deeper write-ups, with the measurements behind them:

  • Game mode: the shot-space score, shot-type rules, ball flight, validation
  • Player identities: splitting tracks that changed player, finding lost players again
  • Court calibration: homography fit, auto-detect, whole-clip calibration, floor trajectories, court map, accuracy checks
  • Performance: model backends, pipelining, review video encoding, timings
  • Cameras and clips: profiles, rim detection, make classifier
  • Free-throw player match: filming, measurements, player templates, matching, limits
  • Detector fine-tune: the box-labeled dataset from Ballform's own frames, its measured label quality, and how to retrain the ball/rim detector (not trained yet)
  • Form mode validation: what form mode and the player match found on 15 public single-shooter clips, what was fixed, what still fails, filming advice

limits

Camera movement changes apparent distances. Jerseys can look alike. Players overlap. The ball can be hidden for exactly the frames that matter. Passes and slow-motion edits can resemble shots. Cuts reset tracking. On NBA broadcast clips from games it was never tuned on, it finds 82–84% of shots, 84–94% of its shots are real, and its make/miss calls are right 96–99% of the time (measured accuracy, three blind holdouts). On fixed-camera amateur footage it finds 39 of 44 shots on five videos that were also used to tune it, and 19 of 48 on clips it was never tuned on, so expect the lower figure on new footage. Treat it as a review assistant, not an oracle.

code map

file job
app/analyzer.py decoding, inference, tracking, net flow, annotated video
app/scoring.py arc segmentation, form and outcome evidence
app/shots.py hidden-release jump shots, rim attempts, shot types
app/game.py shooter/defender association, shot-space score
app/court.py, court_detect.py, camera_motion.py, trajectory.py court templates and fit, auto-detect, camera motion, floor trajectories
app/ball_flight.py the ball's flight in feet in the plane from shooter to rim, heights calibrated on the rim
app/court_map.py top-down court map of each tracked player, from the saved floor trajectories
app/form_signature.py, form_match.py, form_db.json free-throw measurements from pose, player templates and matching
app/camera_tilt.py camera roll from upright edges in the scene, to level the free-throw measurements
app/form_loop.py form mode and the player match: detector, pose and decoding on separate threads, detections reused between jobs on one clip
scripts/formdb/build.py builds the player templates from broadcast free throws
app/tracking.py multi-player IDs and jersey descriptors
app/reid.py identities repaired after tracking: arm, leg and shoe colour, uniform changes, lost players found again
app/vision.py wide-view detection, crops, court filtering, cuts
app/native_crops.py fixed cameras: source-resolution detector crops around the hoop and the predicted ball
app/main.py local upload/job API and the one-at-a-time analysis queue
app/worker.py the analysis process: the server hands each job to it and stays free to answer
app/video.py reading chosen frames of a video without a seek for each
app/cleanup.py size/age cleanup of data/jobs/

tests

uv run pytest -q                                   # about a minute
uv run --with pytest-xdist pytest -q -n 6          # the same tests on six cores
node --check web/app.js
node --check web/court.js
node --check web/court-map.js

license

AGPL-3.0-only, because it integrates the AGPL-licensed Ultralytics package and model. MediaPipe is Apache-2.0. See LICENSE, NOTICE.md, CONTRIBUTING.md and SECURITY.md before distributing a modified service.

About

analyze basketball shot selection / shooting form using comp vision

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages