diff --git a/gym-graphic-output.ipynb b/gym-graphic-output.ipynb index cc6567d999eb52c5fbd17b61fba99e8741cf5663..30428320a6ce18a74c9f6b671b662ea0058f2fa0 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",