I'm trying to write a file with multiple images (100) in a 10x10 grid. I use 3 for iterations to:
-open the file -set coordinates (i,j)
The problem is when I look my file, all I can see is the last image multiple times. Maybe the files is overwrite every time that the program enters the for loop. Until now I can't find a solution.
The code is:
import Image
from os import listdir
from os.path import isfile, join
files = [ f for f in listdir("/mnt/hgfs/Documents/Notebooks/test1/") if isfile(join("/mnt/hgfs/Documents/Notebooks/test1/", f)) ]
new_im = Image.new('RGB', (3000,3000))
for i in xrange(0,3000,300):
for j in xrange(0,3000,300):
for ima in files:
#paste the image at location i,j:
im = Image.open(ima)
im.thumbnail((300,300))
new_im.paste(im, (i,j))
new_im.save("hola.png")
Thanks!
Here's a simple bug fix. You only need two for loops, not three.
import Image
from os import listdir
from os.path import isfile, join
files = [ f for f in listdir("/mnt/hgfs/Documents/Notebooks/test1/") if isfile(join("/mnt/hgfs/Documents/Notebooks/test1/", f)) ]
new_im = Image.new('RGB', (3000,3000))
index = 0
for i in xrange(0,3000,300):
for j in xrange(0,3000,300):
im = Image.open(files[index])
im.thumbnail((300,300))
new_im.paste(im, (i,j))
index += 1
new_im.save("hola.png")
This is the Python 3 code to make a squre grid of images file from any directory with images using matplotlib. Square size calculates dynamicly by count of existing images.
import math
import os
import matplotlib.pyplot as plt
# Config:
images_dir = './your_dir_with_images'
result_grid_filename = './grid.jpg'
result_figsize_resolution = 40 # 1 = 100px
images_list = os.listdir(images_dir)
images_count = len(images_list)
print('Images: ', images_list)
print('Images count: ', images_count)
# Calculate the grid size:
grid_size = math.ceil(math.sqrt(images_count))
# Create plt plot:
fig, axes = plt.subplots(grid_size, grid_size, figsize=(result_figsize_resolution, result_figsize_resolution))
current_file_number = 0
for image_filename in images_list:
x_position = current_file_number % grid_size
y_position = current_file_number // grid_size
plt_image = plt.imread(images_dir + '/' + images_list[current_file_number])
axes[x_position, y_position].imshow(plt_image)
print((current_file_number + 1), '/', images_count, ': ', image_filename)
current_file_number += 1
plt.subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0)
plt.savefig(result_grid_filename)
Images in the directory screenshot
result grid image file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With