{ "cells": [ { "cell_type": "markdown", "id": "06bd7724-6c9d-4517-975f-399918e4b8e3", "metadata": {}, "source": [ "# Generate an animation from a matplotlib figure" ] }, { "cell_type": "code", "execution_count": 1, "id": "324c9a4e-9520-4cfd-98cd-c47f103a69b1", "metadata": {}, "outputs": [], "source": [ "from fractions import Fraction\n", "\n", "import cutcutcodec\n", "import matplotlib.pyplot as plt" ] }, { "cell_type": "markdown", "id": "1f66bc9b-c2ac-46a6-b54d-b74d1be2b776", "metadata": {}, "source": [ "## Define a parametric figure\n", "The animation consists on a simple parametric curve on t, evolving between 0 to 1 second" ] }, { "cell_type": "code", "execution_count": 2, "id": "a1721a1e-3492-45bc-b63c-0500e3f40440", "metadata": {}, "outputs": [], "source": [ "# very simple matplotlib figure\n", "duration = 1.0 # video duration in second\n", "\n", "def parametric_fig(timestamp: Fraction) -> plt.Figure:\n", " \"\"\"Return a filled matplotlib figure, parametrize by the time.\"\"\"\n", " fig = plt.figure(layout=\"constrained\", figsize=(7, 4)) # w, h\n", " fig.supxlabel(\"abscissa\")\n", " fig.supylabel(\"ordinate\")\n", " axe = fig.subplots(squeeze=True)\n", " axe.set_xlim([0, 1])\n", " axe.set_ylim([0, 1])\n", " axe.plot([0, 1], [timestamp, timestamp]) # horizontal line\n", " return fig" ] }, { "cell_type": "markdown", "id": "064ac422-8877-43c7-8abe-134713057e3b", "metadata": {}, "source": [ "## Create the video" ] }, { "cell_type": "code", "execution_count": 3, "id": "3afc8d5b-d866-4486-bde0-9fe013a79474", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Encoding matplotlib.mp4: 100%|█████████████████████████████████████████████████████████████| 1.00s/1.00s [00:18<00:00]\n" ] } ], "source": [ "# write outputfile with low compression (high quality)\n", "(stream,) = cutcutcodec.generation.GeneratorVideoMatplotlib(parametric_fig).out_streams\n", "clipped_stream = stream.apply_video_subclip(0, duration)\n", "streams_settings = [\n", " {\"encodec\": \"libx264\", \"rate\": 30, \"shape\": (480, 720), \"options\": {\"crf\": \"23\", \"preset\": \"ultrafast\"}},\n", "]\n", "cutcutcodec.write([clipped_stream], \"/tmp/matplotlib.mp4\", streams_settings=streams_settings)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.14.3" } }, "nbformat": 4, "nbformat_minor": 5 }