Skip to content

Instantly share code, notes, and snippets.

@willprice
Last active June 20, 2023 14:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willprice/fd917d2cafe56732137e60154d456688 to your computer and use it in GitHub Desktop.
Save willprice/fd917d2cafe56732137e60154d456688 to your computer and use it in GitHub Desktop.
PIL Image stacking
import numpy as np
from PIL import Image
def vstack(images):
if len(images) == 0:
raise ValueError("Need 0 or more images")
if isinstance(images[0], np.ndarray):
images = [Image.fromarray(img) for img in images]
width = max([img.size[0] for img in images])
height = sum([img.size[1] for img in images])
stacked = Image.new(images[0].mode, (width, height))
y_pos = 0
for img in images:
stacked.paste(img, (0, y_pos))
y_pos += img.size[1]
return stacked
def hstack(images):
if len(images) == 0:
raise ValueError("Need 0 or more images")
if isinstance(images[0], np.ndarray):
images = [Image.fromarray(img) for img in images]
width = sum([img.size[0] for img in images])
height = max([img.size[1] for img in images])
stacked = Image.new(images[0].mode, (width, height))
x_pos = 0
for img in images:
stacked.paste(img, (x_pos, 0))
x_pos += img.size[0]
return stacked
@rilshok
Copy link

rilshok commented Jul 7, 2022

thanks for the snippet
import missing:
import numpy as np

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment