#!/usr/bin/env python3 """Synthetic shirt numbers, to train the reader before there are thousands of checked crops. python synth.py --backgrounds cache/crops --fonts fonts/ --out synth/ --count 6000 Each sample is a torso-like crop with a number painted on it: on a real crop (so lighting, skin, arms and logos look real) or on a plain shirt colour. The number is drawn in a sporty font, in a colour that stands out, sometimes outlined, then warped like cloth: tilted, in perspective, rippled, blurred. It is written to /.jpg and listed in /dataset.json, in the same format as the dataset from the app (label = the number, or "illegible" for shirts painted without one); now and then the crop gets a team official's card with a letter A-F instead (handball). Mix it with the real dataset in train.py (--extra); the check keeps using real crops only. Fonts: any .ttf/.otf/.woff in --fonts. Free sporty ones (Oswald, Anton, Bebas Neue, Teko, Saira Condensed, ...) come from npm: `npm pack @fontsource/oswald` and so on. """ from __future__ import annotations import argparse import io import json import math import random from pathlib import Path from PIL import Image, ImageDraw, ImageFilter, ImageFont H = 256 def shirt(w: int, h: int, rng: random.Random) -> Image.Image: """A plain shirt: one colour, a soft light gradient, sometimes stripes or a side panel.""" base = tuple(rng.randint(0, 255) for _ in range(3)) img = Image.new("RGB", (w, h), base) d = ImageDraw.Draw(img) kind = rng.random() if kind < 0.25: # horizontal hoops other = tuple(rng.randint(0, 255) for _ in range(3)) step = rng.randint(14, 40) for y in range(0, h, step * 2): d.rectangle([0, y, w, y + step], fill=other) elif kind < 0.45: # side panel / sleeve band other = tuple(rng.randint(0, 255) for _ in range(3)) x = rng.choice([0, w - w // 5]) d.rectangle([x, 0, x + w // 5, h], fill=other) # light from one side shade = Image.linear_gradient("L").resize((w, h)).rotate(rng.choice([0, 90, 180, 270]), expand=False).resize((w, h)) dark = Image.new("RGB", (w, h), (0, 0, 0)) return Image.composite(img, dark, shade.point(lambda v: 150 + v * 105 // 255)) def contrasting(bg: tuple[int, int, int], rng: random.Random) -> tuple[int, int, int]: lum = 0.299 * bg[0] + 0.587 * bg[1] + 0.114 * bg[2] if rng.random() < 0.7: return (245, 245, 245) if lum < 140 else (20, 20, 20) while True: c = tuple(rng.randint(0, 255) for _ in range(3)) if abs((0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2]) - lum) > 90: return c def number_layer(text: str, font_path: Path, height: int, fill, outline, rng: random.Random) -> Image.Image: font = ImageFont.truetype(str(font_path), size=height) box = font.getbbox(text) pad = 12 layer = Image.new("RGBA", (box[2] - box[0] + 2 * pad, box[3] - box[1] + 2 * pad), (0, 0, 0, 0)) d = ImageDraw.Draw(layer) stroke = rng.choice([0, 0, 2, 3, 5]) if outline else 0 d.text((pad - box[0], pad - box[1]), text, font=font, fill=fill + (255,), stroke_width=stroke, stroke_fill=(outline or fill) + (255,)) return layer def warp(layer: Image.Image, rng: random.Random) -> Image.Image: """Cloth: a tilt, a little perspective and a ripple.""" layer = layer.rotate(rng.uniform(-14, 14), resample=Image.BICUBIC, expand=True) w, h = layer.size dx, dy = w * rng.uniform(-0.12, 0.12), h * rng.uniform(-0.08, 0.08) coeffs = _perspective([(0, 0), (w, 0), (w, h), (0, h)], [(dx, dy), (w - dx, -dy), (w + dx, h + dy), (-dx, h - dy)]) layer = layer.transform((w, h), Image.PERSPECTIVE, coeffs, Image.BICUBIC) amp, period = rng.uniform(0, 4), rng.uniform(30, 90) if amp > 0.5: out = Image.new("RGBA", layer.size, (0, 0, 0, 0)) for x in range(w): col = layer.crop((x, 0, x + 1, h)) out.paste(col, (x, int(amp * math.sin(x / period * 2 * math.pi)))) layer = out return layer def _perspective(src, dst): import numpy as np m = [] for (x, y), (u, v) in zip(dst, src): m.append([x, y, 1, 0, 0, 0, -u * x, -u * y]) m.append([0, 0, 0, x, y, 1, -v * x, -v * y]) a = np.array(m, dtype=float) b = np.array(src, dtype=float).reshape(8) return np.linalg.solve(a, b).tolist() def badge(letter: str, font_path: Path, rng: random.Random) -> Image.Image: """A team official's accreditation card (handball): a pale card with a big letter, on a lanyard.""" cw = int(H * rng.uniform(0.22, 0.34)) ch = int(cw * rng.uniform(1.3, 1.6)) card = Image.new("RGBA", (cw, ch), (0, 0, 0, 0)) d = ImageDraw.Draw(card) paper = tuple(rng.randint(225, 255) for _ in range(3)) d.rounded_rectangle([0, 0, cw - 1, ch - 1], radius=max(2, cw // 12), fill=paper + (255,), outline=(120, 120, 120, 255)) d.rectangle([0, 0, cw, int(ch * rng.uniform(0.18, 0.3))], fill=tuple(rng.randint(0, 200) for _ in range(3)) + (255,)) ink = rng.choice([(0, 0, 0), (20, 20, 60), (60, 0, 0)]) glyph = number_layer(letter, font_path, int(ch * rng.uniform(0.32, 0.45)), ink, None, rng) card.paste(glyph, ((cw - glyph.width) // 2, int(ch * 0.62) - glyph.height // 2), glyph) return card.rotate(rng.uniform(-12, 12), resample=Image.BICUBIC, expand=True) def sample(rng: random.Random, backgrounds: list[Path], fonts: list[Path], with_number: bool): if backgrounds and rng.random() < 0.6: bg = Image.open(rng.choice(backgrounds)).convert("RGB") bg = bg.resize((int(bg.width * H / bg.height), H)) else: bg = shirt(rng.randint(120, 200), H, rng) w = bg.width if not with_number: return bg, "illegible" if rng.random() < 0.08: # an official's card instead of a shirt number letter = rng.choice("ABCDEF") card = badge(letter, rng.choice(fonts), rng) x = int((w - card.width) / 2 + rng.uniform(-0.2, 0.2) * w) x = max(0, min(w - card.width, x)) y = int(H * rng.uniform(0.15, 0.6)) d = ImageDraw.Draw(bg) d.line([(x + card.width // 2, 0), (x + card.width // 2, y)], fill=tuple(rng.randint(0, 255) for _ in range(3)), width=3) bg.paste(card, (x, y), card) return bg, letter n = rng.choice([rng.randint(1, 30), rng.randint(1, 30), rng.randint(0, 99)]) region = bg.crop((w // 3, H // 4, 2 * w // 3, H // 2)).resize((1, 1)).getpixel((0, 0)) fill = contrasting(region, rng) outline = contrasting(fill, rng) if rng.random() < 0.3 else None # Big on a chest crop (handball); small and to one side on a shorts crop (football). shorts = rng.random() < 0.4 height = int(H * (rng.uniform(0.12, 0.26) if shorts else rng.uniform(0.22, 0.48))) layer = warp(number_layer(str(n), rng.choice(fonts), height, fill, outline, rng), rng) if layer.width > w * 0.95: layer = layer.resize((int(w * 0.95), int(layer.height * w * 0.95 / layer.width))) x = int((w - layer.width) / 2 + rng.uniform(-0.3, 0.3) * w) if shorts else int((w - layer.width) / 2 + rng.uniform(-0.15, 0.15) * w) x = max(0, min(w - layer.width, x)) y = int(H * rng.uniform(0.05, 0.55)) bg.paste(layer, (x, y), layer) # an arm or the ball across a corner, now and then (never most of the number) if rng.random() < 0.25: d = ImageDraw.Draw(bg) skin = rng.choice([(224, 172, 140), (198, 134, 66), (141, 85, 36), (90, 56, 37)]) side = rng.choice([0, w]) d.ellipse([side - w // 4, y + layer.height * 0.6, side + w // 4, y + layer.height * 1.4], fill=skin) return bg, str(n) def finish(img: Image.Image, rng: random.Random) -> bytes: if rng.random() < 0.5: img = img.filter(ImageFilter.GaussianBlur(rng.uniform(0.3, 1.6))) if rng.random() < 0.3: # motion img = img.filter(ImageFilter.BoxBlur(rng.uniform(0.5, 2))) buf = io.BytesIO() img.save(buf, "JPEG", quality=rng.randint(55, 92)) return buf.getvalue() def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--backgrounds", help="folder of real torso crops to paint on (optional)") ap.add_argument("--fonts", required=True) ap.add_argument("--out", required=True) ap.add_argument("--count", type=int, default=6000) ap.add_argument("--blank", type=float, default=0.15, help="share of shirts without a number") ap.add_argument("--seed", type=int, default=1) args = ap.parse_args() rng = random.Random(args.seed) fonts = [p for p in Path(args.fonts).rglob("*") if p.suffix.lower() in {".ttf", ".otf", ".woff"}] if not fonts: raise SystemExit("no fonts found") backgrounds = sorted(Path(args.backgrounds).glob("*.jpg")) if args.backgrounds else [] out = Path(args.out) out.mkdir(parents=True, exist_ok=True) samples = [] for i in range(args.count): img, label = sample(rng, backgrounds, fonts, rng.random() >= args.blank) f = out / f"synth_{i:05d}.jpg" f.write_bytes(finish(img, rng)) samples.append({"id": f.stem, "label": label, "file": str(f.resolve())}) (out / "dataset.json").write_text(json.dumps({"version": 1, "synthetic": True, "samples": samples})) print(f"{len(samples)} synthetic crops in {out}") if __name__ == "__main__": main()