Last active
December 12, 2021 02:56
-
-
Save hanglearning/1a17b44fdb6335b3aeae7fd2f8066053 to your computer and use it in GitHub Desktop.
Vertically stack two images
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
# ref https://stackoverflow.com/questions/53876007/how-to-vertically-merge-two-images/53882483 | |
# usage | |
# $ python vertical_stack.py </path/to/top/figure> </path/to/bottom/figure> </directory/to/output/figure> <output_file_name_with_extension> | |
# <output_file_name_with_extension> is optional, default to vertical_stack.png | |
# example | |
# $ python stack_vertical_images.py /Users/foo/bar/top_figure.png /Users/foo/bar/button_figure.png /Users/output vertical_stack.png | |
# NOTE | |
# there is no ending slash / in </directory/to/output/figure> !! | |
from PIL import Image | |
import sys | |
images_list = [sys.argv[1], sys.argv[2]] | |
imgs = [Image.open(i) for i in images_list] | |
try: | |
image_name = sys.argv[4] | |
except: | |
image_name = "vertical_stack.png" | |
min_img_width = min(i.width for i in imgs) | |
total_height = 0 | |
for i, img in enumerate(imgs): | |
# If the image is larger than the minimum width, resize it | |
if img.width > min_img_width: | |
imgs[i] = img.resize((min_img_width, int(img.height / img.width * min_img_width)), Image.ANTIALIAS) | |
total_height += imgs[i].height | |
img_merge = Image.new(imgs[0].mode, (min_img_width, total_height)) | |
y = 0 | |
for img in imgs: | |
img_merge.paste(img, (0, y)) | |
y += img.height | |
img_merge.save(f"{sys.argv[3]}/{image_name}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment