0
votes

I have two different folders a and b. The 'a' folder contains images of the format a_i.jpg (where i = 1 to N). The 'b' folder contains images of the format 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.

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')
1

1 Answers

0
votes

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")