def random_crop_random_shape(img, max_shape, min_shape=0): max_shape = get_2dshape(max_shape) min_shape = get_2dshape(min_shape) assert min_shape[0] < img.shape[0] < max_shape[0] and min_shape[ 1] < img.shape[1] < max_shape[1] tar_shape = _rand_2dshape(max_shape, lower_bound=min_shape) return random_crop(img, tar_shape)
def center_crop(img, target_shape): """ center crop """ target_shape = get_2dshape(target_shape) rest = _get_crop2d_rest(img, target_shape) start = rest[0] // 2, rest[1] // 2 return _crop2d(img, start, target_shape)
def _get_crop2d_rest(img, target_shape): source_shape = img.shape[:2] target_shape = get_2dshape(target_shape) rest_shape = source_shape[0] - target_shape[0], source_shape[ 1] - target_shape[1] assert rest_shape[0] >= 0 and rest_shape[1] >= 0 return rest_shape
def center_crop(img, coor, output_size): output_size = get_2dshape(output_size) w, h = img.size th, tw = output_size i = int(round((h - th) / 2.)) j = int(round((w - tw) / 2.)) return crop(img, coor, i, j, th, tw)
def __init__(self, map_size=15, mode=None, **kwargs): kwargs.setdefault('enable_path_checking', False) super().__init__(map_size, **kwargs) mode = mode or 'ALL' assert mode in ('ALL', 'TRAIN', 'VAL') h, w = get_2dshape(map_size) assert h % 4 == 3 and w % 4 == 3 self._lv_obstacles = list( itertools.chain( [(i, (w - 1) // 2) for i in range(h) if i not in ((h - 3) // 4, (h - 1) // 2 + (h + 1) // 4)], [((h - 1) // 2, i) for i in range(w) if i not in ((w - 3) // 4, (w - 1) // 2 + (w + 1) // 4)])) self._lv_starts = [(i, j) for i in range(h) for j in range(w) if (i, j) not in self._lv_obstacles] if mode == 'ALL': self._lv_finals = self._lv_starts.copy() elif mode == 'TRAIN': self._lv_finals = [ (i, j) for i in range(h) for j in range(w) if (i < h // 2 or j < w // 2) and (i, j) not in self._lv_obstacles ] elif mode == 'VAL': self._lv_finals = [(i, j) for i in range(h) for j in range(w) if not (i < h // 2 or j < w // 2) and ( i, j) not in self._lv_obstacles]
def random_size_crop(img, target_shape, area_range, aspect_ratio=None, contiguous_ar=False, *, nr_trial=10): """random size crop used for Facebook ImageNet data augmentation see https://github.com/facebook/fb.resnet.torch/blob/master/datasets/imagenet.lua """ target_shape = get_2dshape(target_shape) h, w = img.shape[:2] area = h * w area_range = area_range if isinstance( area, collections.Iterable) else (area_range, 1) if aspect_ratio is None: assert contiguous_ar == False aspect_ratio = [h / w] for i in range(nr_trial): target_area = random.uniform(area_range[0], area_range[1]) * area target_ar = random.choice(aspect_ratio) nw = int(round((target_area * target_ar)**0.5)) nh = int(round((target_area / target_ar)**0.5)) if random.rand() < 0.5: nh, nw = nw, nh if nh <= h and nw <= w: sx, sy = random.randint(w - nw + 1), random.randint(h - nh + 1) img = img[sy:sy + nh, sx:sx + nw] return imgproc.resize(img, target_shape) scale = min(*target_shape) / min(h, w) return imgproc.center_crop(imgproc.resize_scale(img, scale), target_shape)
def get_morphology_kernel(shape, kernel_size): shape = MorphologyKernelType.from_string(shape) kernel_size = get_2dshape(kernel_size) if shape is MorphologyKernelType.RECT: return torch.ones(kernel_size, dtype=torch.float32) elif shape is MorphologyKernelType.CROSS: kernel = torch.zeros(kernel_size, dtype=torch.float32) kernel[kernel_size[0] // 2, :] = 1 kernel[:, kernel_size[1] // 2] = 1 return kernel elif shape is MorphologyKernelType.ELLIPSE: kernel = torch.zeros(kernel_size, dtype=torch.float32) r, c = kernel_size[0] // 2, kernel_size[1] // 2 inv_r2 = 1 / (r * r) if r != 0 else 0 for i in range(kernel_size[0]): j1, j2 = 0, 0 dy = i - r if abs(dy) <= r: dx = c * sqrt((r * r - dy * dy) * inv_r2) j1 = max(c - dx, 0) j2 = min(c + dx + 1, kernel_size[1]) kernel[i, j1:j2] = 1 return kernel
def __init__(self, kernel_size, border_mode='reflect'): self.kernel_size = get_2dshape(kernel_size) super().__init__(self._gen_kernel(), border_mode=border_mode)
def random_crop_and_resize(img, max_shape, target_shape, min_shape=0): target_shape = get_2dshape(target_shape) cropped = random_crop_random_shape(img, max_shape, min_shape=min_shape) return imgproc.resize(cropped, target_shape)
def leftup_crop(img, target_shape): """ left-up crop """ start = 0, 0 target_shape = get_2dshape(target_shape) return _crop2d(img, start, target_shape)
def __init__(self, size, interpolation=Image.BILINEAR, tg=None): super().__init__(tg) self.size = get_2dshape(size) self.interpolation = interpolation
def __init__(self, size, tg=None): super().__init__(tg) self.size = get_2dshape(size)
def __init__(self, size, padding=0, pad_if_needed=False, tg=None): super().__init__(tg) self.size = get_2dshape(size) self.padding = padding self.pad_if_needed = pad_if_needed
def resize(img, size, interpolation='LINEAR'): size = get_2dshape(size) return backend.resize(img, (size[1], size[0]), interpolation=interpolation)
def resize_wh(img, size_wh, interpolation='LINEAR'): size_wh = get_2dshape(size_wh) return backend.resize(img, size_wh, interpolation=interpolation)
def resize_scale_wh(img, scale_wh, interpolation='LINEAR'): scale_wh = get_2dshape(scale_wh, type=float) return resize_scale(img, (scale_wh[1], scale_wh[0]), interpolation=interpolation)
def resize_scale(img, scale, interpolation='LINEAR'): scale = get_2dshape(scale, type=float) new_size = math.ceil(img.shape[0] * scale[0]), math.ceil(img.shape[1] * scale[1]) return resize(img, new_size, interpolation=interpolation)
def __init__(self, kernel_size): self.kernel_size = get_2dshape(kernel_size)
def __init__(self, map_size=14, visible_size=None, obs_ratio=0.3, enable_path_checking=True, random_action_mapping=None, enable_noaction=False, dense_reward=False, reward_move=None, reward_noaction=0, reward_final=10, reward_error=-2, state_mode='DEFAULT'): """ :param map_size: A single int or a tuple (h, w), representing the map size. :param visible_size: A single int or a tuple (h, w), representing the visible size. The agent will at the center of the visible window, and out-of-border part will be colored by obstacle color. :param obs_ratio: Obstacle ratio (how many obstacles will be in the map). :param enable_path_checking: Enable path computation in map construction. Turn it down only when you are sure about valid maze. :param random_action_mapping: Whether to enable random action mapping. If true, the result of performing every action will be shuffled. _checkingIf a single bool True is provided, we do random shuffle. Otherwise, it should be a list with same length as action space (5 when noaction enabled, 4 otherwise). :param enable_noaction: Whether to enable no-action operation. :param dense_reward: Whether the reward is dense. :param reward_move: Reward for a valid move. For dense reward setting, it should be a positive number. While in sparse reward setting, it is expected to be a non-positive number. :param reward_noaction: Reward for a no-action. :param reward_final: Reward when you arrive at the final point. :param reward_error: Reward when you perform an invalid move. :param state_mode: State mode, either 'DEFAULT' or 'RENDER'. """ super().__init__() self._rng = random.gen_rng() self._map_size = get_2dshape(map_size) self._visible_size = visible_size self._enable_path_checking = enable_path_checking if self._visible_size is not None: self._visible_size = get_2dshape(self._visible_size) self._obs_ratio = obs_ratio if enable_noaction: self._action_space = DiscreteActionSpace(5, action_meanings=['NOOP', 'UP', 'RIGHT', 'DOWN', 'LEFT']) self._action_delta = [(0, 0), (-1, 0), (0, 1), (1, 0), (0, -1)] self._action_mapping = [0, 1, 2, 3, 4] else: self._action_space = DiscreteActionSpace(4, action_meanings=['UP', 'RIGHT', 'DOWN', 'LEFT']) self._action_delta = [(-1, 0), (0, 1), (1, 0), (0, -1)] self._action_mapping = [0, 1, 2, 3] if random_action_mapping is not None: if random_action_mapping is True: self._rng.shuffle(self._action_mapping) else: assert len(self._action_mapping) == len(random_action_mapping) self._action_mapping = random_action_mapping self._enable_noaction = enable_noaction self._dense_reward = dense_reward if reward_move is None: reward_move = -1 if not dense_reward else 1 self._rewards = (reward_move, reward_noaction, reward_final, reward_error) assert state_mode in ('DEFAULT' ,'RENDER') self._state_mode = state_mode