Skip to content

Instantly share code, notes, and snippets.

Last active December 11, 2022 22:44
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
OpenAI Gym Video Recorder
# This works for gym 0.26.2. It might not work on previous versions.
import gym
import cv2
fps = 30
# Create environment
env = gym.make('CartPole-v1', render_mode='rgb_array')
# Get initial observation and frame
obs = env.reset()
frame = env.render()
print("Frame shape:", frame.shape)
size = frame.shape
# Create recorder
out = cv2.VideoWriter('output.mp4', cv2.VideoWriter_fourcc(*'mp4v'), fps, (size[1], size[0]))
# Run episode
obs = env.reset()
for _ in range(500):
frame = env.render()
out.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
action = env.action_space.sample()
obs, reward, terminated, truncated, info = env.step(action)
if terminated:
# Close out the environment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment