Creating Animations With NumPy
00:00 Using NumPy to Create Animations. In the previous section of the course, you created a color image containing three overlapping squares of different colors. In this section of the course, you’ll create an animation showing those three squares merging into a single white square.
00:16 You’ll create several versions of the images containing the squares, and the location of the squares will vary between successive images.
00:28
You create an empty list called square_animation
, which you’ll use to store the images you generate.
00:36
Within the for
loop, you create NumPy arrays for the red, green, and blue channels, as you did in the previous section.
00:48 The red square starts in a position displaced to the top left of the center. In each successive frame, the red square moves closer to the center until it reaches it in the final iteration of the loop.
01:00 The array containing the green layer is always the same and represents a square in the center of the image. The blue square is initially shifted towards the bottom right and moves towards the center in a similar way.
01:15
Note that in this example, you’re iterating over the range(0, 102, 2)
, which means that the variable offset
increases in steps of two.
01:24 Each of the red, green, and blue images is created separately as a grayscale image, and while they’re named after each color, there isn’t any color information actually present in the images at this point.
01:40 The animation now has a new frame appended to it, consisting of a merge of the three images in the red, green, and blue channels. This is where the color is created.
01:58
You learned earlier on that you can save an Image
object to a file using Image.save()
. You can use the same function to save a GIF file that includes a sequence of images. You call Image.save()
on the first image in the sequence, which is the first image that you stored in the list square_animation
.
02:17
The first argument in .save()
is the filename for the file that you want to save. The extension in the filename tells .save()
which file format it needs to output.
02:27
You also include two keyword arguments in .save()
. save_all=True
ensures that all the images in the sequence are saved and not just the first one.
02:38
append_images
allows you to append the remaining images in the sequence to the file. Once the file is saved, which may take some time depending on your system, you can open it with any image software.
02:52
The image should loop by default, but on some systems, you’ll need to add the keyword argument loop=0
to .save()
to make sure that it does. Now that you’ve seen what to do, you can experiment by trying to create your own animation using different shapes and different colors. But in the next section of the course, you’ll take a look back at what you’ve learned.
Become a Member to join the conversation.