Friday, May 21, 2021

Fun with Matplotlib : Creating a GIF of randomly generated images

import matplotlib.pyplot as plt
import numpy 
from numpy import random
import os 
import imageio
import glob

#rm -r  /content/images

images_dir = "/content/images"
if (os.path.exists(images_dir) == False): 
  os.mkdir(images_dir)

num_of_files = 10
cmaplist = plt.colormaps()

for i in range(num_of_files) : 
  random_cmap_no = random.randint(0, len(cmaplist)-1)
  img = random.random((50,50))
  plt.text(10, 10,"{:03d} ".format(i) + cmaplist[random_cmap_no], 
           bbox=dict( edgecolor='red', linewidth=2, fc = (random.random(),random.random(),0.8)))
  plt.imshow(img,cmap = plt.get_cmap(cmaplist[random_cmap_no]) , interpolation="nearest")
  filename = "{}/{:03d}.png".format(images_dir, i)
  plt.savefig(filename)
  plt.show()
  
gif_file = images_dir + "/" + "myimages.gif"

filenames = glob.glob( images_dir + "/*.png")
filenames = sorted(filenames)
images  = []
for filename in filenames:
  images.append(imageio.imread(filename))
imageio.mimsave(gif_file, images)

#another approach found in a google tutorial
# with imageio.get_writer(gif_file, mode="I") as writer:
#   filenames = glob.glob( images_dir + "/*.png")
#   filenames = sorted(filenames)
#   for filename in filenames:
#     image = imageio.imread(filename)
#     writer.append_data(image)
#   image = imageio.imread(filename)
#   writer.append_data(image)

No comments:

Post a Comment

How to check local and global angular versions

 Use the command ng version (or ng v ) to find the version of Angular CLI in the current folder. Run it outside of the Angular project, to f...