How to select images with numbered filenames and append all images together horizontally

Question:

I have several image files whose names are numbered 1-300. (frame1jpg, .. ,frame300.jpg)

I would like to append all images together horizontally by select (n) and Start/End file.

And I can change (n) and start/end files.

Example1: (n) = 5, start frame5.jpg end frame30.jpg. After that append from frame5.jpg, frame10.jpg,..,frame25.jpg

Example2: (n) = 7, start frame0.jpg end frame25.jpg. After that append from frame0.jpg, frame7.jpg,..,frame21.jpg

Now I have code to append image as below.

import sys
from PIL import Image

images = [Image.open(x) for x in ['frame45.jpg','frame55.jpg','frame65.jpg','frame75.jpg','frame85.jpg']]
widths, heights = zip(*(i.size for i in images))

total_width = sum(widths)
max_height = max(heights)

new_im = Image.new('RGB', (total_width, max_height))

x_offset = 0
for im in images:
  new_im.paste(im, (x_offset,0))
  x_offset += im.size[0]

new_im.save('00final.png')

I’d like to change from.

images = [Image.open(x) for x in ['frame45.jpg','frame55.jpg','frame65.jpg','frame75.jpg','frame85.jpg']]

To easy define (n) and Start/End file.

Asked By: Kukkik

||

Answers:

Just get the list of filenames given your start, end and step:

def get_images(start, end, step):
    file_list = [f"frame{i}.jpg" for i in range(start, end, step)]   
    return [Image.open(x) for x in file_list]

images = get_images(start, end, step)
Answered By: Andrey Sobolev
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.