INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Add a boolean flag to argparse parser.
def boolean_flag(parser, name, default=False, help=None): """Add a boolean flag to argparse parser. Parameters ---------- parser: argparse.Parser parser to add the flag to name: str --<name> will enable the flag, while --no-<name> will disable it default: bool or None de...
Given an a gym environment possibly wrapped multiple times returns a wrapper of class named classname or raises ValueError if no such wrapper was applied
def get_wrapper_by_name(env, classname): """Given an a gym environment possibly wrapped multiple times, returns a wrapper of class named classname or raises ValueError if no such wrapper was applied Parameters ---------- env: gym.Env of gym.Wrapper gym environment classname: str ...
This is just like regular pickle dump except from the fact that failure cases are different:
def relatively_safe_pickle_dump(obj, path, compression=False): """This is just like regular pickle dump, except from the fact that failure cases are different: - It's never possible that we end up with a pickle in corrupted state. - If a there was a different file at the path, that file will re...
Unpickle a possible compressed pickle.
def pickle_load(path, compression=False): """Unpickle a possible compressed pickle. Parameters ---------- path: str path to the output file compression: bool if true assumes that pickle was compressed when created and attempts decompression. Returns ------- obj: object ...
Update the estimate.
def update(self, new_val): """Update the estimate. Parameters ---------- new_val: float new observated value of estimated quantity. """ if self._value is None: self._value = new_val else: self._value = self._gamma * self._value...
Stores provided method args as instance attributes.
def store_args(method): """Stores provided method args as instance attributes. """ argspec = inspect.getfullargspec(method) defaults = {} if argspec.defaults is not None: defaults = dict( zip(argspec.args[-len(argspec.defaults):], argspec.defaults)) if argspec.kwonlydefaults ...
Import a function identified by a string like pkg. module: fn_name.
def import_function(spec): """Import a function identified by a string like "pkg.module:fn_name". """ mod_name, fn_name = spec.split(':') module = importlib.import_module(mod_name) fn = getattr(module, fn_name) return fn
Flattens a variables and their gradients.
def flatten_grads(var_list, grads): """Flattens a variables and their gradients. """ return tf.concat([tf.reshape(grad, [U.numel(v)]) for (v, grad) in zip(var_list, grads)], 0)
Creates a simple neural network
def nn(input, layers_sizes, reuse=None, flatten=False, name=""): """Creates a simple neural network """ for i, size in enumerate(layers_sizes): activation = tf.nn.relu if i < len(layers_sizes) - 1 else None input = tf.layers.dense(inputs=input, units=size, ...
Re - launches the current script with workers Returns parent for original parent child for MPI children
def mpi_fork(n, extra_mpi_args=[]): """Re-launches the current script with workers Returns "parent" for original parent, "child" for MPI children """ if n <= 1: return "child" if os.getenv("IN_MPI") is None: env = os.environ.copy() env.update( MKL_NUM_THREADS="1",...
Converts an episode to have the batch dimension in the major ( first ) dimension.
def convert_episode_to_batch_major(episode): """Converts an episode to have the batch dimension in the major (first) dimension. """ episode_batch = {} for key in episode.keys(): val = np.array(episode[key]).copy() # make inputs batch-major instead of time-major episode_batch[...
Reshapes a tensor ( source ) to have the correct shape and dtype of the target before broadcasting it with MPI.
def reshape_for_broadcasting(source, target): """Reshapes a tensor (source) to have the correct shape and dtype of the target before broadcasting it with MPI. """ dim = len(target.get_shape()) shape = ([1] * (dim - 1)) + [-1] return tf.reshape(tf.cast(source, target.dtype), shape)
Compute target value using TD ( lambda ) estimator and advantage with GAE ( lambda )
def add_vtarg_and_adv(seg, gamma, lam): """ Compute target value using TD(lambda) estimator, and advantage with GAE(lambda) """ new = np.append(seg["new"], 0) # last element is only used for last vtarg, but we already zeroed it if last new = 1 vpred = np.append(seg["vpred"], seg["nextvpred"]) T ...
Switches between two operations depending on a scalar value ( int or bool ). Note that both then_expression and else_expression should be symbolic tensors of the * same shape *.
def switch(condition, then_expression, else_expression): """Switches between two operations depending on a scalar value (int or bool). Note that both `then_expression` and `else_expression` should be symbolic tensors of the *same shape*. # Arguments condition: scalar tensor. then_expres...
Reference: https:// en. wikipedia. org/ wiki/ Huber_loss
def huber_loss(x, delta=1.0): """Reference: https://en.wikipedia.org/wiki/Huber_loss""" return tf.where( tf.abs(x) < delta, tf.square(x) * 0.5, delta * (tf.abs(x) - 0.5 * delta) )
Get default session or create one with a given config
def get_session(config=None): """Get default session or create one with a given config""" sess = tf.get_default_session() if sess is None: sess = make_session(config=config, make_default=True) return sess
Returns a session that will use <num_cpu > CPU s only
def make_session(config=None, num_cpu=None, make_default=False, graph=None): """Returns a session that will use <num_cpu> CPU's only""" if num_cpu is None: num_cpu = int(os.getenv('RCALL_NUM_CPU', multiprocessing.cpu_count())) if config is None: config = tf.ConfigProto( allow_sof...
Initialize all the uninitialized variables in the global scope.
def initialize(): """Initialize all the uninitialized variables in the global scope.""" new_variables = set(tf.global_variables()) - ALREADY_INITIALIZED get_session().run(tf.variables_initializer(new_variables)) ALREADY_INITIALIZED.update(new_variables)
Just like Theano function. Take a bunch of tensorflow placeholders and expressions computed based on those placeholders and produces f ( inputs ) - > outputs. Function f takes values to be fed to the input s placeholders and produces the values of the expressions in outputs.
def function(inputs, outputs, updates=None, givens=None): """Just like Theano function. Take a bunch of tensorflow placeholders and expressions computed based on those placeholders and produces f(inputs) -> outputs. Function f takes values to be fed to the input's placeholders and produces the values of the...
adjust shape of the data to the shape of the placeholder if possible. If shape is incompatible AssertionError is thrown
def adjust_shape(placeholder, data): ''' adjust shape of the data to the shape of the placeholder if possible. If shape is incompatible, AssertionError is thrown Parameters: placeholder tensorflow input placeholder data input data to be (potentially) reshaped to be fed i...
check if two shapes are compatible ( i. e. differ only by dimensions of size 1 or by the batch dimension )
def _check_shape(placeholder_shape, data_shape): ''' check if two shapes are compatible (i.e. differ only by dimensions of size 1, or by the batch dimension)''' return True squeezed_placeholder_shape = _squeeze_shape(placeholder_shape) squeezed_data_shape = _squeeze_shape(data_shape) for i, s_data...
Usage:
def profile(n): """ Usage: @profile("my_func") def my_func(): code """ def decorator_with_name(func): def func_wrapper(*args, **kwargs): with profile_kv(n): return func(*args, **kwargs) return func_wrapper return decorator_with_name
Configure environment for DeepMind - style Atari.
def wrap_deepmind(env, episode_life=True, clip_rewards=True, frame_stack=False, scale=False): """Configure environment for DeepMind-style Atari. """ if episode_life: env = EpisodicLifeEnv(env) if 'FIRE' in env.unwrapped.get_action_meanings(): env = FireResetEnv(env) env = WarpFrame(e...
Reset only when lives are exhausted. This way all states are still reachable even though lives are episodic and the learner need not know about any of this behind - the - scenes.
def reset(self, **kwargs): """Reset only when lives are exhausted. This way all states are still reachable even though lives are episodic, and the learner need not know about any of this behind-the-scenes. """ if self.was_real_done: obs = self.env.reset(**kwargs) ...
Send the root node s parameters to every worker. Arguments: sess: the TensorFlow session. variables: all parameter variables including optimizer s
def sync_from_root(sess, variables, comm=None): """ Send the root node's parameters to every worker. Arguments: sess: the TensorFlow session. variables: all parameter variables including optimizer's """ if comm is None: comm = MPI.COMM_WORLD import tensorflow as tf values = comm....
Count the GPUs on this machine.
def gpu_count(): """ Count the GPUs on this machine. """ if shutil.which('nvidia-smi') is None: return 0 output = subprocess.check_output(['nvidia-smi', '--query-gpu=gpu_name', '--format=csv']) return max(0, len(output.split(b'\n')) - 2)
Set CUDA_VISIBLE_DEVICES to MPI rank if not already set
def setup_mpi_gpus(): """ Set CUDA_VISIBLE_DEVICES to MPI rank if not already set """ if 'CUDA_VISIBLE_DEVICES' not in os.environ: if sys.platform == 'darwin': # This Assumes if you're on OSX you're just ids = [] # doing a smoke test and don't want GPUs else: ...
Returns the rank of each process on its machine The processes on a given machine will be assigned ranks 0 1 2... N - 1 where N is the number of processes on this machine.
def get_local_rank_size(comm): """ Returns the rank of each process on its machine The processes on a given machine will be assigned ranks 0, 1, 2, ..., N-1, where N is the number of processes on this machine. Useful if you want to assign one gpu per machine """ this_node = platform...
Copies the file from rank 0 to all other ranks Puts it in the same place on all machines
def share_file(comm, path): """ Copies the file from rank 0 to all other ranks Puts it in the same place on all machines """ localrank, _ = get_local_rank_size(comm) if comm.Get_rank() == 0: with open(path, 'rb') as fh: data = fh.read() comm.bcast(data) else: ...
Perform a reduction operation over dicts
def dict_gather(comm, d, op='mean', assert_all_have_data=True): """ Perform a reduction operation over dicts """ if comm is None: return d alldicts = comm.allgather(d) size = comm.size k2li = defaultdict(list) for d in alldicts: for (k,v) in d.items(): k2li[k].append(...
Perform a weighted average over dicts that are each on a different node Input: local_name2valcount: dict mapping key - > ( value count ) Returns: key - > mean
def mpi_weighted_mean(comm, local_name2valcount): """ Perform a weighted average over dicts that are each on a different node Input: local_name2valcount: dict mapping key -> (value, count) Returns: key -> mean """ all_name2valcount = comm.gather(local_name2valcount) if comm.rank == 0: ...
learn a policy function with TRPO algorithm
def learn(*, network, env, total_timesteps, timesteps_per_batch=1024, # what to train on max_kl=0.001, cg_iters=10, gamma=0.99, lam=1.0, # advantage estimation seed=None, ent_coef=0.0, cg_damping=1e-2, vf_stepsize=3e-4, ...
computes discounted sums along 0th dimension of x.
def discount(x, gamma): """ computes discounted sums along 0th dimension of x. inputs ------ x: ndarray gamma: float outputs ------- y: ndarray with same shape as x, satisfying y[t] = x[t] + gamma*x[t+1] + gamma^2*x[t+2] + ... + gamma^k x[t+k], where k = le...
Computes fraction of variance that ypred explains about y. Returns 1 - Var [ y - ypred ]/ Var [ y ]
def explained_variance(ypred,y): """ Computes fraction of variance that ypred explains about y. Returns 1 - Var[y-ypred] / Var[y] interpretation: ev=0 => might as well have predicted zero ev=1 => perfect prediction ev<0 => worse than just predicting zero """ asser...
X: 2d array of floats time x features New: 2d array of bools indicating when a new episode has started
def discount_with_boundaries(X, New, gamma): """ X: 2d array of floats, time x features New: 2d array of bools, indicating when a new episode has started """ Y = np.zeros_like(X) T = X.shape[0] Y[T-1] = X[T-1] for t in range(T-2, -1, -1): Y[t] = X[t] + gamma * Y[t+1] * (1 - New[t...
Sample a batch of experiences.
def sample(self, batch_size): """Sample a batch of experiences. Parameters ---------- batch_size: int How many transitions to sample. Returns ------- obs_batch: np.array batch of observations act_batch: np.array batch ...
See ReplayBuffer. store_effect
def add(self, *args, **kwargs): """See ReplayBuffer.store_effect""" idx = self._next_idx super().add(*args, **kwargs) self._it_sum[idx] = self._max_priority ** self._alpha self._it_min[idx] = self._max_priority ** self._alpha
Sample a batch of experiences.
def sample(self, batch_size, beta): """Sample a batch of experiences. compared to ReplayBuffer.sample it also returns importance weights and idxes of sampled experiences. Parameters ---------- batch_size: int How many transitions to sample. ...
Update priorities of sampled transitions.
def update_priorities(self, idxes, priorities): """Update priorities of sampled transitions. sets priority of transition at index idxes[i] in buffer to priorities[i]. Parameters ---------- idxes: [int] List of idxes of sampled transitions priorities:...
Configure environment for retro games using config similar to DeepMind - style Atari in wrap_deepmind
def wrap_deepmind_retro(env, scale=True, frame_stack=4): """ Configure environment for retro games, using config similar to DeepMind-style Atari in wrap_deepmind """ env = WarpFrame(env) env = ClipRewardEnv(env) if frame_stack > 1: env = FrameStack(env, frame_stack) if scale: ...
Get variables inside a scope The scope can be specified as a string Parameters ---------- scope: str or VariableScope scope in which the variables reside. trainable_only: bool whether or not to return only the variables that were marked as trainable. Returns ------- vars: [ tf. Variable ] list of variables in scope.
def scope_vars(scope, trainable_only=False): """ Get variables inside a scope The scope can be specified as a string Parameters ---------- scope: str or VariableScope scope in which the variables reside. trainable_only: bool whether or not to return only the variables that we...
Creates the act function:
def build_act(make_obs_ph, q_func, num_actions, scope="deepq", reuse=None): """Creates the act function: Parameters ---------- make_obs_ph: str -> tf.placeholder or TfInput a function that take a name and creates a placeholder of input with that name q_func: (tf.Variable, int, str, bool) ->...
Creates the act function with support for parameter space noise exploration ( https:// arxiv. org/ abs/ 1706. 01905 ):
def build_act_with_param_noise(make_obs_ph, q_func, num_actions, scope="deepq", reuse=None, param_noise_filter_func=None): """Creates the act function with support for parameter space noise exploration (https://arxiv.org/abs/1706.01905): Parameters ---------- make_obs_ph: str -> tf.placeholder or TfInp...
Creates the train function:
def build_train(make_obs_ph, q_func, num_actions, optimizer, grad_norm_clipping=None, gamma=1.0, double_q=True, scope="deepq", reuse=None, param_noise=False, param_noise_filter_func=None): """Creates the train function: Parameters ---------- make_obs_ph: str -> tf.placeholder or TfInput a f...
options = tf. RunOptions ( trace_level = tf. RunOptions. FULL_TRACE ) #pylint: disable = E1101 run_metadata = tf. RunMetadata () profile_opts = dict ( options = options run_metadata = run_metadata )
def profile_tf_runningmeanstd(): import time from baselines.common import tf_util tf_util.get_session( config=tf.ConfigProto( inter_op_parallelism_threads=1, intra_op_parallelism_threads=1, allow_soft_placement=True )) x = np.random.random((376,)) n_trials = 10000 ...
Creates a sample function that can be used for HER experience replay.
def make_sample_her_transitions(replay_strategy, replay_k, reward_fun): """Creates a sample function that can be used for HER experience replay. Args: replay_strategy (in ['future', 'none']): the HER replay strategy; if set to 'none', regular DDPG experience replay is used replay_k ...
This model takes as input an observation and returns values of all actions.
def model(inpt, num_actions, scope, reuse=False): """This model takes as input an observation and returns values of all actions.""" with tf.variable_scope(scope, reuse=reuse): out = inpt out = layers.fully_connected(out, num_outputs=64, activation_fn=tf.nn.tanh) out = layers.fully_connec...
Returns a dict { key: array ( batch_size x shapes [ key ] ) }
def sample(self, batch_size): """Returns a dict {key: array(batch_size x shapes[key])} """ buffers = {} with self.lock: assert self.current_size > 0 for key in self.buffers.keys(): buffers[key] = self.buffers[key][:self.current_size] buff...
episode_batch: array ( batch_size x ( T or T + 1 ) x dim_key )
def store_episode(self, episode_batch): """episode_batch: array(batch_size x (T or T+1) x dim_key) """ batch_sizes = [len(episode_batch[key]) for key in episode_batch.keys()] assert np.all(np.array(batch_sizes) == batch_sizes[0]) batch_size = batch_sizes[0] with self.loc...
episode_batch: array of batch_size x ( T or T + 1 ) x dim_key o is of size T + 1 others are of size T
def store_episode(self, episode_batch, update_stats=True): """ episode_batch: array of batch_size x (T or T+1) x dim_key 'o' is of size T+1, others are of size T """ self.buffer.store_episode(episode_batch) if update_stats: # add transitions t...
convert a list of = - spaced command - line arguments to a dictionary evaluating python objects when possible
def parse_cmdline_kwargs(args): ''' convert a list of '='-spaced command-line arguments to a dictionary, evaluating python objects when possible ''' def parse(v): assert isinstance(v, str) try: return eval(v) except (NameError, SyntaxError): return v ...
Only creates a new environment from the provided function if one has not yet already been created. This is useful here because we need to infer certain properties of the env e. g. its observation and action spaces without any intend of actually using it.
def cached_make_env(make_env): """ Only creates a new environment from the provided function if one has not yet already been created. This is useful here because we need to infer certain properties of the env, e.g. its observation and action spaces, without any intend of actually using it. """ i...
Estimate the geometric median of points in 2D.
def compute_geometric_median(X, eps=1e-5): """ Estimate the geometric median of points in 2D. Code from https://stackoverflow.com/a/30305181 Parameters ---------- X : (N,2) ndarray Points in 2D. Second axis must be given in xy-form. eps : float, optional Distance threshold...
Project the keypoint onto a new position on a new image.
def project(self, from_shape, to_shape): """ Project the keypoint onto a new position on a new image. E.g. if the keypoint is on its original image at x=(10 of 100 pixels) and y=(20 of 100 pixels) and is projected onto a new image with size (width=200, height=200), its new posit...
Move the keypoint around on an image.
def shift(self, x=0, y=0): """ Move the keypoint around on an image. Parameters ---------- x : number, optional Move by this value on the x axis. y : number, optional Move by this value on the y axis. Returns ------- imga...
Draw the keypoint onto a given image.
def draw_on_image(self, image, color=(0, 255, 0), alpha=1.0, size=3, copy=True, raise_if_out_of_image=False): """ Draw the keypoint onto a given image. The keypoint is drawn as a square. Parameters ---------- image : (H,W,3) ndarray The...
Generate nearby points to this keypoint based on manhattan distance.
def generate_similar_points_manhattan(self, nb_steps, step_size, return_array=False): """ Generate nearby points to this keypoint based on manhattan distance. To generate the first neighbouring points, a distance of S (step size) is moved from the center point (this keypoint) to the top...
Create a shallow copy of the Keypoint object.
def copy(self, x=None, y=None): """ Create a shallow copy of the Keypoint object. Parameters ---------- x : None or number, optional Coordinate of the keypoint on the x axis. If ``None``, the instance's value will be copied. y : None or number, o...
Create a deep copy of the Keypoint object.
def deepcopy(self, x=None, y=None): """ Create a deep copy of the Keypoint object. Parameters ---------- x : None or number, optional Coordinate of the keypoint on the x axis. If ``None``, the instance's value will be copied. y : None or number, ...
Project keypoints from one image to a new one.
def on(self, image): """ Project keypoints from one image to a new one. Parameters ---------- image : ndarray or tuple of int New image onto which the keypoints are to be projected. May also simply be that new image's shape tuple. Returns ...
Draw all keypoints onto a given image.
def draw_on_image(self, image, color=(0, 255, 0), alpha=1.0, size=3, copy=True, raise_if_out_of_image=False): """ Draw all keypoints onto a given image. Each keypoint is marked by a square of a chosen color and size. Parameters ---------- image : (...
Move the keypoints around on an image.
def shift(self, x=0, y=0): """ Move the keypoints around on an image. Parameters ---------- x : number, optional Move each keypoint by this value on the x axis. y : number, optional Move each keypoint by this value on the y axis. Returns...
Convert keypoint coordinates to ( N 2 ) array.
def to_xy_array(self): """ Convert keypoint coordinates to ``(N,2)`` array. Returns ------- (N, 2) ndarray Array containing the coordinates of all keypoints. Shape is ``(N,2)`` with coordinates in xy-form. """ result = np.zeros((len(self....
Convert an array ( N 2 ) with a given image shape to a KeypointsOnImage object.
def from_xy_array(cls, xy, shape): """ Convert an array (N,2) with a given image shape to a KeypointsOnImage object. Parameters ---------- xy : (N, 2) ndarray Coordinates of ``N`` keypoints on the original image, given as ``(N,2)`` array of xy-coordinates...
Draws a new black image of shape ( H W N ) in which all keypoint coordinates are set to 255. ( H = shape height W = shape width N = number of keypoints )
def to_keypoint_image(self, size=1): """ Draws a new black image of shape ``(H,W,N)`` in which all keypoint coordinates are set to 255. (H=shape height, W=shape width, N=number of keypoints) This function can be used as a helper when augmenting keypoints with a method that only supports...
Converts an image generated by to_keypoint_image () back to a KeypointsOnImage object.
def from_keypoint_image(image, if_not_found_coords={"x": -1, "y": -1}, threshold=1, nb_channels=None): # pylint: disable=locally-disabled, dangerous-default-value, line-too-long """ Converts an image generated by ``to_keypoint_image()`` back to a KeypointsOnImage object. Parameters ----...
Generates a ( H W K ) output containing K distance maps for K keypoints.
def to_distance_maps(self, inverted=False): """ Generates a ``(H,W,K)`` output containing ``K`` distance maps for ``K`` keypoints. The k-th distance map contains at every location ``(y, x)`` the euclidean distance to the k-th keypoint. This function can be used as a helper when augment...
Converts maps generated by to_distance_maps () back to a KeypointsOnImage object.
def from_distance_maps(distance_maps, inverted=False, if_not_found_coords={"x": -1, "y": -1}, threshold=None, # pylint: disable=locally-disabled, dangerous-default-value, line-too-long nb_channels=None): """ Converts maps generated by ``to_distance_maps()`` back to a Keypoints...
Create a shallow copy of the KeypointsOnImage object.
def copy(self, keypoints=None, shape=None): """ Create a shallow copy of the KeypointsOnImage object. Parameters ---------- keypoints : None or list of imgaug.Keypoint, optional List of keypoints on the image. If ``None``, the instance's keypoints will be...
Create a deep copy of the KeypointsOnImage object.
def deepcopy(self, keypoints=None, shape=None): """ Create a deep copy of the KeypointsOnImage object. Parameters ---------- keypoints : None or list of imgaug.Keypoint, optional List of keypoints on the image. If ``None``, the instance's keypoints will b...
Estimate whether the bounding box contains a point.
def contains(self, other): """ Estimate whether the bounding box contains a point. Parameters ---------- other : tuple of number or imgaug.Keypoint Point to check for. Returns ------- bool True if the point is contained in the bou...
Project the bounding box onto a differently shaped image.
def project(self, from_shape, to_shape): """ Project the bounding box onto a differently shaped image. E.g. if the bounding box is on its original image at x1=(10 of 100 pixels) and y1=(20 of 100 pixels) and is projected onto a new image with size (width=200, height=200), its ne...
Extend the size of the bounding box along its sides.
def extend(self, all_sides=0, top=0, right=0, bottom=0, left=0): """ Extend the size of the bounding box along its sides. Parameters ---------- all_sides : number, optional Value by which to extend the bounding box size along all sides. top : number, optiona...
Compute the intersection bounding box of this bounding box and another one.
def intersection(self, other, default=None): """ Compute the intersection bounding box of this bounding box and another one. Note that in extreme cases, the intersection can be a single point, meaning that the intersection bounding box will exist, but then also has a height and width of...
Compute the union bounding box of this bounding box and another one.
def union(self, other): """ Compute the union bounding box of this bounding box and another one. This is equivalent to drawing a bounding box around all corners points of both bounding boxes. Parameters ---------- other : imgaug.BoundingBox Other bou...
Compute the IoU of this bounding box with another one.
def iou(self, other): """ Compute the IoU of this bounding box with another one. IoU is the intersection over union, defined as:: ``area(intersection(A, B)) / area(union(A, B))`` ``= area(intersection(A, B)) / (area(A) + area(B) - area(intersection(A, B)))`` Pa...
Estimate whether the bounding box is fully inside the image area.
def is_fully_within_image(self, image): """ Estimate whether the bounding box is fully inside the image area. Parameters ---------- image : (H,W,...) ndarray or tuple of int Image dimensions to use. If an ndarray, its shape will be used. If a ...
Estimate whether the bounding box is at least partially inside the image area.
def is_partly_within_image(self, image): """ Estimate whether the bounding box is at least partially inside the image area. Parameters ---------- image : (H,W,...) ndarray or tuple of int Image dimensions to use. If an ndarray, its shape will be used. ...
Estimate whether the bounding box is partially or fully outside of the image area.
def is_out_of_image(self, image, fully=True, partly=False): """ Estimate whether the bounding box is partially or fully outside of the image area. Parameters ---------- image : (H,W,...) ndarray or tuple of int Image dimensions to use. If an ndarray, its shape will b...
Clip off all parts of the bounding box that are outside of the image.
def clip_out_of_image(self, image): """ Clip off all parts of the bounding box that are outside of the image. Parameters ---------- image : (H,W,...) ndarray or tuple of int Image dimensions to use for the clipping of the bounding box. If an ndarray, its ...
Shift the bounding box from one or more image sides i. e. move it on the x/ y - axis.
def shift(self, top=None, right=None, bottom=None, left=None): """ Shift the bounding box from one or more image sides, i.e. move it on the x/y-axis. Parameters ---------- top : None or int, optional Amount of pixels by which to shift the bounding box from the top. ...
Draw the bounding box on an image.
def draw_on_image(self, image, color=(0, 255, 0), alpha=1.0, size=1, copy=True, raise_if_out_of_image=False, thickness=None): """ Draw the bounding box on an image. Parameters ---------- image : (H,W,C) ndarray(uint8) The image onto which to dra...
Extract the image pixels within the bounding box.
def extract_from_image(self, image, pad=True, pad_max=None, prevent_zero_size=True): """ Extract the image pixels within the bounding box. This function will zero-pad the image if the bounding box is partially/fully outside of the image. Parameters ...
Convert the corners of the bounding box to keypoints ( clockwise starting at top left ).
def to_keypoints(self): """ Convert the corners of the bounding box to keypoints (clockwise, starting at top left). Returns ------- list of imgaug.Keypoint Corners of the bounding box as keypoints. """ # TODO get rid of this deferred import f...
Create a shallow copy of the BoundingBox object.
def copy(self, x1=None, y1=None, x2=None, y2=None, label=None): """ Create a shallow copy of the BoundingBox object. Parameters ---------- x1 : None or number If not None, then the x1 coordinate of the copied object will be set to this value. y1 : None or nu...
Create a deep copy of the BoundingBox object.
def deepcopy(self, x1=None, y1=None, x2=None, y2=None, label=None): """ Create a deep copy of the BoundingBox object. Parameters ---------- x1 : None or number If not None, then the x1 coordinate of the copied object will be set to this value. y1 : None or n...
Project bounding boxes from one image to a new one.
def on(self, image): """ Project bounding boxes from one image to a new one. Parameters ---------- image : ndarray or tuple of int New image onto which the bounding boxes are to be projected. May also simply be that new image's shape tuple. Retur...
Convert an ( N 4 ) ndarray to a BoundingBoxesOnImage object.
def from_xyxy_array(cls, xyxy, shape): """ Convert an (N,4) ndarray to a BoundingBoxesOnImage object. This is the inverse of :func:`imgaug.BoundingBoxesOnImage.to_xyxy_array`. Parameters ---------- xyxy : (N,4) ndarray Array containing the corner coordinates...
Convert the BoundingBoxesOnImage object to an ( N 4 ) ndarray.
def to_xyxy_array(self, dtype=np.float32): """ Convert the BoundingBoxesOnImage object to an (N,4) ndarray. This is the inverse of :func:`imgaug.BoundingBoxesOnImage.from_xyxy_array`. Parameters ---------- dtype : numpy.dtype, optional Desired output datatyp...
Draw all bounding boxes onto a given image.
def draw_on_image(self, image, color=(0, 255, 0), alpha=1.0, size=1, copy=True, raise_if_out_of_image=False, thickness=None): """ Draw all bounding boxes onto a given image. Parameters ---------- image : (H,W,3) ndarray The image onto which to d...
Remove all bounding boxes that are fully or partially outside of the image.
def remove_out_of_image(self, fully=True, partly=False): """ Remove all bounding boxes that are fully or partially outside of the image. Parameters ---------- fully : bool, optional Whether to remove bounding boxes that are fully outside of the image. partly...
Clip off all parts from all bounding boxes that are outside of the image.
def clip_out_of_image(self): """ Clip off all parts from all bounding boxes that are outside of the image. Returns ------- imgaug.BoundingBoxesOnImage Bounding boxes, clipped to fall within the image dimensions. """ bbs_cut = [bb.clip_out_of_image(se...
Shift all bounding boxes from one or more image sides i. e. move them on the x/ y - axis.
def shift(self, top=None, right=None, bottom=None, left=None): """ Shift all bounding boxes from one or more image sides, i.e. move them on the x/y-axis. Parameters ---------- top : None or int, optional Amount of pixels by which to shift all bounding boxes from the ...
Create a deep copy of the BoundingBoxesOnImage object.
def deepcopy(self): """ Create a deep copy of the BoundingBoxesOnImage object. Returns ------- imgaug.BoundingBoxesOnImage Deep copy. """ # Manual copy is far faster than deepcopy for BoundingBoxesOnImage, # so use manual copy here too ...
Augmenter that embosses images and overlays the result with the original image.
def Emboss(alpha=0, strength=1, name=None, deterministic=False, random_state=None): """ Augmenter that embosses images and overlays the result with the original image. The embossed version pronounces highlights and shadows, letting the image look as if it was recreated on a metal plate ("embossed")...
Augmenter that detects all edges in images marks them in a black and white image and then overlays the result with the original image.
def EdgeDetect(alpha=0, name=None, deterministic=False, random_state=None): """ Augmenter that detects all edges in images, marks them in a black and white image and then overlays the result with the original image. dtype support:: See ``imgaug.augmenters.convolutional.Convolve``. Par...
Augmenter that detects edges that have certain directions and marks them in a black and white image and then overlays the result with the original image.
def DirectedEdgeDetect(alpha=0, direction=(0.0, 1.0), name=None, deterministic=False, random_state=None): """ Augmenter that detects edges that have certain directions and marks them in a black and white image and then overlays the result with the original image. dtype support:: See ``imga...
Normalize a shape tuple or array to a shape tuple.
def normalize_shape(shape): """ Normalize a shape tuple or array to a shape tuple. Parameters ---------- shape : tuple of int or ndarray The input to normalize. May optionally be an array. Returns ------- tuple of int Shape tuple. """ if isinstance(shape, tuple...
Project coordinates from one image shape to another.
def project_coords(coords, from_shape, to_shape): """ Project coordinates from one image shape to another. This performs a relative projection, e.g. a point at 60% of the old image width will be at 60% of the new image width after projection. Parameters ---------- coords : ndarray or tuple...
Add gaussian noise ( aka white noise ) to images.
def AdditiveGaussianNoise(loc=0, scale=0, per_channel=False, name=None, deterministic=False, random_state=None): """ Add gaussian noise (aka white noise) to images. dtype support:: See ``imgaug.augmenters.arithmetic.AddElementwise``. Parameters ---------- loc : number or tuple of numb...