Elias EstatisticsEU Elias EstatisticsEU - 4 months ago 11
Python Question

Combine multiple different images from a directory into a canvas sized 3x6

I itirate to images of a directory. I want from those images to create a 3x6 canvas, a new image that will display the images of that directory side by side into a single image / canvas. Each image must be a different image. Side by side. –

I have the following code. It tries to read the image filenames from a directory that are stored into a list. Then it tries to copy / combine each image into a 3x6 canvas. However, the result that i want happens not.
What i am doing wrong?

import Image
import os
import PIL
import glob
import matplotlib.pyplot as plt

# path
path = "/media/"
listing = os.listdir(path)

# getting all path+filename in a list
npath=[]
im=[]
for infile in listing:
im.append(infile)
npath.append(os.path.join(path, infile))

#creates a new empty image, RGB mode, and size 400 by 400.
new_im = Image.new('RGB', (2100,2400))


#Here I resize my opened image, so it is no bigger than ****
#Iterate through a grid with some spacing, to place my image
for i in xrange(0,2100,700):
for j in xrange(0,2400, 400):
for imagefile in npath:
im=Image.open(imagefile)
im.thumbnail((1000,1000))
#paste the image at location i,j:
new_im.paste(im, (i,j))
new_im.show()
#saving
new_im.save('/media/test.png')


The solution

import Image
import os
import PIL
import glob
import matplotlib.pyplot as plt

# path
path = "/media/estatistics/Mydisk/Dika_mou/Dimiourgies/music/png_3d/new/"
listing = os.listdir(path)


# getting all path+filename in a list
npath=[]
im=[]

for infile in listing:
im.append(infile)
npath.append(os.path.join(path, infile))

#creates a new empty image, RGB mode, and size 400 by 400.
new_im = Image.new('RGB', (2500,3000))

for i in xrange(0,2500,800):
for j in xrange(0,3000, 500):
im=Image.open(npath.pop(0))
im.thumbnail((1000,1000))
#paste the image at location i,j:
new_im.paste(im, (i,j))
new_im.save('/media/test.png')

Answer

Do not iterate over the image list for every position but consume the list:

for i in xrange(0,2100,700):
    for j in xrange(0,2400, 400):
        try:
            im=Image.open(npath.pop(0))
            im.thumbnail((1000,1000))
            #paste the image at location i,j:
            new_im.paste(im, (i,j))
        except IndexError:
            continue