-
Notifications
You must be signed in to change notification settings - Fork 1
/
gym_wrapper.py
67 lines (52 loc) · 2.78 KB
/
gym_wrapper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from collections import deque
import numpy as np
from gym.spaces import Box
from gym import ObservationWrapper
class FrameStack(ObservationWrapper):
def __init__(self, env, num_frames):
super(FrameStack, self).__init__(env)
self._env = env
self.num_frames = num_frames
self.frames = deque(maxlen=num_frames)
low = np.repeat(self.observation_space['observation'].low[np.newaxis, ...], num_frames, axis=0)
high = np.repeat(self.observation_space['observation'].high[np.newaxis, ...], num_frames, axis=0)
self.observation_space['observation'] = Box(low=low,
high=high,
dtype=self.observation_space['observation'].dtype)
def observation(self):
assert len(self.frames) == self.num_frames, (len(self.frames), self.num_frames)
return np.stack(list(self.frames), axis=0)
def step(self, action):
observation, reward, done, info = self.env.step(action)
self.frames.append(observation['observation'])
return {'observation': self.observation(), 'instruction': observation['instruction']}, reward, done, info
def reset(self, **kwargs):
observation = self.env.reset(**kwargs)
[self.frames.append(observation['observation']) for _ in range(self.num_frames)]
return {'observation': self.observation(), 'instruction': observation['instruction']}
def __getattr__(self, name):
return getattr(self._env, name)
class GrayScaleObservation(ObservationWrapper):
r"""Convert the image observation from RGB to gray scale."""
def __init__(self, env, keep_dim=False):
super(GrayScaleObservation, self).__init__(env)
self._env = env
self.keep_dim = keep_dim
assert (len(env.observation_space['observation'].shape) == 3
and env.observation_space['observation'].shape[-1] == 3)
obs_shape = self.observation_space['observation'].shape[:2]
if self.keep_dim:
self.observation_space['observation'] = Box(low=0,
high=255,
shape=(obs_shape[0], obs_shape[1], 1),
dtype=np.uint8)
else:
self.observation_space['observation'] = Box(low=0, high=255, shape=obs_shape, dtype=np.uint8)
def observation(self, observation):
import cv2
observation['observation'] = cv2.cvtColor(observation['observation'], cv2.COLOR_RGB2GRAY)
if self.keep_dim:
observation['observation'] = np.expand_dims(observation['observation'], -1)
return observation
def __getattr__(self, name):
return getattr(self._env, name)