[英]Merging images from different source folders
I have two different folders a and b.我有两个不同的文件夹 a 和 b。 The 'a' folder contains images of the format a_i.jpg (where i = 1 to N).
“a”文件夹包含格式为 a_i.jpg(其中 i = 1 到 N)的图像。 The 'b' folder contains images of the format b_i.jpg.
“b”文件夹包含格式为 b_i.jpg 的图像。 I want to merge these images taking a_1 and merging it with b_1, a_2 with b_2, .... a_N with b_N and then store the new image dataset in a different folder that contains 'N' merged images of the same format and n_i.jpg.
我想合并这些图像,将 a_1 与 b_1 合并,将 a_2 与 b_2 合并,.... a_N 与 b_N,然后将新图像数据集存储在包含“N”个相同格式和 n_i 的合并图像的不同文件夹中。 .jpg
NOTE: I made sure that all the images are of the same size.注意:我确保所有图像的大小相同。
With this code I'm able to merge singular files, but how do I loop over the entire folders as mentioned above?使用此代码,我可以合并单个文件,但是如何循环遍历上面提到的整个文件夹?
images = [Image.open(x) for x in ['in.jpg', 'tulips.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('new2.jpg')
I hope the below solution is what you are looking for我希望以下解决方案是您正在寻找的
source_folder1 = "a"
source_folder2 = "b"
target_folder = "Image_Merged"
for img_no in range(1,n+1):
img1 = source_folder1+"_"+str(img_no)+".jpg"
img2 = source_folder2+"_"+str(img_no)+".jpg"
images = [Image.open(x) for x in [img1, img2]]
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(target_folder+"/target_folder_"+str(img_no)+".jpg")
based on @palash-jhamb answer, there are few changes基于@palash-jhamb 的回答,变化不大
from PIL import Image
source_folder1 = 'a/'
source_folder2 = 'b/'
target_folder = 'Image_Merged/'
n = len(source_folder1)+1
for img_no in range(1,n+1):
img1 = (source_folder1+str(img_no)+".jpg")
img2 = (source_folder2+str(img_no)+".jpg")
images = [Image.open(x) for x in [img1, img2]]
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(target_folder+"/target_folder_"+str(img_no)+".jpg")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.