_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q251800 | sum_to_n | train | def sum_to_n(n, size, limit=None): #from http://stackoverflow.com/questions/2065553/python-get-all-numbers-that-add-up-to-a-number
"""Produce all lists of `size` positive integers in decreasing order
| python | {
"resource": ""
} |
q251801 | TokenExpression.nfa | train | def nfa(self, nextstate):
"""Returns an initial state for an NFA"""
if self.interval:
mininterval, maxinterval = self.interval #pylint: disable=unpacking-non-sequence
nextstate2 = nextstate
for i in range(maxinterval):
state = State(transitions=[(self,... | python | {
"resource": ""
} |
q251802 | Query.nfa | train | def nfa(self):
"""convert the expression into an NFA"""
finalstate = State(final=True)
nextstate = finalstate
for tokenexpr in reversed(self):
| python | {
"resource": ""
} |
q251803 | stddev | train | def stddev(values, meanval=None): #from AI: A Modern Appproach
"""The standard deviation of a set of values.
Pass in the mean if you already know it."""
if meanval == None: | python | {
"resource": ""
} |
q251804 | FrequencyList.save | train | def save(self, filename, addnormalised=False):
"""Save a frequency list to file, can be loaded later using the load method"""
f = io.open(filename,'w',encoding='utf-8')
| python | {
"resource": ""
} |
q251805 | FrequencyList.output | train | def output(self,delimiter = '\t', addnormalised=False):
"""Print a representation of the frequency list"""
for type, count in self:
if isinstance(type,tuple) or isinstance(type,list):
if addnormalised:
yield " ".join((u(x) for x in type)) + delimiter + str... | python | {
"resource": ""
} |
q251806 | Distribution.entropy | train | def entropy(self, base = 2):
"""Compute the entropy of the distribution"""
entropy = 0
if not base and self.base: base = self.base
for type in self._dist:
if not base:
entropy | python | {
"resource": ""
} |
q251807 | Distribution.output | train | def output(self,delimiter = '\t', freqlist = None):
"""Generator yielding formatted strings expressing the time and probabily for each item in the distribution"""
for type, prob in self:
if freqlist:
if isinstance(type,list) or isinstance(type, tuple):
yie... | python | {
"resource": ""
} |
q251808 | FreeLingClient.process | train | def process(self, sourcewords, debug=False):
"""Process a list of words, passing it to the server and realigning the output with the original words"""
if isinstance( sourcewords, list ) or isinstance( sourcewords, tuple ):
sourcewords_s = " ".join(sourcewords)
else:
... | python | {
"resource": ""
} |
q251809 | checkversion | train | def checkversion(version, REFVERSION=FOLIAVERSION):
"""Checks FoLiA version, returns 1 if the document is newer than the library, -1 if it is older, 0 if it is equal"""
try:
for refversion, docversion in zip([int(x) for x in REFVERSION.split('.')], [int(x) for x in | python | {
"resource": ""
} |
q251810 | xmltreefromstring | train | def xmltreefromstring(s):
"""Internal function, deals with different Python versions, unicode strings versus bytes, and with the leak bug in lxml"""
if sys.version < '3':
#Python 2
if isinstance(s,unicode): #pylint: disable=undefined-variable
s = s.encode('utf-8')
try:
... | python | {
"resource": ""
} |
q251811 | xmltreefromfile | train | def xmltreefromfile(filename):
"""Internal function to read an XML file"""
try:
return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))
| python | {
"resource": ""
} |
q251812 | commonancestors | train | def commonancestors(Class, *args):
"""Generator function to find common ancestors of a particular type for any two or more FoLiA element instances.
The function produces all common ancestors of the type specified, starting from the closest one up to the most distant one.
Parameters:
Class: The typ... | python | {
"resource": ""
} |
q251813 | AbstractElement.description | train | def description(self):
"""Obtain the description associated with the element.
Raises:
:class:`NoSuchAnnotation` if there is no associated description."""
for e in self: | python | {
"resource": ""
} |
q251814 | AbstractElement.findcorrectionhandling | train | def findcorrectionhandling(self, cls):
"""Find the proper correctionhandling given a textclass by looking in the underlying corrections where it is reused"""
if cls == "current":
return CorrectionHandling.CURRENT
elif cls == "original":
return CorrectionHandling.ORIGINAL ... | python | {
"resource": ""
} |
q251815 | AbstractElement.textvalidation | train | def textvalidation(self, warnonly=None):
"""Run text validation on this element. Checks whether any text redundancy is consistent and whether offsets are valid.
Parameters:
warnonly (bool): Warn only (True) or raise exceptions (False). If set to None then this value will be determined based... | python | {
"resource": ""
} |
q251816 | AbstractElement.speech_speaker | train | def speech_speaker(self):
"""Retrieves the speaker of the audio or video file associated with the element.
The source is inherited from ancestor elements if none is specified. For this reason, always use this method rather than access the ``src`` attribute directly.
Returns:
str or... | python | {
"resource": ""
} |
q251817 | AbstractElement.feat | train | def feat(self,subset):
"""Obtain the feature class value of the specific subset.
If a feature occurs multiple times, the values will be returned in a list.
Example::
sense = word.annotation(folia.Sense)
synset = sense.feat('synset')
Returns:
str or... | python | {
"resource": ""
} |
q251818 | AbstractElement.copy | train | def copy(self, newdoc=None, idsuffix=""):
"""Make a deep copy of this element and all its children.
Parameters:
newdoc (:class:`Document`): The document the copy should be associated with.
idsuffix (str or bool): If set to a string, the ID of the copy will be append with this (p... | python | {
"resource": ""
} |
q251819 | AbstractElement.copychildren | train | def copychildren(self, newdoc=None, idsuffix=""):
"""Generator creating a deep copy of the children of this element.
Invokes :meth:`copy` on all children, parameters are the same.
"""
if idsuffix is True: idsuffix = ".copy." + "%08x" % random.getrandbits(32) #random 32-bit hash for each... | python | {
"resource": ""
} |
q251820 | ActWrapper.save_act | validation | def save_act(self, path=None):
"""Save model to a pickle located at `path`"""
if path is None:
path = os.path.join(logger.get_dir(), "model.pkl")
with tempfile.TemporaryDirectory() as td:
save_variables(os.path.join(td, "model"))
arc_name = os.path.join(td, "... | python | {
"resource": ""
} |
q251821 | nature_cnn | validation | def nature_cnn(unscaled_images, **conv_kwargs):
"""
CNN from Nature paper.
"""
scaled_images = tf.cast(unscaled_images, tf.float32) / 255.
activ = tf.nn.relu
h = activ(conv(scaled_images, 'c1', nf=32, rf=8, stride=4, init_scale=np.sqrt(2),
**conv_kwargs))
h2 = activ(conv(h... | python | {
"resource": ""
} |
q251822 | conv_only | validation | def conv_only(convs=[(32, 8, 4), (64, 4, 2), (64, 3, 1)], **conv_kwargs):
'''
convolutions-only net
Parameters:
----------
conv: list of triples (filter_number, filter_size, stride) specifying parameters for each layer.
Returns:
function that takes tensorflow tensor as input and re... | python | {
"resource": ""
} |
q251823 | make_vec_env | validation | def make_vec_env(env_id, env_type, num_env, seed,
wrapper_kwargs=None,
start_index=0,
reward_scale=1.0,
flatten_dict_observations=True,
gamestate=None):
"""
Create a wrapped, monitored SubprocVecEnv for Atari and MuJoCo.
""... | python | {
"resource": ""
} |
q251824 | parse_unknown_args | validation | def parse_unknown_args(args):
"""
Parse arguments not consumed by arg parser into a dicitonary
"""
retval = {}
preceded_by_key = False
for arg in args:
if arg.startswith('--'):
if '=' in arg:
key = arg.split('=')[0][2:]
value = arg.split('=')[1... | python | {
"resource": ""
} |
q251825 | clear_mpi_env_vars | validation | def clear_mpi_env_vars():
"""
from mpi4py import MPI will call MPI_Init by default. If the child process has MPI environment variables, MPI will think that the child process is an MPI process just like the parent and do bad things such as hang.
This context manager is a hacky way to clear those environment... | python | {
"resource": ""
} |
q251826 | cg | validation | def cg(f_Ax, b, cg_iters=10, callback=None, verbose=False, residual_tol=1e-10):
"""
Demmel p 312
"""
p = b.copy()
r = b.copy()
x = np.zeros_like(b)
rdotr = r.dot(r)
fmtstr = "%10i %10.3g %10.3g"
titlestr = "%10s %10s %10s"
if verbose: print(titlestr % ("iter", "residual norm",... | python | {
"resource": ""
} |
q251827 | observation_placeholder | validation | def observation_placeholder(ob_space, batch_size=None, name='Ob'):
'''
Create placeholder to feed observations into of the size appropriate to the observation space
Parameters:
----------
ob_space: gym.Space observation space
batch_size: int size of the batch to be fed into input.... | python | {
"resource": ""
} |
q251828 | observation_input | validation | def observation_input(ob_space, batch_size=None, name='Ob'):
'''
Create placeholder to feed observations into of the size appropriate to the observation space, and add input
encoder of the appropriate type.
| python | {
"resource": ""
} |
q251829 | encode_observation | validation | def encode_observation(ob_space, placeholder):
'''
Encode input in the way that is appropriate to the observation space
Parameters:
----------
ob_space: gym.Space observation space
placeholder: tf.placeholder observation input placeholder
'''
if isinstance(ob_space, Di... | python | {
"resource": ""
} |
q251830 | RolloutWorker.save_policy | validation | def save_policy(self, path):
"""Pickles the current policy for later inspection.
"""
| python | {
"resource": ""
} |
q251831 | RolloutWorker.logs | validation | def logs(self, prefix='worker'):
"""Generates a dictionary that contains all collected statistics.
"""
logs = []
logs += [('success_rate', np.mean(self.success_history))]
if self.compute_Q:
logs += [('mean_Q', np.mean(self.Q_history))]
logs += | python | {
"resource": ""
} |
q251832 | smooth | validation | def smooth(y, radius, mode='two_sided', valid_only=False):
'''
Smooth signal y, where radius is determines the size of the window
mode='twosided':
average over the window [max(index - radius, 0), min(index + radius, len(y)-1)]
mode='causal':
average over the window [max(index - radius, ... | python | {
"resource": ""
} |
q251833 | copy_obs_dict | validation | def copy_obs_dict(obs):
"""
Deep-copy an observation dict.
"""
| python | {
"resource": ""
} |
q251834 | obs_space_info | validation | def obs_space_info(obs_space):
"""
Get dict-structured information about a gym.Space.
Returns:
A tuple (keys, shapes, dtypes):
keys: a list of dict keys.
shapes: a dict mapping keys to shapes.
dtypes: a dict mapping keys to dtypes.
"""
if isinstance(obs_space, gym.spac... | python | {
"resource": ""
} |
q251835 | q_retrace | validation | def q_retrace(R, D, q_i, v, rho_i, nenvs, nsteps, gamma):
"""
Calculates q_retrace targets
:param R: Rewards
:param D: Dones
:param q_i: Q values for actions taken
:param v: V values
:param rho_i: Importance weight for each action
:return: Q_retrace values
"""
rho_bar = batch_to... | python | {
"resource": ""
} |
q251836 | PiecewiseSchedule.value | validation | def value(self, t):
"""See Schedule.value"""
for (l_t, l), (r_t, r) in zip(self._endpoints[:-1], self._endpoints[1:]):
if l_t <= t and t < r_t:
alpha = float(t - l_t) / (r_t - l_t)
| python | {
"resource": ""
} |
q251837 | _subproc_worker | validation | def _subproc_worker(pipe, parent_pipe, env_fn_wrapper, obs_bufs, obs_shapes, obs_dtypes, keys):
"""
Control a single environment instance using IPC and
shared memory.
"""
def _write_obs(maybe_dict_obs):
flatdict = obs_to_dict(maybe_dict_obs)
for k in keys:
dst = obs_bufs[... | python | {
"resource": ""
} |
q251838 | learn | validation | def learn(
network,
env,
seed=None,
nsteps=5,
total_timesteps=int(80e6),
vf_coef=0.5,
ent_coef=0.01,
max_grad_norm=0.5,
lr=7e-4,
lrschedule='linear',
epsilon=1e-5,
alpha=0.99,
gamma=0.99,
log_interval=100,
load_path=None,
**network_kwargs):
'''
Ma... | python | {
"resource": ""
} |
q251839 | sf01 | validation | def sf01(arr):
"""
swap and then flatten axes 0 and 1
"""
s = arr.shape
return | python | {
"resource": ""
} |
q251840 | pretty_eta | validation | def pretty_eta(seconds_left):
"""Print the number of seconds in human readable format.
Examples:
2 days
2 hours and 37 minutes
less than a minute
Paramters
---------
seconds_left: int
Number of seconds to be converted to the ETA
Returns
-------
eta: str
Stri... | python | {
"resource": ""
} |
q251841 | boolean_flag | validation | 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... | python | {
"resource": ""
} |
q251842 | get_wrapper_by_name | validation | 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
... | python | {
"resource": ""
} |
q251843 | pickle_load | validation | 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
... | python | {
"resource": ""
} |
q251844 | RunningAvg.update | validation | def update(self, new_val):
"""Update the estimate.
Parameters
----------
new_val: float
new observated value of estimated quantity.
"""
if self._value is None:
| python | {
"resource": ""
} |
q251845 | store_args | validation | 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 ... | python | {
"resource": ""
} |
q251846 | flatten_grads | validation | def flatten_grads(var_list, grads):
"""Flattens a variables and their gradients.
"""
| python | {
"resource": ""
} |
q251847 | nn | validation | 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,
... | python | {
"resource": ""
} |
q251848 | mpi_fork | validation | 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",... | python | {
"resource": ""
} |
q251849 | get_session | validation | def get_session(config=None):
"""Get default session or create one with a given config"""
sess = tf.get_default_session()
if sess is None:
| python | {
"resource": ""
} |
q251850 | initialize | validation | def initialize():
"""Initialize all the uninitialized variables in the global scope."""
new_variables | python | {
"resource": ""
} |
q251851 | adjust_shape | validation | 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... | python | {
"resource": ""
} |
q251852 | wrap_deepmind | validation | 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... | python | {
"resource": ""
} |
q251853 | EpisodicLifeEnv.reset | validation | 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) | python | {
"resource": ""
} |
q251854 | gpu_count | validation | def gpu_count():
"""
Count the GPUs on this machine.
"""
if shutil.which('nvidia-smi') is None:
| python | {
"resource": ""
} |
q251855 | setup_mpi_gpus | validation | 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 | python | {
"resource": ""
} |
q251856 | get_local_rank_size | validation | 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... | python | {
"resource": ""
} |
q251857 | share_file | validation | 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:
| python | {
"resource": ""
} |
q251858 | dict_gather | validation | 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():
| python | {
"resource": ""
} |
q251859 | discount | validation | 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],
| python | {
"resource": ""
} |
q251860 | PrioritizedReplayBuffer.add | validation | def add(self, *args, **kwargs):
"""See ReplayBuffer.store_effect"""
idx = self._next_idx
super().add(*args, **kwargs)
self._it_sum[idx] = | python | {
"resource": ""
} |
q251861 | PrioritizedReplayBuffer.update_priorities | validation | 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:... | python | {
"resource": ""
} |
q251862 | wrap_deepmind_retro | validation | 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)
| python | {
"resource": ""
} |
q251863 | make_sample_her_transitions | validation | 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 ... | python | {
"resource": ""
} |
q251864 | parse_cmdline_kwargs | validation | 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:
| python | {
"resource": ""
} |
q251865 | compute_geometric_median | validation | 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... | python | {
"resource": ""
} |
q251866 | Keypoint.project | validation | 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... | python | {
"resource": ""
} |
q251867 | Keypoint.shift | validation | 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 | python | {
"resource": ""
} |
q251868 | Keypoint.draw_on_image | validation | 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... | python | {
"resource": ""
} |
q251869 | Keypoint.generate_similar_points_manhattan | validation | 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... | python | {
"resource": ""
} |
q251870 | Keypoint.copy | validation | 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.
| python | {
"resource": ""
} |
q251871 | Keypoint.deepcopy | validation | 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. | python | {
"resource": ""
} |
q251872 | KeypointsOnImage.on | validation | 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
... | python | {
"resource": ""
} |
q251873 | KeypointsOnImage.draw_on_image | validation | 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 : (... | python | {
"resource": ""
} |
q251874 | KeypointsOnImage.shift | validation | 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... | python | {
"resource": ""
} |
q251875 | KeypointsOnImage.copy | validation | 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... | python | {
"resource": ""
} |
q251876 | KeypointsOnImage.deepcopy | validation | 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... | python | {
"resource": ""
} |
q251877 | BoundingBox.project | validation | 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... | python | {
"resource": ""
} |
q251878 | BoundingBox.extend | validation | 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... | python | {
"resource": ""
} |
q251879 | BoundingBox.intersection | validation | 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... | python | {
"resource": ""
} |
q251880 | BoundingBox.union | validation | 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
| python | {
"resource": ""
} |
q251881 | BoundingBox.iou | validation | 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... | python | {
"resource": ""
} |
q251882 | BoundingBox.is_fully_within_image | validation | 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 ... | python | {
"resource": ""
} |
q251883 | BoundingBox.is_partly_within_image | validation | 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.
... | python | {
"resource": ""
} |
q251884 | BoundingBox.is_out_of_image | validation | 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... | python | {
"resource": ""
} |
q251885 | BoundingBox.clip_out_of_image | validation | 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 ... | python | {
"resource": ""
} |
q251886 | BoundingBox.draw_on_image | validation | 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... | python | {
"resource": ""
} |
q251887 | BoundingBox.extract_from_image | validation | 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
... | python | {
"resource": ""
} |
q251888 | BoundingBox.copy | validation | 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... | python | {
"resource": ""
} |
q251889 | BoundingBoxesOnImage.draw_on_image | validation | 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... | python | {
"resource": ""
} |
q251890 | BoundingBoxesOnImage.remove_out_of_image | validation | 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... | python | {
"resource": ""
} |
q251891 | BoundingBoxesOnImage.clip_out_of_image | validation | 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.
"""
| python | {
"resource": ""
} |
q251892 | BoundingBoxesOnImage.deepcopy | validation | 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,
| python | {
"resource": ""
} |
q251893 | Emboss | validation | 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")... | python | {
"resource": ""
} |
q251894 | EdgeDetect | validation | 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... | python | {
"resource": ""
} |
q251895 | DirectedEdgeDetect | validation | 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... | python | {
"resource": ""
} |
q251896 | normalize_shape | validation | 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.
| python | {
"resource": ""
} |
q251897 | project_coords | validation | 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... | python | {
"resource": ""
} |
q251898 | AdditivePoissonNoise | validation | def AdditivePoissonNoise(lam=0, per_channel=False, name=None, deterministic=False, random_state=None):
"""
Create an augmenter to add poisson noise to images.
Poisson noise is comparable to gaussian noise as in ``AdditiveGaussianNoise``, but the values are sampled from
a poisson distribution instead of... | python | {
"resource": ""
} |
q251899 | Dropout | validation | def Dropout(p=0, per_channel=False, name=None, deterministic=False, random_state=None):
"""
Augmenter that sets a certain fraction of pixels in images to zero.
dtype support::
See ``imgaug.augmenters.arithmetic.MultiplyElementwise``.
Parameters
----------
p : float or tuple of float o... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.