STEM

Overlay Real-time Animations Using Pygame

In this post, I demonstrate how to load an image file and do some simple overlay animations, such as drawing different shapes of different colors at ever-changing locations over the image using nothing but the good-old Pygame library. The code and working demo are embedded below.

I wanted to load a static image of my choice, and create some animations on top of it without actually changing the original image. And I wanted to do it in Python. It turns out that Pygame library allows me to do exactly that. This is admittedly not a actually animating the image underneath, but drawing animated objects (in tihs case, shapes) on top of the image at varying locations by controlling the transparency of the objects on top such that the image underneath still shows through adequately during the animation.

Let me illustrate the objective with actual outputs. My original static image is as follows that I want to add some life and colors to:

The following one is a saved output from an animation by drawing multiple, random-colored rectangles at random locations of the image underneath using RGBA color codes with 25% transparency.


I can easily change the dimensions of the rectangles as well to achieve my desired effect as shown in the version below.


But there’s no reason to be confined to rectangles, I can do circles, ovals, squares, rectangles or combination of all of them all in one go as shown below.


With some modification, more complex shapes can also be overlaid. The complete code for the rectangular animation version of the program is shown below. You can also run the program by clicking on the Run icon on the widget below. You cannot select your own image here (since it’s coming from the virtual server where the code is hosted and the image name is hard-coded), but the code is obviously extensible enough to use any image of your choice. To extend it for user-selection of the image, and selection of the animation type, you can build a UI around the core logic of this program. Be sure to change the image_path to the file name and/or complete path and name in the example code below with your image.

This is an uncomplicated way for me to create some fun memories of my images or create some simple animations to share as animated GIFs or videos (AVI, mpeg, MP4). The Pygame window animations can be captured and saved to those formats using your favorite tool (or by extending the code to take snapshots and save to the required output format if so desired)…that is up to you.

Now, do you see any similarity between the software animations I did above and the album cover design for ‘Transfer Affection’ by A Flock of Seagulls band of the 80s? Hmmm…you decide.


I hope this was fun and informational for you…Happy coding!

Back To Top