INNER CODE UNIT · Python
slice_grid
htdt/godogen · asset-gen/tools/grid_slice.py:17
def slice_grid(src: Path, output_dir: Path, cols: int, rows: int, names: list[str] | None):
img = Image.open(src).convert("RGBA")
w, h = img.size
cell_w, cell_h = w // cols, h // rows
output_dir.mkdir(parents=True, exist_ok=True)
total = cols * rows
if names and len(names) != total:
print(json.dumps({"ok": False, "error": f"--names has {len(names)} entries, grid is {total} cells"}))
return
paths = []
for i in range(total):
row, col = divmod(i, cols)
x0, y0 = col * cell_w, row * cell_h
cell = img.crop((x0, y0, x0 + cell_w, y0 + cell_h))
name = names[i] if names else f"{i + 1:02d}"
path = output_dir / f"{name}.png"