Created
August 19, 2022 07:49
-
-
Save jwc20/46b2ed409f26fb266ad2f05c7822e3c1 to your computer and use it in GitHub Desktop.
Stitch images vertically
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
import numpy as np | |
from PIL import Image | |
import glob | |
list_im = glob.glob("*.png") | |
total_width = 0 | |
total_height = 0 | |
max_width = 0 | |
max_height = 0 | |
min_width = 2000 | |
min_height = 0 | |
pre_w = 0 | |
pre_h = 0 | |
ix = [] | |
d = {} | |
for img in list_im: | |
if "_" in img: | |
img_num = img.split("_")[0] | |
else: | |
img_num = img.split(".")[0] | |
if img_num.isnumeric(): | |
d[img] = int(img_num) | |
for img in sorted(d, key=d.get, reverse=False): | |
im = Image.open(img) | |
size = im.size | |
w = size[0] | |
h = size[1] | |
total_width += w | |
total_height += h | |
if h > max_height: | |
max_height = h | |
if w > max_width: | |
max_width = w | |
if h < min_height: | |
min_height = h | |
if w < min_width: | |
min_width = w | |
ix.append(im) | |
target_vertical = Image.new("RGB", (max_width, total_height)) | |
for img in ix: | |
target_vertical.paste(img, (pre_w, pre_h, pre_w + img.size[0], pre_h + img.size[1])) | |
pre_h += img.size[1] | |
tw, th = target_vertical.size | |
target_vertical.crop((0, 0, tw - (max_width - min_width), th)).save( | |
"result_sorted_combined.png", quality=100 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment