Python 3 implements GIF inversion and generates GIF from multiple images

Time:2020-2-28

Original link he Xiaodong blog

An entertainment code, it’s funny to put the expression pack GIF upside down as a small toy of your own. The operation is to read the pictures into frames, merge them upside down, and then make them into new pictures.

Effects: before flippingPython 3 implements GIF inversion and generates GIF from multiple imagesAfter flipPython 3 implements GIF inversion and generates GIF from multiple images

The code is as follows:

# encoding: utf-8

from PIL import Image, ImageSequence 

Read GIF

im = Image.open("nba.gif")

#Iterator of GIF picture stream

iter = ImageSequence.Iterator(im)

index = 1
#Traverse every frame of the picture stream

for frame in iter:
    print("image %d: mode %s, size %s" % (index, frame.mode, frame.size))
    frame.save("./images/frame%d.png" % index)
    index += 1

# frame0 = frames[0]

# frame0.show()

#Split GIF into picture streams

imgs = [frame.copy() for frame in ImageSequence.Iterator(im)]

#Make picture stream into GIF moving picture again

# imgs[0].save('out.gif', save_all=True, append_images=imgs[1:])

#Reverse picture flow

imgs.reverse()

#Save all frame images after reverse order

imgs[0].save('./reverse_out.gif', save_all=True, append_images=imgs[1:])

In addition, the minimalist version is simpler

# encoding: utf-8

from PIL import Image, ImageSequence 

im = Image.open(r'./nba.gif')
sequence = []

for f in ImageSequence.Iterator(im):
    sequence.append(f.copy())    

sequence.reverse()
sequence[0].save(r'./r-nba.gif',save_all = True, append_images=sequence[1:])

It’s very useful to generate GIF code from multiple static images. At the end of this year, you can merge the annual images into a large GIF for memory

# coding=utf8

import imageio
import os 

path = '../images'
filenames = []
for files in os.listdir(path):
    if files.endswith('jpg') or files.endswith('jpeg') or files.endswith('png'):
        file = os.path.join(path,files)
        filenames.append(file)

images = []
for filename in filenames:
    images.append(imageio.imread(filename))
    
imageio.mimsave('movie.gif', images, duration = 0.3)

The original author does not recommend using image2gif package. Please refer to the first floor for details

Of course, if you have a need, you will have a groupSame size photo generation gif, email: [email protected]

Reference link:

  1. Zhihu cvpy column
  2. Official documents of imageio

Youth, you must be eager for the source of knowledge