因此,我想创建一个将图像拼接在一起的实用程序。 到目前为止,我已经有了这段代码:
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
如何循环浏览文件夹中的所有图像文件? 我想我会使用一个循环,但是如何读取文件夹中存在的每对图像文件,从文件名中识别它们的顺序,将每对图像缝合在一起,然后转到下一对文件?
文件应根据文件名中的数字进行拼接。例子:
1.jpg
和2.jpg
应该先缝合,然后再缝合3.jpg
和4.jpg
,5.jpg
和6.jpg
,依此类推。
OR
01.jpg
和02.jpg
应该先缝合,然后再缝合03.jpg
和04.jpg
,05.jpg
和06.jpg
,依此类推。
OR
scan01.tif
和scan02.tif
,然后scan03.tif
和scan04.tif
,scan05.tif
和scan06.tif
...
OR
newpic0001.png
和newpic0002.png
,然后是newpic0003.png
和newpic0004.png
,然后是newpic0005.png
和newpic0006.png
...
您有个主意:按照文件末尾的数字前进,忽略前导零。
如果重要的话,我正在使用枕头进行图像处理,并使用tkinter进行GUI。
谢谢。
答案 0 :(得分:1)
尝试一下:
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
答案 1 :(得分:0)
这感觉有些野蛮,但是可以。想法是获取文件名列表,然后仅使用文件名中的数字对它们进行排序。
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]))
注意:get_file_key()
从文件名中提取数字并将其用于对数组进行排序。如果文件名中包含的数字不属于排序范围,那么此处可能会有问题。