I have about 250 .png files in one directory.
I need to vertically concatenate them from python.
Here is the code I have so far.
list_im = [] <- this is the list of .png files <- How do I populate it if I have 250 files in one directory?
imgs = [ Image.open(i) for i in list_im ]
# pick the image which is the smallest, and resize the others to match it (can be arbitrary image shape here)
min_shape = sorted( [(np.sum(i.size), i.size ) for i in imgs])[0][1]
imgs_comb = np.hstack([i.resize(min_shape) for i in imgs])
# for a vertical stacking it is simple: use vstack
imgs_comb = np.vstack([i.resize(min_shape) for i in imgs])
imgs_comb = Image.fromarray( imgs_comb)
imgs_comb.save('concatenatedPNGFiles.png' )
How do I populate the list_im with 250 .png files in python?
>Solution :
I would do something like this:
import os from glob import glob from PIL import Image import numpy as np # Get the directory path where your PNG files are stored directory_path = "/path/to/directory/with/png/files" # Create a list of all PNG file paths in the directory list_im = glob(os.path.join(directory_path, "*.png")) imgs = [Image.open(i) for i in list_im] # pick the image which is the smallest, and resize the others to match it (can be arbitrary image shape here) min_shape = sorted([(np.sum(i.size), i.size) for i in imgs])[0][1] imgs_comb = np.vstack([i.resize(min_shape) for i in imgs]) imgs_comb = Image.fromarray(imgs_comb) imgs_comb.save('concatenatedPNGFiles.png')
- import os: This module provides a way to interact with the operating system, including file and directory operations.
- from glob import glob: The glob function from the glob module is used to find all pathnames matching a specified pattern (in this case, *.png).
- directory_path = "/path/to/directory/with/png/files": Replace this with the actual path to the directory containing your PNG files.
- list_im = glob(os.path.join(directory_path, ".png"))* : This line creates a list of all PNG file paths in the specified directory using glob. The os.path.join function is used to join the directory path and the pattern (*.png) to create a valid path.
With this modification, the list_im will contain all the PNG file paths in the specified directory, and the rest of your code should work as intended.