Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I make GIF using arrays

Need some help

I am working with "moving_mnist" dataset. Loading this data using tfds.load("moving_mnist") and then convert it in arrays using tfds.as_numpy() which will return image sequence arrays of shape (20,64,64,1) where 20 is number of frames. Now what I want, to show these arrays as GIF in my jupyter notebook please see below code which I tried but it will generate simple image for last frame.

import tensorflow_datasets as tfds
ds, ds_info = tfds.load("moving_mnist", with_info = True,split="test")

num_examples = 3
examples = list(dataset_utils.as_numpy(ds.take(num_examples)))
fig = plt.figure(figsize=(3*3, 3*3))
fig.subplots_adjust(hspace=1/3, wspace=1/3)
for i, ex in enumerate(examples):
   video = ex["image-sequence"]
   frame,height, width, c = video.shape

   if c == 1:
       video = video.reshape(video.shape[:3])

       for i in range(0,frame):
       ax.imshow(video[i,:,:], animated=True)

Here is result I got but want it as GIF

like image 805
Eshan Agarwal Avatar asked Oct 24 '25 18:10

Eshan Agarwal


2 Answers

The moviepy library makes this pretty easy:

import numpy as np
frames = np.random.randint(256, size=[20, 64, 64, 1], dtype=np.uint8)  # YOUR DATA HERE

# save it as a gif
from moviepy import ImageSequenceClip
clip = ImageSequenceClip(list(frames), fps=20)
clip.write_gif('test.gif', fps=20)

Then if you want to show that gif in a jupyter notebook, in the next cell you can type:

from IPython.display import display, Image
Image('test.gif')
like image 150
matwilso Avatar answered Oct 26 '25 07:10

matwilso


you could use the library array2gif.

Here is in example taken from the docs:

import numpy as np
from array2gif import write_gif

dataset = [
    np.array([
        [[255, 0, 0], [255, 0, 0]],  # red intensities
        [[0, 255, 0], [0, 255, 0]],  # green intensities
        [[0, 0, 255], [0, 0, 255]]   # blue intensities
    ]),
    np.array([
        [[0, 0, 255], [0, 0, 255]],
        [[0, 255, 0], [0, 255, 0]],
        [[255, 0, 0], [255, 0, 0]]
    ])
]
write_gif(dataset, 'rgbbgr.gif', fps=5)
like image 40
Hendrik Evert Avatar answered Oct 26 '25 06:10

Hendrik Evert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!