如何在渲染的openAI gym环境中显示episode

5

另外,展示其他信息像奖励或环境输出也是不错的选择,因为将它们打印到 shell 中速度较慢,而创建一个带有 OpenCV 或 PyGame 的屏幕以实时展示它们则需要大量不必要的工作。相比之下,修改已经被打印出来的图像就轻松多了。 - Vasco Cansado Carvalho
1个回答

3
我认为OpenAI中没有直接实现该功能的命令,但是我已经编写了一些代码,你可以根据自己的需要进行适当修改。这是最终结果:

enter image description here

实现这个结果的步骤如下:
  1. 对于每一步,使用 env.render(mode='rgb_array')获取帧。
  2. 将帧(一个numpy数组)转换为PIL图像。
  3. 使用 PIL.ImageDraw 中的工具,在PIL图像上面写入剧集名称(请参阅代码段中的 _label_with_episode_number函数)。
  4. 将打好标签的图像保存到帧列表中。
  5. 使用matplotlib工具渲染帧列表作为GIF。
下面是我编写的代码,用于获得随机代理的行为GIF,并在每个帧的左上角显示剧集编号:
import os
import imageio
import numpy as np
from PIL import Image
import PIL.ImageDraw as ImageDraw
import matplotlib.pyplot as plt    


def _label_with_episode_number(frame, episode_num):
    im = Image.fromarray(frame)

    drawer = ImageDraw.Draw(im)

    if np.mean(im) < 128:
        text_color = (255,255,255)
    else:
        text_color = (0,0,0)
    drawer.text((im.size[0]/20,im.size[1]/18), f'Episode: {episode_num+1}', fill=text_color)

    return im


def save_random_agent_gif(env):
    frames = []
    for i in range(5):
        state = env.reset()        
        for t in range(500):
            action = env.action_space.sample()

            frame = env.render(mode='rgb_array')
            frames.append(_label_with_episode_number(frame, episode_num=i))

            state, _, done, _ = env.step(action)
            if done:
                break

    env.close()

    imageio.mimwrite(os.path.join('./videos/', 'random_agent.gif'), frames, fps=60)


env = gym.make('CartPole-v1')
save_random_agent_gif(env)

您可以在此处找到代码的工作版本:https://github.com/RishabhMalviya/dqn_experiments/blob/master/train_and_visualize.py#L10

@Steven如果您发现问题已经得到解决,请接受答案。 - shinvu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接