Skip to content

Instantly share code, notes, and snippets.

@saravanabalagi
Created December 11, 2023 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saravanabalagi/7bac9669e0a80f58ac8ff06c7920a7e5 to your computer and use it in GitHub Desktop.
Save saravanabalagi/7bac9669e0a80f58ac8ff06c7920a7e5 to your computer and use it in GitHub Desktop.
Combines images horizontally using imagemagick in the specified directory based on filename suffixes: img_01.jpg, img_02.jpg, img_03.jpg will be combined into img.jpg
from pathlib import Path
import subprocess
import argparse
def find_and_append_images_with_pathlib(directory):
"""
Adjusted script using pathlib to find images in the specified directory with a given pattern
and append them horizontally using the 'convert' command from ImageMagick.
It supports both .jpg and .png files and handles different suffix patterns.
"""
# Supported image extensions
extensions = ["jpg", "png"]
# Dictionary to store found files
files_to_append = {}
# Use pathlib to iterate through the files in the directory
for file_path in Path(directory).glob('*'):
file_ext = file_path.suffix[1:].lower()
if file_ext not in extensions:
continue
name = file_path.stem
if '_' not in name:
continue
num_suffix = name.split('_')[-1]
if not num_suffix.isdigit():
continue
base_name = name[:-len(num_suffix) - 1]
if base_name not in files_to_append:
files_to_append[base_name] = []
files_to_append[base_name].append(file_path)
for base_name, files in files_to_append.items():
suffix = files[0].suffix
output_file = Path(directory) / f"{base_name}{suffix}"
files_str = sorted(map(str, files))
# Run the 'convert' command to append images
command = ["convert"] + files_str + ["+append", str(output_file)]
print(f"Running command: {' '.join(command)}")
subprocess.run(command)
return files_to_append
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Append images in a directory with a given pattern.')
parser.add_argument('directory', type=str, help='directory to search for images')
args = parser.parse_args()
find_and_append_images_with_pathlib(args.directory)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment