Created
June 28, 2025 19:53
-
-
Save pszemraj/7ff201c6a2d15b394da9a52fff04b964 to your computer and use it in GitHub Desktop.
Slice a tall image into chunks.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
Slice a (possibly very tall) image into fixed-height chunks. | |
Creates a sibling directory called <image stem>_slices/ | |
and writes slice_000.png, slice_001.png, … inside it. | |
""" | |
import argparse | |
from pathlib import Path | |
from PIL import Image | |
def slice_image(path: Path, slice_height: int) -> None: | |
img = Image.open(path) | |
w, h = img.size | |
# Where to write the chunks | |
out_dir = path.with_suffix("").with_name(f"{path.stem}_slices") | |
out_dir.mkdir(exist_ok=True) | |
n_slices = (h + slice_height - 1) // slice_height | |
for i in range(n_slices): | |
top = i * slice_height | |
bottom = min(top + slice_height, h) | |
box = (0, top, w, bottom) | |
chunk = img.crop(box) | |
out_file = out_dir / f"slice_{i:03}_of_{n_slices}.png" | |
chunk.save(out_file) | |
print(f"wrote {out_file} ({w}×{bottom - top}px)") | |
print(f"\nDone. {n_slices} slice(s) in {out_dir}") | |
def main() -> None: | |
parser = argparse.ArgumentParser( | |
description="Slice a tall image into chunks.", | |
formatter_class=argparse.ArgumentDefaultsHelpFormatter, | |
) | |
parser.add_argument("image", type=Path, help="Path to the source image") | |
parser.add_argument( | |
"--height", | |
"-H", | |
type=int, | |
default=1024, | |
help="Height of each slice in pixels", | |
) | |
args = parser.parse_args() | |
if not args.image.is_file(): | |
parser.error(f"File not found: {args.image}") | |
slice_image(args.image, args.height) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment