kame
kame

Reputation: 21960

Python: Animation with PIL

I want an animated picture. But I need a refresh-function because plt.show() always opens a new window. Does anybody have a hint? Thanks!

import numpy as np
import scipy
from scipy import *
import matplotlib.pyplot as plt

#array
aa = []
for x in range(44):
    aa.append([])
    for z in range(44):
        aa[x].append(3*sin(x/3.0)+2*cos(z/3.0))

b = aa
plt.imshow(b)
plt.show()

time = 0
dt = 0.1
while(time<3):
    b = sin(aa)
    time += dt

Upvotes: 6

Views: 8893

Answers (2)

Glen Davies
Glen Davies

Reputation: 156

In addition to the other answer about GUI toolkits, you could also save the images and build an animation after the fact.

If the image has few enough colours, PIL can save as a gif directly, as seen in this blog post

The relevant part:

frames = []
x, y = 0, 0
for i in range(10):
    new_frame = create_image_with_ball(400, 400, x, y, 40) # your imgs here
    frames.append(new_frame)
    x += 40 # you wont need these
    y += 40 # 

# Save into a GIF file that loops forever
frames[0].save('moving_ball.gif', format='GIF', append_images=frames[1:], save_all=True, duration=100, loop=0)

It will require modification for your purposes, but I have added a few comments to get you started.

Upvotes: 5

Dan Passaro
Dan Passaro

Reputation: 4387

PIL is geared towards image editing, not animating or displaying. Instead, look to a GUI toolkit or a multimedia library like pyglet or pygame

Upvotes: 8

Related Questions