Created
February 13, 2020 16:25
-
-
Save nanduzira/423a9bec205baebe3d40de5e0cf32283 to your computer and use it in GitHub Desktop.
Script to combine multiple images into a single one.
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 sys | |
from PIL import Image | |
from itertools import islice | |
n_factors = list() | |
def factors(n, i): | |
if i==0: | |
return | |
elif n%i == 0: | |
n_factors.append(i) | |
return factors(n, i-1) | |
def xy(n): | |
global n_factors | |
n_factors = [] | |
factors(n, n) | |
n_factors.sort() | |
x = n_factors[int(len(n_factors)/2)] | |
return x, int(n/x) | |
def image_combine(imgs:list): | |
x,y = xy(len(imgs)) | |
it = iter(imgs) | |
img_list = [list(islice(it, x)) for i in range(y)] | |
images = [] | |
total_width = 0 | |
total_height = 0 | |
for i in range(y): | |
images.append([Image.open(img_list[i][j]) for j in range(x)]) | |
widths, heights = zip(*(j.size for j in images[i])) | |
total_width = max([sum(widths), total_width]) | |
total_height += max(heights) | |
new_im = Image.new('RGB', (total_width, total_height)) | |
y_offset = 0 | |
for imx in images: | |
x_offset = 0 | |
max_height = 0 | |
for imy in imx: | |
new_im.paste(imy, (x_offset, y_offset)) | |
x_offset += imy.size[0] | |
max_height = max([max_height,imy.size[1]]) | |
y_offset += max_height | |
new_im.save('test.png') | |
if __name__=="__main__": | |
imgs = [ | |
"1.png", | |
"2.png", | |
"3.png", | |
"4.png", | |
"5.png", | |
"6.png", | |
"3.png", | |
"2.png", | |
"1.png" | |
] | |
image_combine(imgs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment