简体   繁体   中英

Loop through all the images in a folder in a certain order according to their file names

So, I want to create a utility to stitch images together. I have this code so far:

def merger(file1, file2):

    # File I/O: Open source images
    image1 = Image.open(file1)
    image2 = Image.open(file2)

    # Read the source image dimensions using pillow Image class
    (width1, height1) = image1.size
    (width2, height2) = image2.size

    # Calculate the output image dimensions
    merged_width = width1 + width2          # The width is a sum of the 2 widths
    merged_height = max(height1, height2)   # The height is the larger of the two

    # Merge the images using pillow Image class
    output = Image.new('RGB', (merged_width, merged_height))   # Create new image object (for output)
    output.paste(im=image1, box=(0, 0))                        # Paste the 1st source image into the output object
    output.paste(im=image2, box=(width1, 0))                   # Paste the 2nd source image into the output object
    return output

How do I cycle through all the image files in a folder? I suppose I'd use a loop, but how do I read each pair of image files present in a folder, recognize their order from the file names, stitch each pair together, then go on to the next pair of files?

Files should be stitched based on the numbers in the filenames. Examples:

1.jpg and 2.jpg should be stitched first, then 3.jpg and 4.jpg , 5.jpg and 6.jpg and so on.

OR

01.jpg and 02.jpg should be stitched first, then 03.jpg and 04.jpg , 05.jpg and 06.jpg and so on.

OR

scan01.tif and scan02.tif , then scan03.tif and scan04.tif , scan05.tif and scan06.tif ...

OR

newpic0001.png and newpic0002.png first, then newpic0003.png and newpic0004.png , then newpic0005.png and newpic0006.png ...

You get the idea: go according to the number at the end of the file, ignore the leading zeroes.

I am using pillow for image processing and tkinter for GUI if that matters.

Thanks.

Try this:

import os

file_list = [x for x in sorted([x for x in os.listdir('/path/to/directory/')])]
for i in range (0, len(file_list), 2):
    if i+1 < len(file_list):
        f1, f2 = file_list[i], file_list[i+1]
    else:
        f1, f2 = file_list[i], None
    # do your merge magic here with f1 and f2

References: Listing all directory in a path

This feels a little brutish, but it works. The idea is to get a list of filenames and then sort them by using only the digits from the filename.

import os
import re


def sort_filenames(all_files):
    filenames_sorted = []
    original_filenames = {}
    for full_filename in all_files:
        filename, file_extension = os.path.splitext(full_filename)

        # Save all the files names to be sorted
        filenames_sorted.append(filename)
        # Save original full filename in a dictionary for later retrieval
        original_filenames[filename] = full_filename

    # Sort the list using our own key
    filenames_sorted.sort(key=get_file_key)
    filenames = []
    for key in filenames_sorted:
        filenames.append(original_filenames[key])

    return filenames


def get_file_key(filename):
    # Remove all non-digits from the filename
    key = re.sub("[^0-9]", "", filename)
    return int(key)


# Start with the list of all files in the current directory
all_files = os.listdir("./")

# FOR TESTING ONLY....fill all_files with some testing examples
all_files = ['scan01.tif', 'scan04.tif', 'scan03.tif', 'scan05.tif', 'scan06.tif', 'scan02.tif']
all_files = ['newpic0002.png', 'newpic0001.png', 'newpic0003.png', 'newpic0006.png', 'newpic0005.png', 'newpic0004.png']

sorted_files = sort_filenames(all_files)

for i in range(0, len(sorted_files) - 1, 2):
    # Just printing the statement to confirm we have it right
    print('merger({}, {})'.format(sorted_files[i], sorted_files[i + 1]))


Note : that get_file_key() extracts the digits from the filename and uses them for sorting the array. If you have filenames that contain digits that are not part of the sorting then you may have issues here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM