Question: 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')

```

Answer: 
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

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

```