From 397da753909aeb1c48404ecdb94d99a748c7b8fb Mon Sep 17 00:00:00 2001
From: Christof Kaufmann <christof.kaufmann@hs-bochum.de>
Date: Fri, 31 Mar 2023 11:01:07 +0200
Subject: [PATCH] Add section for making GIFs of gym environments

---
 gym-graphic-output.ipynb | 49 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 49 insertions(+)

diff --git a/gym-graphic-output.ipynb b/gym-graphic-output.ipynb
index cc6567d..3042832 100644
--- a/gym-graphic-output.ipynb
+++ b/gym-graphic-output.ipynb
@@ -42,6 +42,55 @@
     "env.close()"
    ]
   },
+  {
+   "attachments": {},
+   "cell_type": "markdown",
+   "id": "f95a4861",
+   "metadata": {},
+   "source": [
+    "## Making GIFs\n",
+    "\n",
+    "GIFs are fun and easy to make and look at. Here is a way to make them after every episode."
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "4e2994b5",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "import gymnasium as gym\n",
+    "import PIL\n",
+    "import os\n",
+    "\n",
+    "# env = gym.make(\"Pong-v4\", render_mode=\"rgb_array\")\n",
+    "# env.metadata['render_fps'] = 30\n",
+    "\n",
+    "env = gym.make(\"CartPole-v1\", render_mode=\"rgb_array_list\")\n",
+    "\n",
+    "def save_gif(frames, filename='gym.gif'):\n",
+    "    directory = os.path.dirname(filename)\n",
+    "    if not os.path.exists(directory):\n",
+    "        os.makedirs(directory)\n",
+    "\n",
+    "    images = [PIL.Image.fromarray(frame) for frame in frames]\n",
+    "    images[0].save(filename, format='GIF', append_images=images[1:],\n",
+    "                   save_all=True, duration=30, loop=0)\n",
+    " \n",
+    "observation, info = env.reset()\n",
+    "gif_count = 0\n",
+    "for _ in range(1000):\n",
+    "    action = env.action_space.sample()\n",
+    "    observation, reward, terminated, truncated, info = env.step(action)\n",
+    "    if terminated or truncated:\n",
+    "        # save gif for every episode\n",
+    "        save_gif(env.render(), f'gifs/gym-{gif_count:04}.gif')\n",
+    "        gif_count += 1\n",
+    "        observation, info = env.reset()\n",
+    "env.close()"
+   ]
+  },
   {
    "cell_type": "markdown",
    "id": "9f7a4b36-5204-4783-9b6e-55eb3568b591",
-- 
GitLab