Programmatically generate video or animated GIF in Python?
Well, now I'm using ImageMagick. I save my frames as PNG files and then invoke ImageMagick's convert.exe from Python to create an animated GIF. The nice thing about this approach is I can specify a frame duration for each frame individually. Unfortunately this depends on ImageMagick being installed on the machine. They have a Python wrapper but it looks pretty crappy and unsupported. Still open to other suggestions.
making gif from images using imageio in python
This works for me:
import os
import imageio
png_dir = '../animation/png'
images = []
for file_name in sorted(os.listdir(png_dir)):
if file_name.endswith('.png'):
file_path = os.path.join(png_dir, file_name)
images.append(imageio.imread(file_path))
# Make it pause at the end so that the viewers can ponder
for _ in range(10):
images.append(imageio.imread(file_path))
imageio.mimsave('../animation/gif/movie.gif', images)
How to generate a GIF without saving/importing image files?
I guess you need something like this. GIF is an image file type so you have to save it to have one.
#! /usr/bin/env python3
import numpy as np
from PIL import Image
im = []
for n in range(20):
arr = np.random.randint(low = 0, high = 255, size = (300, 300, 3))
im.append(Image.fromarray(arr.astype('uint8')))
im[0].save('im.gif', save_all=True, append_images=im[1:], optimize=False, duration=200, loop=0)
#im[0].show()
Then open im.gif
with a browser or some app that can show animated GIFs.
If you really don't want to save the GIF but just show it, you can do something like this
#! /usr/bin/env python3
import base64
import io
import numpy as np
from PIL import Image
from viaduc import Viaduc
im = []
for n in range(20):
arr = np.random.randint(low = 0, high = 255, size = (300, 300, 3))
im.append(Image.fromarray(arr.astype('uint8')))
buffer = io.BytesIO()
im[0].save(buffer, format='GIF', save_all=True, append_images=im[1:], optimize=False, duration=200, loop=0)
buffer.seek(0)
data_uri = base64.b64encode(buffer.read()).decode('ascii')
class Presentation(Viaduc.Presentation):
width = 300
height = 300
title = 'gif'
html = '''
<!DOCTYPE html>
<head>
{{bootstrap_meta}} {{bootstrap_css}}
<title>{{title}}</title>
</head>
<body>
<img src="data:image/gif;base64,''' + data_uri + '''">
{{bootstrap_js}}
</body>
</html>
'''
if __name__ == '__main__':
Viaduc(presentation=Presentation())
Using PIL to generate gif from many png files
As others have mentioned in comments the code you posted works on the latest Python + pillow distribution. Possible issue with your pillow version, similar issue is mentioned here PIL.PngImagePlugin.PngImageFile images can't be saved as GIFs in 7.1.1.
Solution in that issue is to
- update Pillow
- .copy() all frames
- use jpg instead of png.
How to create gifs with images in Python
Here is something that I wrote a while ago. I couldn't find anything better when I wrote this in the last six months. Hopefully this can get you started. It uses ImageMagick found here!
import os, sys
import glob
dataDir = 'directory of image files' #must contain only image files
#change directory gif directory
os.chdir(dataDir)
#Create txt file for gif command
fileList = glob.glob('*') #star grabs everything, can change to *.png for only png files
fileList.sort()
#writes txt file
file = open('blob_fileList.txt', 'w')
for item in fileList:
file.write("%s\n" % item)
file.close()
#verifies correct convert command is being used, then converts gif and png to new gif
os.system('SETLOCAL EnableDelayedExpansion')
os.system('SET IMCONV="C:\Program Files\ImageMagick-6.9.1-Q16\Convert"')
# The following line is where you can set delay of images (100)
os.system('%IMCONV% -delay 100 @fileList.txt theblob.gif')
New convert call
For whatever reason (I didn't look at differences), I no longer needed the set local and set command lines in the code. I needed it before because the convert command was not being used even with path set. When you use the new 7.. release of image magick. See new line of code to replace last three lines. Be sure to check box that ask to download legacy commands e.g convert when installing. Everything was converted to a single magick command, but I didnt want to relearn the new conventions.
os.system('convert -delay 50 @fileList.txt animated.gif')
Related Topics
Apply VS Transform on a Group Object
How to Use Python to Login to a Webpage and Retrieve Cookies for Later Usage
Directory-Tree Listing in Python
Main() Function Doesn't Run When Running Script
Using Python Requests with JavaScript Pages
I Need to Securely Store a Username and Password in Python, What Are My Options
How to Get Week Number in Python
How to Access the Ith Column of a Numpy Multidimensional Array
How to Extract the N-Th Elements from a List of Tuples
Using Pip Behind a Proxy with Cntlm
How to Add Property to a Class Dynamically
How to Manage Local VS Production Settings in Django
Pandas Read_Csv: Low_Memory and Dtype Options
Rewrite Multiple Lines in the Console