Advertisement
OreganoHauch

working code for arranging images in grid (spacings not adjusted)

Dec 20th, 2020
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. from PIL import Image, ImageOps
  2. import random
  3.  
  4. random_setting = False
  5. savepng = False
  6.  
  7. def concat_images(image_paths, size, shape=None):
  8. # Open images and resize them
  9. width, height = size
  10. images = map(Image.open, image_paths)
  11. images = [ImageOps.fit(image, size, Image.ANTIALIAS)
  12. for image in images]
  13.  
  14. # Create canvas for the final image with total size
  15. shape = shape if shape else (1, len(images))
  16. image_size = (width * shape[1], height * shape[0])
  17. image = Image.new('RGB', image_size)
  18. # Paste images into final image
  19. for row in range(shape[0]):
  20. for col in range(shape[1]):
  21. offset = width * col, height * row
  22. idx = row * shape[1] + col
  23. image.paste(images[idx], offset)
  24.  
  25. return image
  26.  
  27. # Get list of image paths
  28. folder = "/asap3/petra3/gpfs/p06/2018/data/11005475/scratch_cc/Jan/savefig/plotXBIC_singlecell_new"
  29. image_paths = [os.path.join(folder, f)
  30. for f in sorted(os.listdir(folder)) if f.endswith('.png')]
  31.  
  32. if random_setting:
  33. # Random selection of images
  34. image_array = random.choices(image_paths, k=45)
  35. else:
  36. image_array = image_paths
  37.  
  38. if savepng:
  39. # Create and save image grid
  40. now = datetime.now()
  41. dt_string = now.strftime("%d-%m-%Y_%H_%M_%S")
  42. image = concat_images(image_array, (400, 400), shape=(5,9))
  43. image.save(f"image_{dt_string}.png", "PNG")
  44.  
  45. concat_images(image_array, (400, 400), shape=(5,9))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement