def __init__(self, to_colorspace, from_colorspace="RGB", alpha=1.0, name=None, deterministic=False, random_state=None): super(ChangeColorspace, self).__init__(name=name, deterministic=deterministic, random_state=random_state) if eu.is_single_number(alpha): self.alpha = Deterministic(alpha) elif eu.is_iterable(alpha): eu.do_assert( len(alpha) == 2, "Expected tuple/list with 2 entries, got %d entries." % (len(alpha), )) self.alpha = Uniform(alpha[0], alpha[1]) elif isinstance(alpha, StochasticParameter): self.alpha = alpha else: raise Exception( "Expected alpha to be int or float or tuple/list of ints/floats or StochasticParameter, got %s." % (type(alpha), )) if eu.is_string(to_colorspace): eu.do_assert(to_colorspace in ChangeColorspace.COLORSPACES) self.to_colorspace = Deterministic(to_colorspace) elif eu.is_iterable(to_colorspace): eu.do_assert( all([eu.is_string(colorspace) for colorspace in to_colorspace])) eu.do_assert( all([(colorspace in ChangeColorspace.COLORSPACES) for colorspace in to_colorspace])) self.to_colorspace = Choice(to_colorspace) elif isinstance(to_colorspace, StochasticParameter): self.to_colorspace = to_colorspace else: raise Exception( "Expected to_colorspace to be string, list of strings or StochasticParameter, got %s." % (type(to_colorspace), )) self.from_colorspace = from_colorspace eu.do_assert(self.from_colorspace in ChangeColorspace.COLORSPACES) eu.do_assert(from_colorspace != ChangeColorspace.GRAY) self.eps = 0.001 # epsilon value to check if alpha is close to 1.0 or 0.0
def __init__(self, sigma=0, name=None, deterministic=False, random_state=None): super(GaussianBlur, self).__init__(name=name, deterministic=deterministic, random_state=random_state) if eu.is_single_number(sigma): self.sigma = Deterministic(sigma) elif eu.is_iterable(sigma): eu.do_assert( len(sigma) == 2, "Expected tuple/list with 2 entries, got %d entries." % (len(sigma), )) self.sigma = Uniform(sigma[0], sigma[1]) elif isinstance(sigma, StochasticParameter): self.sigma = sigma else: raise Exception( "Expected float, int, tuple/list with 2 entries or StochasticParameter. Got %s." % (type(sigma), )) self.eps = 0.001 # epsilon value to estimate whether sigma is above 0
def __init__(self, k=1, name=None, deterministic=False, random_state=None): super(MedianBlur, self).__init__(name=name, deterministic=deterministic, random_state=random_state) if eu.is_single_number(k): eu.do_assert( k % 2 != 0, "Expected k to be odd, got %d. Add or subtract 1." % (int(k), )) self.k = Deterministic(int(k)) elif eu.is_iterable(k): eu.do_assert(len(k) == 2) eu.do_assert(all([eu.is_single_number(ki) for ki in k])) eu.do_assert( k[0] % 2 != 0, "Expected k[0] to be odd, got %d. Add or subtract 1." % (int(k[0]), )) eu.do_assert( k[1] % 2 != 0, "Expected k[1] to be odd, got %d. Add or subtract 1." % (int(k[1]), )) self.k = DiscreteUniform(int(k[0]), int(k[1])) elif isinstance(k, StochasticParameter): self.k = k else: raise Exception( "Expected int, tuple/list with 2 entries or StochasticParameter. Got %s." % (type(k), ))
def __init__(self, to_colorspace, from_colorspace="RGB", children=None, name=None, deterministic=False, random_state=None): super(WithColorspace, self).__init__(name=name, deterministic=deterministic, random_state=random_state) self.to_colorspace = to_colorspace self.from_colorspace = from_colorspace if children is None: self.children = Sequential([], name="%s-then" % (self.name, )) elif eu.is_iterable(children): self.children = Sequential(children, name="%s-then" % (self.name, )) elif isinstance(children, Augmentor): self.children = Sequential([children], name="%s-then" % (self.name, )) else: raise Exception( "Expected None, Augmenter or list/tuple of Augmenter as children, got %s." % (type(children), ))
def handle_continuous_param(param, name, value_range=None, tuple_to_uniform=True, list_to_choice=True): def check_value_range(v): if value_range is None: return True elif isinstance(value_range, tuple): eu.do_assert(len(value_range) == 2) if value_range[0] is None and value_range[1] is None: return True elif value_range[0] is None: eu.do_assert( v <= value_range[1], "Parameter '%s' is outside " "of the expected value range (x <= %.4f)" % (name, value_range[1])) return True elif value_range[1] is None: eu.do_assert( value_range[0] <= v, "Parameter '%s' is outside " "of the expected value range (%.4f <= x)" % (name, value_range[0])) return True else: eu.do_assert( value_range[0] <= v <= value_range[1], "Parameter '%s' is outside of the expected value range (%.4f <= x <= %.4f)" % (name, value_range[0], value_range[1])) return True elif eu.is_callable(value_range): value_range(v) return True else: raise Exception("Unexpected input for value_range, got %s." % (str(value_range), )) if eu.is_single_number(param): check_value_range(param) return Deterministic(param) elif tuple_to_uniform and isinstance(param, tuple): eu.do_assert(len(param) == 2) check_value_range(param[0]) check_value_range(param[1]) return Uniform(param[0], param[1]) elif list_to_choice and eu.is_iterable(param): for param_i in param: check_value_range(param_i) return Choice(param) elif isinstance(param, StochasticParameter): return param else: raise Exception( "Expected number, tuple of two number, list of number or StochasticParameter for %s, got %s." % ( name, type(param), ))
def __init__(self, k=1, name=None, deterministic=False, random_state=None): super(AverageBlur, self).__init__(name=name, deterministic=deterministic, random_state=random_state) self.mode = "single" if eu.is_single_number(k): self.k = Deterministic(int(k)) elif eu.is_iterable(k): eu.do_assert(len(k) == 2) if all([eu.is_single_number(ki) for ki in k]): self.k = DiscreteUniform(int(k[0]), int(k[1])) elif all([isinstance(ki, StochasticParameter) for ki in k]): self.mode = "two" self.k = (k[0], k[1]) else: k_tuple = [None, None] if eu.is_single_number(k[0]): k_tuple[0] = Deterministic(int(k[0])) elif eu.is_iterable(k[0]) and all( [eu.is_single_number(ki) for ki in k[0]]): k_tuple[0] = DiscreteUniform(int(k[0][0]), int(k[0][1])) else: raise Exception( "k[0] expected to be int or tuple of two ints, got %s" % (type(k[0]), )) if eu.is_single_number(k[1]): k_tuple[1] = Deterministic(int(k[1])) elif eu.is_iterable(k[1]) and all( [eu.is_single_number(ki) for ki in k[1]]): k_tuple[1] = DiscreteUniform(int(k[1][0]), int(k[1][1])) else: raise Exception( "k[1] expected to be int or tuple of two ints, got %s" % (type(k[1]), )) self.mode = "two" self.k = k_tuple elif isinstance(k, StochasticParameter): self.k = k else: raise Exception( "Expected int, tuple/list with 2 entries or StochasticParameter. Got %s." % (type(k), ))
def __init__(self, channels=None, children=None, name=None, deterministic=False, random_state=None): super(WithChannels, self).__init__(name=name, deterministic=deterministic, random_state=random_state) if channels is None: self.channels = None elif eu.is_single_integer(channels): self.channels = [channels] elif eu.is_iterable(channels): eu.do_assert( all([eu.is_single_integer(channel) for channel in channels]), "Expected integers as channels, got %s." % ([type(channel) for channel in channels], )) self.channels = channels else: raise Exception( "Expected None, int or list of ints as channels, got %s." % (type(channels), )) if children is None: self.children = Sequential([], name="%s-then" % (self.name, )) elif eu.is_iterable(children): self.children = Sequential(children, name="%s-then" % (self.name, )) elif isinstance(children, Augmentor): self.children = Sequential([children], name="%s-then" % (self.name, )) else: raise Exception( "Expected None, Augmenter or list/tuple of Augmenter as children, got %s." % (type(children), ))
def __init__(self, value=0, per_channel=False, name=None, deterministic=False, random_state=None): super(Add, self).__init__(name=name, deterministic=deterministic, random_state=random_state) if eu.is_single_integer(value): eu.do_assert( -255 <= value <= 255, "Expected value to have range [-255, 255], got value %d." % (value, )) self.value = Deterministic(value) elif eu.is_iterable(value): eu.do_assert( len(value) == 2, "Expected tuple/list with 2 entries, got %d entries." % (len(value), )) self.value = DiscreteUniform(value[0], value[1]) elif isinstance(value, StochasticParameter): self.value = value else: raise Exception( "Expected float or int, tuple/list with 2 entries or StochasticParameter. Got %s." % (type(value), )) if per_channel in [True, False, 0, 1, 0.0, 1.0]: self.per_channel = Deterministic(int(per_channel)) elif eu.is_single_number(per_channel): eu.do_assert( 0 <= per_channel <= 1.0, "Expected bool, or number in range [0, 1.0] for per_channel, got %s." % (type(per_channel), )) self.per_channel = Binomial(per_channel) else: raise Exception( "Expected per_channel to be boolean or number or StochasticParameter" )
def __init__(self, children=None, random_order=False, name=None, deterministic=False, random_state=None): Augmentor.__init__(self, name=name, deterministic=deterministic, random_state=random_state) if children is None: list.__init__(self, []) elif isinstance(children, Augmentor): list.__init__(self, [children]) elif eu.is_iterable(children): list.__init__(self, children) else: raise Exception( "Expected None or Augmenter or list of Augmenter, got %s." % (type(children), )) self.random_order = random_order
def augment_keypoints(self, keypoints_on_images, parents=None, hooks=None): """ Augment image keypoints. This is the corresponding function to `augment_images()`, just for keypoints/landmarks (i.e. coordinates on the image). Usually you will want to call `augment_images()` with a list of images, e.g. `augment_images([A, B, C])` and then `augment_keypoints()` with the corresponding list of keypoints on these images, e.g. `augment_keypoints([Ak, Bk, Ck])`, where `Ak` are the keypoints on image `A`. Make sure to first convert the augmenter(s) to deterministic states before augmenting images and their corresponding keypoints, e.g. by >>> seq = iaa.Fliplr(0.5) >>> seq_det = seq.to_deterministic() >>> imgs_aug = seq_det.augment_images([A, B, C]) >>> kps_aug = seq_det.augment_keypoints([Ak, Bk, Ck]) Otherwise, different random values will be sampled for the image and keypoint augmentations, resulting in different augmentations (e.g. images might be rotated by `30deg` and keypoints by `-10deg`). Also make sure to call `to_deterministic()` again for each new batch, otherwise you would augment all batches in the same way. Parameters ---------- keypoints_on_images : list of ia.KeypointsOnImage The keypoints/landmarks to augment. Expected is a list of ia.KeypointsOnImage objects, each containing the keypoints of a single image. parents : None or list of Augmenter, optional(default=None) Parent augmenters that have previously been called before the call to this function. Usually you can leave this parameter as None. It is set automatically for child augmenters. hooks : None or ia.HooksKeypoints, optional(default=None) HooksKeypoints object to dynamically interfere with the augmentation process. Returns ------- keypoints_on_images_result : list of ia.KeypointsOnImage Augmented keypoints. """ if self.deterministic: state_orig = self.random_state.get_state() if parents is None: parents = [] if hooks is None: hooks = HooksKeyPoints() eu.do_assert(eu.is_iterable(keypoints_on_images)) eu.do_assert( all([ isinstance(kps_on_img, KeyPointsOnImage) for kps_on_img in keypoints_on_images ])) kps_on_imgs_copy = [ kps_on_img.deepcopy() for kps_on_img in keypoints_on_images ] kps_on_imgs_copy = hooks.preprocess(kps_on_imgs_copy, augmentor=self, parents=parents) if hooks.is_activated(kps_on_imgs_copy, augmentor=self, parents=parents, default=self.activated): if len(kps_on_imgs_copy) > 0: kps_on_imgs_result = self._augment_keypoints( kps_on_imgs_copy, random_state=eu.copy_random_state(self.random_state), parents=parents, hooks=hooks) eu.forward_random_state(self.random_state) else: kps_on_imgs_result = kps_on_imgs_copy else: kps_on_imgs_result = kps_on_imgs_copy kps_on_imgs_result = hooks.postprocess(kps_on_imgs_result, augmentor=self, parents=parents) if self.deterministic: self.random_state.set_state(state_orig) return kps_on_imgs_result
def augment_images(self, images, parents=None, hooks=None): """Augment multiple images. Parameters: images: list of image(H,W,C) parents: None or list of Augmentor, optional(default=None) Parent augmentors that have previously beem called before the call to this function. Usually you can leave this parameter as None. It is set automatically for child augmentors. Returns: images_results:ndarray or list, Corresponding augmentor images. """ if self.deterministic: state_orig = self.random_state.get_state() if parents is None: parents = [] if eu.is_np_array(images): input_type = "array" input_added_axis = False eu.do_assert(images.ndim in [3, 4], message="Expected 3d/4d array of form (N, H, W) or (" "N, H, W, C)") images_copy = np.copy(images) if images_copy.ndim == 3 and images_copy.shape[-1] in [1, 3]: warnings.warn( "You provided a numpy array of shape %s as input to augment_images(), " "which was interpreted as (N, H, W). The last dimension however has " "value 1 or 3, which indicates that you provided a single image " "with shape (H, W, C) instead. If that is the case, you should use " "augment_image(image) or augment_images([image]), otherwise " "you will not get the expected augmentations." % (images_copy.shape, )) if images_copy.ndim == 3: images_copy == images_copy[..., np.newaxis] input_added_axis = True elif eu.is_iterable(images): input_type = "list" input_added_axis = [] if len(images) == 0: images_copy = [] else: eu.do_assert(all(image.ndim in [2, 3] for image in images), message="Expected list of images with each image " "having shape(H, W) or (H, W, C)") images_copy = [] input_added_axis = [] for image in images: image_copy = np.copy(image) if image.ndim == 2: image_copy = image_copy[:, :, np.newaxis] input_added_axis.append(True) else: input_added_axis.append(False) images_copy.append(image_copy) else: raise Exception("Expected Images as one numpy array " "or list/tuple of numpy arrays.") if hooks is None: hooks = HooksImages() images_copy = hooks.preprocess(images_copy, augmentor=self, parents=parents) if hooks.is_activated(images_copy, augmentor=self, parents=parents, default=self.activated): if len(images) > 0: images_result = self._augment_images( images=images_copy, random_state=eu.copy_random_state(self.random_state), parents=parents, hooks=hooks) eu.forward_random_state(self.random_state) else: images_result = images_copy else: images_result = images_copy images_result = hooks.postprocess(images_result, augmentor=self, parents=parents) if input_type == "array": if input_added_axis == True: images_result = np.squeeze(images_result, axis=3) if input_type == "list": for i in range(len(images_result)): if input_added_axis[i] == True: images_result[i] = np.squeeze(images_result[i], axis=2) if self.deterministic: self.random_state.set_state(state_orig) return images_result