"""Output sizing and complete, aligned tile coverage; independent of CUDA.""" import math MAX_EDGE = 4096 MAX_PIXELS = 16_777_216 def output_size(width, height, size): if min(width, height) < 1: raise ValueError("The image must have nonzero dimensions.") if size in ("2×", "4×"): scale = int(size[0]) result = (width * scale, height * scale) elif size in ("2048 px long edge", "4096 px long edge"): edge = int(size.split()[0]) result = (max(1, round(width * edge / max(width, height))), max(1, round(height * edge / max(width, height)))) else: raise ValueError("Choose a supported output size.") if max(result) > MAX_EDGE or math.prod(result) > MAX_PIXELS: raise ValueError("This size exceeds 4096 px. Choose a long-edge output size.") return result def padded_size(width, height, tile=512, alignment=16): return (max(tile, math.ceil(width / alignment) * alignment), max(tile, math.ceil(height / alignment) * alignment)) def tile_starts(length, tile, overlap): if length < 1 or tile < 1 or not 0 <= overlap < tile: raise ValueError("Invalid tile geometry.") if length <= tile: return [0] positions = list(range(0, length - tile + 1, tile - overlap)) if positions[-1] != length - tile: positions.append(length - tile) return positions def tile_coordinates(height, width, tile_h, tile_w, overlap): return [(y, x) for y in tile_starts(height, tile_h, min(overlap, tile_h - 1)) for x in tile_starts(width, tile_w, min(overlap, tile_w - 1))]