Python
video generation
GIF creation
animation
programming

Programmatically generate video or animated GIF in Python?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Python can generate videos and animated GIFs programmatically very effectively, but the right library depends on the output you want. If you need video encoding from frames, imageio or OpenCV are practical choices. If you need a lightweight animated GIF, Pillow or imageio usually gives a simpler workflow.

Start from a Sequence of Frames

Most programmatic animation pipelines work from frames. A frame can come from:

  • generated plots
  • PIL images
  • NumPy arrays
  • OpenCV drawing output

A simple example builds frames with Pillow.

python
1from PIL import Image, ImageDraw
2
3frames = []
4for x in range(0, 100, 10):
5    img = Image.new("RGB", (200, 100), "white")
6    draw = ImageDraw.Draw(img)
7    draw.ellipse((x, 40, x + 20, 60), fill="blue")
8    frames.append(img)

Once you have frames, exporting to GIF or video becomes a formatting step.

Create an Animated GIF with Pillow

Pillow makes GIF creation straightforward for small to moderate animations.

python
1from PIL import Image, ImageDraw
2
3frames = []
4for x in range(0, 100, 10):
5    img = Image.new("RGB", (200, 100), "white")
6    draw = ImageDraw.Draw(img)
7    draw.ellipse((x, 40, x + 20, 60), fill="blue")
8    frames.append(img)
9
10frames[0].save(
11    "animation.gif",
12    save_all=True,
13    append_images=frames[1:],
14    duration=100,
15    loop=0,
16)

This is a good solution when the animation is short and you do not need advanced video codecs.

The main limitation is that GIF is a restricted format with a limited color palette and larger file sizes compared with video.

Create a Video with imageio

For true video output, imageio is often the easiest starting point.

python
1import imageio.v2 as imageio
2import numpy as np
3
4frames = []
5for x in range(0, 100, 10):
6    frame = np.full((100, 200, 3), 255, dtype=np.uint8)
7    frame[40:60, x:x+20] = [0, 0, 255]
8    frames.append(frame)
9
10with imageio.get_writer("animation.mp4", fps=10) as writer:
11    for frame in frames:
12        writer.append_data(frame)

This is usually simpler than wiring OpenCV encoders directly, especially for scripts that already work with NumPy arrays.

Use OpenCV When Frames Already Live in OpenCV Pipelines

If your frames are being produced by computer vision code, OpenCV can write video directly.

python
1import cv2
2import numpy as np
3
4writer = cv2.VideoWriter(
5    "animation.avi",
6    cv2.VideoWriter_fourcc(*"XVID"),
7    10,
8    (200, 100)
9)
10
11for x in range(0, 100, 10):
12    frame = np.full((100, 200, 3), 255, dtype=np.uint8)
13    cv2.rectangle(frame, (x, 40), (x + 20, 60), (255, 0, 0), -1)
14    writer.write(frame)
15
16writer.release()

OpenCV is powerful, but codec configuration can be more finicky across platforms than a simpler imageio workflow.

Choose Output Format by the Actual Use Case

A GIF is convenient for chat apps, docs, and quick previews. A video is usually better when you care about:

  • file size
  • smooth playback
  • longer duration
  • color fidelity

That is why many workflows generate MP4 for production and GIF only for preview or sharing.

The technical work of frame generation may be the same, but the distribution goal should determine the final format.

Common Pitfalls

  • Treating GIF and video as interchangeable even though they have very different quality and size tradeoffs.
  • Generating frames in one library format and forgetting the writer expects NumPy arrays or another specific representation.
  • Choosing OpenCV first when a simpler writer such as Pillow or imageio would fit the task better.
  • Ignoring frame size consistency, which video encoders require.
  • Building all frames in memory for very long animations when a streaming write approach would be safer.

Summary

  • Programmatic animation in Python usually starts with a sequence of generated frames.
  • Pillow is a simple choice for animated GIF output.
  • 'imageio is an easy way to write MP4 or GIF from NumPy-based frames.'
  • OpenCV is useful when the animation is already part of a computer-vision pipeline.
  • Pick GIF or video based on distribution needs, not just on which file extension is easiest to produce.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.