Animation Module — Save / Embed Helpers for Any FuncAnimation#
The cleopatra.glyphs.base.animation module exposes cleopatra's animation save / inline-embed
machinery as glyph-independent helpers. They operate on any
matplotlib.animation.FuncAnimation — a sine wave, stock prices, or a map — not only on a
Glyph's internal self.anim:
save_animation(anim, path, fps=2, ...)writes an animation to a file, choosing the writer from the extension:gifandwebpvia Pillow,mov/avi/mp4via FFmpeg. The extension is matched case-insensitively. Quality controls are keyword-only:crf/bitrate(mutually exclusive),codec,preset,pix_fmt, anddpifor the FFmpeg formats;optimizeandloopfor the Pillow (GIF/WebP) formats; plusextra_argspassed straight through to the writer.to_bytes(anim, fmt="gif", fps=2, ...)renders to in-memory bytes in any supported format (temp file cleaned up afterwards);to_gif(...)andto_mp4(...)are thin wrappers for the two common formats.embed_gif(anim, fps=2)returns anIPython.display.Imagefor inline notebook display. IPython is imported lazily (and is bundled with Jupyter, so any notebook already has it); if it is absent,embed_gifraises a clearModuleNotFoundErrorwith apip install ipythonhint — or useto_giffor raw bytes with no IPython dependency.gif_from_video(src, path, fps=12, width=None, max_colors=254, ...)derives a GIF from a video already on disk, without re-rendering. Drawing is usually far more expensive than encoding, so a long clip is best rendered once to MP4 and every other format derived from that file.
The GIF palette#
Both GIF paths — save_animation and gif_from_video — quantise through one palette shared
by every frame, built by build_clip_palette from the colours the whole clip contains and
applied by quantize_to_palette. Both are public, so a downstream package writing its own
frames can reuse the same table rather than re-deriving one. Per-frame
palettes would make constant regions shimmer and let a colour drift between frames; two of
the 256 entries are pinned to pure black and white so single-colour overlays stay crisp.
The palette is chosen for colour coverage, not pixel population, over the set of colours the
clip contains. The distinction matters on exactly the clips this package produces: with a
population-weighted split (median cut) a large textured background claims nearly every palette
slot, and small saturated marks — overlay glyphs, thin paths, labels — collapse to the nearest
muddy neighbour. On the texture-heavy clip in tests/test_animation.py those marks landed 100–180 away (in RGB
distance) from the colours they were drawn in; selecting for coverage reproduces them exactly, and
TestClipPaletteQuality asserts it — so the claim is checked, not remembered.
Because coverage is computed over distinct colours rather than pixels, a mark survives no matter how small it is: a one-pixel orbit path is kept as faithfully as a large glyph. Sampling the frames spatially to build a cheaper palette source would undo that — an interpolating resize blends a one-pixel mark into its background before the quantiser ever sees it.
The trade is a marginally coarser background, because palette entries now go to colours the clip contains rather than to the colours it contains most of, and file size moves either way depending on the clip. Both were measured while developing this and neither is asserted by a test, so treat the direction as reliable and the magnitude as indicative.
quantize_method is the opt-out, on both save_animation and gif_from_video. It takes a key of
QUANTIZE_METHODS — "coverage" (the default), "median", or "octree". Reach for "median" on
a smooth photographic clip with no small marks at stake: it splits the colour cube by how densely
the clip populates it, so the crowded regions a photographic background occupies win the table.
Note none of these see pixel counts — the palette is built from each colour once, so they weight by
distinct colours, not by area:
Render the intermediate with pix_fmt="yuv444p" if a GIF will be derived from it
save_animation writes yuv420p by default — the right choice for playback compatibility,
but it stores colour at half resolution in each direction. That loss happens before the
GIF palette ever runs, and no quantiser can undo it: on the same test clip a yuv420p
intermediate caps the derived GIF at ~50 RGB distance, against ~5 from a yuv444p one.
gif_from_video emits a UserWarning when it is handed a subsampled source.
Memory
gif_from_video decodes the source twice rather than holding it, so the decoded RGB frames are
never all resident. The quantised frames still are — Pillow's GIF encoder accumulates every
frame before writing its first byte. Expect roughly width × height × frames bytes at peak: a
third of what the RGB frames would cost, but still proportional to the clip's length. Use
width to bring a long master down.
SUPPORTED_VIDEO_FORMAT is ["gif", "mov", "avi", "mp4", "webp"]. Glyph.save_animation
delegates to save_animation, so the writer/format logic has a single source of truth.
Downstream packages that build their own FuncAnimation can reuse these helpers instead of
re-rolling temp-file + writer + IPython.display glue.
Usage#
import matplotlib
matplotlib.use("Agg") # any backend; Agg shown for headless rendering
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from cleopatra.glyphs.base.animation import embed_gif, save_animation, to_gif
# Build any FuncAnimation — no Glyph required.
fig, ax = plt.subplots()
(line,) = ax.plot([0, 1], [0, 0])
def update(i):
line.set_ydata([0, i])
return (line,)
anim = FuncAnimation(fig, update, frames=3, blit=True)
save_animation(anim, "wave.gif", fps=3) # write to a file (gif/webp/mov/avi/mp4)
save_animation(anim, "wave.mp4", fps=3, crf=18) # quality-controlled MP4
gif_bytes = to_gif(anim, fps=3) # in-memory GIF bytes
embed_gif(anim, fps=3) # inline in a notebook cell
Note
The output format is taken from the file extension and is matched case-insensitively
(out.GIF works). gif / webp are written with Pillow (no FFmpeg needed). Video
formats (mov/avi/mp4) use FFmpeg: cleopatra depends on imageio-ffmpeg, which
bundles a static FFmpeg binary, so video export works out of the box — a system
FFmpeg on the PATH is used in preference when present. A FileNotFoundError (pointing
at https://ffmpeg.org/) is raised only if no FFmpeg — bundled or system — is available;
an unsupported extension raises a ValueError. embed_gif imports IPython only when
called; if IPython is absent it raises a ModuleNotFoundError with a pip install
ipython hint (use to_gif to avoid IPython).
Full colour range by default
The FFmpeg export (mov/avi/mp4) is encoded full colour range — the pixel format is swapped
for its full-range yuvj* variant (yuv420p becomes yuvj420p) so it maps to the true 0-255
range on every FFmpeg build. The computer-generated, full-range matplotlib figure then keeps its
contrast instead of being squeezed into FFmpeg's limited/broadcast default (16-235), which visibly
washes it out. Pass extra_args=["-color_range", "tv"] to restore the old limited/broadcast-range
behaviour — the most predictable option for the minority of players that ignore the full-range flag.
Module Documentation#
cleopatra.glyphs.base.animation
#
Save/embed helpers for matplotlib animations (glyph-independent).
These helpers operate on any matplotlib.animation.FuncAnimation, not
only on a Glyph's internal self.anim. Saving or embedding an animation
is generic matplotlib machinery — it works on a sine wave, stock prices, or
a map — so it lives here alongside the glyph classes that produce
animations. Downstream packages that build their own FuncAnimation can
reuse cleopatra's writer/format handling instead of re-rolling temp-file +
writer + IPython.display glue.
Glyph.save_animation delegates to save_animation below, so the
writer/format logic has a single source of truth.
build_clip_palette(frames, colors=CLIP_PALETTE_COLORS, method='coverage')
#
Build one colour palette shared by every frame of a clip.
Quantising each frame independently makes constant regions shimmer and lets the same colour drift between frames, so one table is derived from the whole clip and every frame is mapped through it.
The table is chosen for colour coverage (Pillow's MAXCOVERAGE) over the
set of colours the clip contains, gathered by _clip_gamut. Median cut, the
obvious alternative, splits by pixel population instead: on a clip with a
large textured area the background claims nearly every slot and small
saturated marks -- overlay glyphs, thin paths, labels -- collapse to the
nearest muddy neighbour. Because coverage is computed over distinct colours
rather than pixels, a mark survives no matter how few pixels it covers; a
single-pixel mark is kept as faithfully as a large one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frames
|
Iterable[Image]
|
The clip's frames as RGB |
required |
colors
|
int
|
How many palette entries to quantise to. The remaining entries up to 256 are reserved -- pure black and white are pinned so single-colour overlays stay crisp. |
CLIP_PALETTE_COLORS
|
method
|
str
|
Which strategy picks the entries; a key of |
'coverage'
|
Returns:
| Type | Description |
|---|---|
Image
|
PIL.Image.Image: A |
Image
|
ready to pass to |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
- Pure black and white are held back at the top of the table, so a
single-colour overlay drawn on the clip stays crisp:
>>> from PIL import Image >>> from cleopatra.glyphs.base.animation import build_clip_palette >>> frames = [ ... Image.new("RGB", (12, 12), (200, 30, 30)), ... Image.new("RGB", (12, 12), (30, 30, 200)), ... ] >>> entries = build_clip_palette(frames).getpalette() >>> entries[254 * 3 : 254 * 3 + 3] [0, 0, 0] >>> entries[255 * 3 : 255 * 3 + 3] [255, 255, 255] - A smaller budget moves the reserved pair up behind it, so asking for
16 colours still leaves black and white reachable:
>>> from PIL import Image >>> from cleopatra.glyphs.base.animation import build_clip_palette >>> frames = [ ... Image.new("RGB", (12, 12), (200, 30, 30)), ... Image.new("RGB", (12, 12), (30, 30, 200)), ... ] >>> entries = build_clip_palette(frames, colors=16).getpalette() >>> entries[16 * 3 : 16 * 3 + 3] [0, 0, 0] -
The table spans the whole clip, so a colour introduced only in the last frame is still represented:
>>> from PIL import Image >>> from cleopatra.glyphs.base.animation import build_clip_palette >>> frames = [Image.new("RGB", (9, 9), (0, 0, 0))] * 4 >>> frames.append(Image.new("RGB", (9, 9), (255, 0, 255))) >>> entries = build_clip_palette(frames).getpalette() >>> triples = [tuple(entries[i : i + 3]) for i in range(0, 254 * 3, 3)] >>> any(r > 200 and g < 40 and b > 200 for r, g, b in triples) True -
The strategy is selectable. On a clip with few enough colours to fit the budget every strategy keeps them all -- the choice only starts to matter once colours must be discarded:
>>> from PIL import Image >>> from cleopatra.glyphs.base.animation import ( ... QUANTIZE_METHODS, ... build_clip_palette, ... ) >>> sorted(QUANTIZE_METHODS) ['coverage', 'median', 'octree'] >>> frame = Image.new("RGB", (40, 40), (30, 30, 30)) >>> frame.putpixel((0, 0), (255, 0, 255)) # one magenta pixel >>> table = build_clip_palette([frame], colors=4, method="median").getpalette() >>> triples = [tuple(table[i : i + 3]) for i in range(0, 4 * 3, 3)] >>> any(r > 200 and g < 40 and b > 200 for r, g, b in triples) True
See Also
quantize_to_palette: Map the frames onto the palette this returns. gif_from_video: Derives a GIF through this same palette.
Source code in src/cleopatra/glyphs/base/animation.py
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 | |
embed_gif(anim, fps=2)
#
Return an IPython.display.Image of the animation for inline display.
IPython is imported lazily, so importing cleopatra never requires it.
IPython ships with Jupyter, so any notebook already has it; outside a
notebook the returned Image is not renderable anyway — use to_gif
for raw bytes with no IPython dependency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
anim
|
FuncAnimation
|
The animation to embed. |
required |
fps
|
int
|
Frames per second. Default is 2. |
2
|
Returns:
| Type | Description |
|---|---|
Image
|
An |
Image
|
returned as the last expression of a notebook cell. |
Raises:
| Type | Description |
|---|---|
ModuleNotFoundError
|
If IPython is not installed, with a hint to
|
Examples:
- Wrap an animation as an inline image and read back its payload:
>>> import matplotlib >>> matplotlib.use("Agg") >>> import matplotlib.pyplot as plt >>> from matplotlib.animation import FuncAnimation >>> from cleopatra.glyphs.base.animation import embed_gif >>> fig, ax = plt.subplots() >>> (line,) = ax.plot([0, 1], [0, 0]) >>> anim = FuncAnimation(fig, lambda i: (line,), frames=2) >>> img = embed_gif(anim) >>> img.format 'gif' >>> img.data[:6] in (b"GIF87a", b"GIF89a") True >>> plt.close(fig) - Returning the image as a cell's last expression renders it inline;
a custom
fpscontrols playback speed:>>> import matplotlib >>> matplotlib.use("Agg") >>> import matplotlib.pyplot as plt >>> from matplotlib.animation import FuncAnimation >>> from cleopatra.glyphs.base.animation import embed_gif >>> fig, ax = plt.subplots() >>> (line,) = ax.plot([0, 1], [0, 0]) >>> anim = FuncAnimation(fig, lambda i: (line,), frames=2) >>> img = embed_gif(anim, fps=3) >>> len(img.data) > 0 True >>> plt.close(fig)
See Also
to_gif: Produce the underlying GIF bytes without IPython. save_animation: Write the animation to a file path instead.
Source code in src/cleopatra/glyphs/base/animation.py
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 | |
gif_from_video(src, path, *, fps=12, width=None, max_colors=CLIP_PALETTE_COLORS, loop=0, optimize=True, quantize_method='coverage')
#
Derive a GIF from an existing video, without re-rendering the frames.
Drawing is usually far more expensive than encoding -- hours, for a long
scientific animation -- so a clip is best rendered once to a video and every
other format derived from that file. save_animation needs a live
FuncAnimation and would re-render; this reads the frames back off disk
instead.
The frames go through exactly the same clip-wide palette as
save_animation's GIF path (build_clip_palette), so a GIF derived from a
video and one rendered straight from the animation quantise identically.
The source is decoded twice -- once to learn the clip's colours, once to quantise and write -- rather than decoded once into a list. That keeps the decoded RGB frames from ever being held together, which is the larger of the two costs: 150 frames of 720p are 415 MB as RGB against 138 MB as palette indices.
It does not make memory flat in the clip's length. Pillow's GIF encoder
accumulates every frame before writing its first byte, so the quantised
frames are all resident by the end -- measured at a 154 MB peak for those
same 150 frames. A clip whose palette-indexed frames do not fit in memory
will still not encode; use width to bring them down.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
str | PathLike
|
The source video. Any container the bundled FFmpeg can decode. |
required |
path
|
str | PathLike
|
Where to write the GIF. |
required |
fps
|
float
|
Frames per second to sample the source at. Frames are dropped or
duplicated by FFmpeg's |
12
|
width
|
int | None
|
Scale the output to this width in pixels, preserving aspect.
|
None
|
max_colors
|
int
|
Palette size, in |
CLIP_PALETTE_COLORS
|
loop
|
int
|
How many times the GIF loops; |
0
|
optimize
|
bool
|
Run Pillow's optimisation pass. |
True
|
quantize_method
|
str
|
Which strategy picks the shared palette; a key of
|
'coverage'
|
Returns:
| Type | Description |
|---|---|
str
|
The output path as a |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
ValueError
|
If |
Warns:
| Type | Description |
|---|---|
UserWarning
|
If |
Examples:
- Render an animation once to MP4, then derive a GIF from that file:
>>> import os, shutil, tempfile, matplotlib >>> matplotlib.use("Agg") >>> import matplotlib.pyplot as plt >>> from matplotlib.animation import FuncAnimation >>> from cleopatra.glyphs.base.animation import gif_from_video, save_animation >>> tmp = tempfile.mkdtemp() >>> fig, ax = plt.subplots() >>> (line,) = ax.plot([0, 1], [0, 0]) >>> anim = FuncAnimation(fig, lambda i: (line,), frames=4) >>> mp4 = save_animation(anim, os.path.join(tmp, "clip.mp4"), fps=4, ... pix_fmt="yuv444p") >>> gif = gif_from_video(mp4, os.path.join(tmp, "clip.gif"), fps=4) >>> from pathlib import Path >>> Path(gif).read_bytes()[:6] in (b"GIF87a", b"GIF89a") True >>> plt.close(fig) >>> shutil.rmtree(tmp) widthscales the output for a web copy, keeping the aspect ratio of the source and leaving the master untouched:>>> import os, shutil, tempfile, matplotlib >>> matplotlib.use("Agg") >>> import matplotlib.pyplot as plt >>> from PIL import Image >>> from matplotlib.animation import FuncAnimation >>> from cleopatra.glyphs.base.animation import gif_from_video, save_animation >>> tmp = tempfile.mkdtemp() >>> fig, ax = plt.subplots() >>> (line,) = ax.plot([0, 1], [0, 0]) >>> anim = FuncAnimation(fig, lambda i: (line,), frames=4) >>> mp4 = save_animation(anim, os.path.join(tmp, "master.mp4"), fps=4, ... pix_fmt="yuv444p") >>> gif = gif_from_video(mp4, os.path.join(tmp, "web.gif"), fps=4, width=160) >>> with Image.open(gif) as web: ... web.size (160, 120) >>> plt.close(fig) >>> shutil.rmtree(tmp)- A source that does not exist is reported up front, rather than failing later inside the decoder:
See Also
save_animation: Write a live FuncAnimation straight to a file.
build_clip_palette: The shared palette both paths quantise through.
Source code in src/cleopatra/glyphs/base/animation.py
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 | |
quantize_to_palette(frames, palette)
#
Map every frame onto a shared palette, dithering the residual error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frames
|
Iterable[Image]
|
The clip's frames as RGB |
required |
palette
|
Image
|
A |
required |
Returns:
| Name | Type | Description |
|---|---|---|
list |
list[Image]
|
The frames as |
Examples:
- Every frame comes back palette-mode, carrying the same table -- which
is what keeps a constant region byte-stable from frame to frame:
>>> from PIL import Image >>> from cleopatra.glyphs.base.animation import ( ... build_clip_palette, ... quantize_to_palette, ... ) >>> frames = [ ... Image.new("RGB", (8, 8), (255, 0, 0)), ... Image.new("RGB", (8, 8), (0, 0, 255)), ... ] >>> quantised = quantize_to_palette(frames, build_clip_palette(frames)) >>> len(quantised) 2 >>> quantised[0].mode 'P' >>> quantised[0].getpalette() == quantised[1].getpalette() True - A colour the palette holds exactly survives the round trip unchanged:
>>> from PIL import Image >>> from cleopatra.glyphs.base.animation import ( ... build_clip_palette, ... quantize_to_palette, ... ) >>> frames = [Image.new("RGB", (8, 8), (255, 0, 0))] >>> quantised = quantize_to_palette(frames, build_clip_palette(frames)) >>> quantised[0].convert("RGB").getpixel((0, 0)) (255, 0, 0)
See Also
build_clip_palette: Builds the shared palette these frames map onto.
Source code in src/cleopatra/glyphs/base/animation.py
save_animation(anim, path, fps=2, *, crf=None, bitrate=None, codec=None, preset=None, pix_fmt='yuv420p', dpi=None, optimize=True, loop=0, quantize_method='coverage', extra_args=None)
#
Save any FuncAnimation to a file.
The output format is determined by the file extension. GIF and animated
WebP use an optimising Pillow writer; mov/avi/mp4 use FFmpeg. FFmpeg is
located on PATH when present and otherwise falls back to the binary
bundled with imageio-ffmpeg, so video export works with no separate
install. WebP is typically 3-5x smaller than GIF for photographic frames.
Note: when no system FFmpeg is found, the first video export sets
matplotlib's global rcParams["animation.ffmpeg_path"] to the bundled
binary — a process-wide side effect that then applies to any later
matplotlib animation in the same process.
For the FFmpeg formats the frame is automatically padded up to an even
width/height (libx264 rejects odd dimensions) and encoded full colour range:
the pix_fmt is swapped for its full-range yuvj* variant (so yuv420p
becomes yuvj420p), which carries the range in the format itself and so maps
to full 0-255 on every ffmpeg build. matplotlib figures are computer-generated
and full-range (0-255) by construction, so this keeps their full contrast
instead of squeezing it into ffmpeg's limited/broadcast default (16-235),
which visibly washes the video out; pass extra_args=["-color_range", "tv"]
for the old limited-range behaviour, which the few players that ignore the
full-range flag render more predictably. By default no fixed bitrate is
requested (unlike older versions, which forced 1800 kbit/s), so libx264
uses its constant-quality default of roughly CRF 23 — pass crf or
bitrate to trade size against quality. GIF output is written with
Pillow's optimize pass enabled; both GIF and WebP loop forever by
default.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
anim
|
FuncAnimation
|
The animation to save. |
required |
path
|
str | PathLike
|
Output file path, as a |
required |
fps
|
int
|
Frames per second. Default is 2. |
2
|
crf
|
int | None
|
Constant Rate Factor for the ffmpeg formats (lower is higher
quality/larger; ~18-28 is typical). Assumes an x264/x265-family
|
None
|
bitrate
|
int | None
|
Target bitrate in kbit/s for the ffmpeg formats. Mutually
exclusive with |
None
|
codec
|
str | None
|
ffmpeg codec (e.g. |
None
|
preset
|
str | None
|
libx264/libx265 speed/size preset (e.g. |
None
|
pix_fmt
|
str
|
Pixel format for the ffmpeg formats. Defaults to
|
'yuv420p'
|
dpi
|
int | None
|
Resolution in dots per inch. |
None
|
optimize
|
bool
|
GIF only — run Pillow's palette optimisation pass (a no-op
for WebP, whose encoder ignores it). Default |
True
|
loop
|
int
|
GIF/WebP only — number of times to loop; |
0
|
quantize_method
|
str
|
GIF only -- which strategy picks the shared palette; a
key of |
'coverage'
|
extra_args
|
list[str] | None
|
Extra ffmpeg flags. A |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The output path as a |
str
|
convenient for chaining. Note a |
str
|
back as its string form, not the original object. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file format is not supported, if both |
FileNotFoundError
|
If a video format is requested but neither a system FFmpeg nor imageio-ffmpeg's bundled binary can be found. |
Examples:
- Save a tiny animation to a GIF; the call returns the path it wrote:
>>> import os, shutil, tempfile, matplotlib >>> matplotlib.use("Agg") >>> import matplotlib.pyplot as plt >>> from pathlib import Path >>> from matplotlib.animation import FuncAnimation >>> from cleopatra.glyphs.base.animation import save_animation >>> tmp = tempfile.mkdtemp() >>> fig, ax = plt.subplots() >>> (line,) = ax.plot([0, 1], [0, 0]) >>> anim = FuncAnimation(fig, lambda i: (line,), frames=2) >>> path = os.path.join(tmp, "wave.gif") >>> save_animation(anim, path) == path True >>> Path(path).read_bytes()[:6] in (b"GIF87a", b"GIF89a") True >>> plt.close(fig) >>> shutil.rmtree(tmp) - The extension is matched case-insensitively, so
.GIFalso works:>>> import os, shutil, tempfile, matplotlib >>> matplotlib.use("Agg") >>> import matplotlib.pyplot as plt >>> from matplotlib.animation import FuncAnimation >>> from cleopatra.glyphs.base.animation import save_animation >>> tmp = tempfile.mkdtemp() >>> fig, ax = plt.subplots() >>> (line,) = ax.plot([0, 1], [0, 0]) >>> anim = FuncAnimation(fig, lambda i: (line,), frames=2) >>> save_animation(anim, os.path.join(tmp, "WAVE.GIF")).endswith("WAVE.GIF") True >>> plt.close(fig) >>> shutil.rmtree(tmp) - An unsupported extension raises
ValueErrorbefore writing (here the animation is rendered once first, so nothing is left dangling):>>> import os, shutil, tempfile, matplotlib >>> matplotlib.use("Agg") >>> import matplotlib.pyplot as plt >>> from matplotlib.animation import FuncAnimation >>> from cleopatra.glyphs.base.animation import save_animation >>> tmp = tempfile.mkdtemp() >>> fig, ax = plt.subplots() >>> (line,) = ax.plot([0, 1], [0, 0]) >>> anim = FuncAnimation(fig, lambda i: (line,), frames=2) >>> _ = save_animation(anim, os.path.join(tmp, "ok.gif")) >>> save_animation(anim, "movie.webm") # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: ...not supported... >>> plt.close(fig) >>> shutil.rmtree(tmp)
See Also
to_gif: Render an animation to in-memory GIF bytes instead of a file.
embed_gif: Wrap an animation as an IPython.display.Image.
Source code in src/cleopatra/glyphs/base/animation.py
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 | |
to_bytes(anim, fmt='gif', fps=2, **kwargs)
#
Render a FuncAnimation to in-memory bytes in any supported format.
Renders to a temporary file (the writers need a real path) and reads it back, leaving nothing on disk. Handy for embedding in a notebook or serving over HTTP.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
anim
|
FuncAnimation
|
The animation to render. |
required |
fmt
|
str
|
Output format — any member of |
'gif'
|
fps
|
int
|
Frames per second. Default is 2. |
2
|
**kwargs
|
Extra keyword arguments forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
bytes
|
The encoded bytes of the animation in the requested format. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
- Render to GIF bytes and inspect the payload:
>>> import matplotlib >>> matplotlib.use("Agg") >>> import matplotlib.pyplot as plt >>> from matplotlib.animation import FuncAnimation >>> from cleopatra.glyphs.base.animation import to_bytes >>> fig, ax = plt.subplots() >>> (line,) = ax.plot([0, 1], [0, 0]) >>> anim = FuncAnimation(fig, lambda i: (line,), frames=2) >>> data = to_bytes(anim, fmt="gif") >>> data[:6] in (b"GIF87a", b"GIF89a") True >>> plt.close(fig) - Render to animated WebP and confirm the container magic bytes:
>>> import matplotlib >>> matplotlib.use("Agg") >>> import matplotlib.pyplot as plt >>> from matplotlib.animation import FuncAnimation >>> from cleopatra.glyphs.base.animation import to_bytes >>> fig, ax = plt.subplots() >>> (line,) = ax.plot([0, 1], [0, 0]) >>> anim = FuncAnimation(fig, lambda i: (line,), frames=2) >>> data = to_bytes(anim, fmt="webp") >>> data[:4] == b"RIFF" and data[8:12] == b"WEBP" True >>> plt.close(fig) - An unsupported format raises
ValueError:
See Also
to_gif: Convenience wrapper for GIF bytes. to_mp4: Convenience wrapper for MP4 bytes. save_animation: Write an animation directly to a file path.
Source code in src/cleopatra/glyphs/base/animation.py
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 | |
to_gif(anim, fps=2, **kwargs)
#
Render a FuncAnimation to in-memory GIF bytes.
Handy for embedding in a notebook or serving over HTTP without leaving
a file on disk. Thin wrapper around to_bytes with fmt="gif".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
anim
|
FuncAnimation
|
The animation to render. |
required |
fps
|
int
|
Frames per second. Default is 2. |
2
|
**kwargs
|
Extra keyword arguments forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
bytes
|
The GIF-encoded bytes of the animation. |
Examples:
- Render an animation to GIF bytes and inspect the payload:
>>> import matplotlib >>> matplotlib.use("Agg") >>> import matplotlib.pyplot as plt >>> from matplotlib.animation import FuncAnimation >>> from cleopatra.glyphs.base.animation import to_gif >>> fig, ax = plt.subplots() >>> (line,) = ax.plot([0, 1], [0, 0]) >>> anim = FuncAnimation(fig, lambda i: (line,), frames=2) >>> data = to_gif(anim) >>> data[:6] in (b"GIF87a", b"GIF89a") True >>> len(data) > 0 True >>> plt.close(fig) - A higher
fpsstill yields self-contained bytes you can serve over HTTP or write yourself, without leaving a temp file behind:>>> import matplotlib >>> matplotlib.use("Agg") >>> import matplotlib.pyplot as plt >>> from matplotlib.animation import FuncAnimation >>> from cleopatra.glyphs.base.animation import to_gif >>> fig, ax = plt.subplots() >>> (line,) = ax.plot([0, 1], [0, 0]) >>> anim = FuncAnimation(fig, lambda i: (line,), frames=3) >>> payload = to_gif(anim, fps=5) >>> payload.startswith((b"GIF87a", b"GIF89a")) True >>> plt.close(fig)
See Also
to_bytes: Render to bytes in any supported format.
save_animation: Write an animation directly to a file path.
embed_gif: Wrap these bytes as an IPython.display.Image.
Source code in src/cleopatra/glyphs/base/animation.py
to_mp4(anim, fps=2, **kwargs)
#
Render a FuncAnimation to in-memory MP4 (H.264) bytes.
Handy for embedding a compact, universally-playable clip or serving it
over HTTP without leaving a file on disk. Thin wrapper around to_bytes
with fmt="mp4"; the frame is auto-padded to even dimensions and
encoded yuv420p like every other MP4 export.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
anim
|
FuncAnimation
|
The animation to render. |
required |
fps
|
int
|
Frames per second. Default is 2. |
2
|
**kwargs
|
Extra keyword arguments forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
bytes
|
The MP4-encoded bytes of the animation. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If neither a system FFmpeg nor imageio-ffmpeg's bundled binary can be found. |
Examples:
- Render to MP4 bytes and confirm the ISO base-media
ftypbox:>>> import matplotlib >>> matplotlib.use("Agg") >>> import matplotlib.pyplot as plt >>> from matplotlib.animation import FuncAnimation >>> from cleopatra.glyphs.base.animation import to_mp4 >>> fig, ax = plt.subplots() >>> (line,) = ax.plot([0, 1], [0, 0]) >>> anim = FuncAnimation(fig, lambda i: (line,), frames=2) >>> data = to_mp4(anim) >>> data[4:8] == b"ftyp" True >>> plt.close(fig) - Trade size for quality with a CRF and confirm non-empty output:
>>> import matplotlib >>> matplotlib.use("Agg") >>> import matplotlib.pyplot as plt >>> from matplotlib.animation import FuncAnimation >>> from cleopatra.glyphs.base.animation import to_mp4 >>> fig, ax = plt.subplots() >>> (line,) = ax.plot([0, 1], [0, 0]) >>> anim = FuncAnimation(fig, lambda i: (line,), frames=2) >>> data = to_mp4(anim, crf=30, preset="veryfast") >>> len(data) > 0 True >>> plt.close(fig)
See Also
to_bytes: Render to bytes in any supported format. to_gif: Render an animation to in-memory GIF bytes. save_animation: Write an animation directly to a file path.
Source code in src/cleopatra/glyphs/base/animation.py
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 | |