Similar to the pattern described on the site below, but
I want to connect the images in folder A and folder B horizontally in order, not all combinations.

With the code below, a tremendous number of new images will be created, which is the number of images in folder A x the number of images in folder B.

from PIL import Image
import itertools
from pathlib import Path
def get_concat_h (im1, im2, color = "black"):
    dst = Image.new (
        'RGB', (im1.width + im2.width, im1.height))
    dst.paste (im1, (0, 0))
    dst.paste (im2, (im1.width, 0))
    return dst
img_dir1 = Path ("folder location/trainA") # directory with images on the left
img_dir2 = Path ("folder location/trainB") # directory with the image on the right
output_dir = Path ("folder location/combined") # output directory
output_dir.mkdir (exist_ok = True)
for path1, path2 in itertools.product (img_dir1.iterdir (), img_dir2.iterdir ()):
    print (f "concat {path1} and {path2}")
    img1 = Image.open (path1)
    img2 = Image.open (path2)
    dst = get_concat_h (img1, img2)
    save_path = output_dir/f "{path1.stem} _ {path2.stem} .jpg"
    dst.save (save_path)

The purpose is to make the image generated in the following folder C into a pix2pix dataset.

256 x 256 images in folder A
256 x 256 images in folder B
512 x 256 images with the above connected horizontally in folder C

├── a.jpg
└── b.jpg
└── c.jpg
└── d.jpg
└── e.jpg

├── f.jpg
└── g.jpg
└── h.jpg
└── i.jpg
└── j.jpg

├── a_f.jpg
├── b_g.jpg
├── c_h.jpg
└── d_i.jpg
└── e_j.jpg

I would appreciate it if you could teach me.

  • Answer # 1

    I'm not sure how I want the JPG files in directories A and B to correspond, so this may not be OK, but if I want to correspond one file in each directory. For example, what if the for line looks like this?

    for path1, path2 in zip (list (img_dir1.glob ("* .jpg")), list (img_dir2.glob ("* .jpg"))):