Last active
June 20, 2023 14:27
-
-
Save willprice/fd917d2cafe56732137e60154d456688 to your computer and use it in GitHub Desktop.
PIL Image stacking
This file contains 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
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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks for the snippet
import missing:
import numpy as np