def pad_to_aspect_ratio(arr, aspect_ratio, mode="<STR_LIT>", cval=<NUM_LIT:0>, return_pad_amounts=False):

pad_top, pad_right, pad_bottom, pad_left = compute_paddings_for_aspect_ratio(arr, aspect_ratio)<EOL>arr_padded = pad(<EOL>arr,<EOL>top=pad_top,<EOL>right=pad_right,<EOL>bottom=pad_bottom,<EOL>left=pad_left,<EOL>mode=mode,<EOL>cval=cval<EOL>)<EOL>if return_pad_amounts:<EOL><INDENT>return arr_padded, (pad_top, pad_right, pad_bottom, pad_left)<EOL><DEDENT>else:<EOL><INDENT>return arr_padded<EOL><DEDENT>

Pad an image-like array on its sides so that it matches a target aspect ratio.

Depending on which dimension is smaller (height or width), only the corresponding
sides (left/right or top/bottom) will be padded. In each case, both of the sides will
be padded equally.

dtype support::

    See :func:`imgaug.imgaug.pad`.

Parameters
----------
arr : (H,W) ndarray or (H,W,C) ndarray
    Image-like array to pad.

aspect_ratio : float
    Target aspect ratio, given as width/height. E.g. 2.0 denotes the image having twice
    as much width as height.

mode : str, optional
    Padding mode to use. See :func:`numpy.pad` for details.

cval : number, optional
    Value to use for padding if `mode` is ``constant``. See :func:`numpy.pad` for details.

return_pad_amounts : bool, optional
    If False, then only the padded image will be returned. If True, a tuple with two
    entries will be returned, where the first entry is the padded image and the second
    entry are the amounts by which each image side was padded. These amounts are again a
    tuple of the form (top, right, bottom, left), with each value being an integer.

Returns
-------
arr_padded : (H',W') ndarray or (H',W',C) ndarray
    Padded image as (H',W') or (H',W',C) ndarray, fulfulling the given aspect_ratio.

tuple of int
    Amounts by which the image was padded on each side, given as a tuple ``(top, right, bottom, left)``.
    This tuple is only returned if `return_pad_amounts` was set to True.
    Otherwise only ``arr_padded`` is returned.


def pool(arr, block_size, func, cval=<NUM_LIT:0>, preserve_dtype=True):

<EOL>from . import dtypes as iadt<EOL>iadt.gate_dtypes(arr,<EOL>allowed=["<STR_LIT:bool>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>disallowed=["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>"],<EOL>augmenter=None)<EOL>do_assert(arr.ndim in [<NUM_LIT:2>, <NUM_LIT:3>])<EOL>is_valid_int = is_single_integer(block_size) and block_size >= <NUM_LIT:1><EOL>is_valid_tuple = is_iterable(block_size) and len(block_size) in [<NUM_LIT:2>, <NUM_LIT:3>]and [is_single_integer(val) and val >= <NUM_LIT:1> for val in block_size]<EOL>do_assert(is_valid_int or is_valid_tuple)<EOL>if is_single_integer(block_size):<EOL><INDENT>block_size = [block_size, block_size]<EOL><DEDENT>if len(block_size) < arr.ndim:<EOL><INDENT>block_size = list(block_size) + [<NUM_LIT:1>]<EOL><DEDENT>input_dtype = arr.dtype<EOL>arr_reduced = skimage.measure.block_reduce(arr, tuple(block_size), func, cval=cval)<EOL>if preserve_dtype and arr_reduced.dtype.type != input_dtype:<EOL><INDENT>arr_reduced = arr_reduced.astype(input_dtype)<EOL><DEDENT>return arr_reduced<EOL>

Resize an array by pooling values within blocks.

dtype support::

    * ``uint8``: yes; fully tested
    * ``uint16``: yes; tested
    * ``uint32``: yes; tested (2)
    * ``uint64``: no (1)
    * ``int8``: yes; tested
    * ``int16``: yes; tested
    * ``int32``: yes; tested (2)
    * ``int64``: no (1)
    * ``float16``: yes; tested
    * ``float32``: yes; tested
    * ``float64``: yes; tested
    * ``float128``: yes; tested (2)
    * ``bool``: yes; tested

    - (1) results too inaccurate (at least when using np.average as func)
    - (2) Note that scikit-image documentation says that the wrapped pooling function converts
          inputs to float64. Actual tests showed no indication of that happening (at least when
          using preserve_dtype=True).

Parameters
----------
arr : (H,W) ndarray or (H,W,C) ndarray
    Image-like array to pool. Ideally of datatype ``numpy.float64``.

block_size : int or tuple of int
    Spatial size of each group of values to pool, aka kernel size.
    If a single integer, then a symmetric block of that size along height and width will be used.
    If a tuple of two values, it is assumed to be the block size along height and width of the image-like,
    with pooling happening per channel.
    If a tuple of three values, it is assumed to be the block size along height, width and channels.

func : callable
    Function to apply to a given block in order to convert it to a single number,
    e.g. :func:`numpy.average`, :func:`numpy.min`, :func:`numpy.max`.

cval : number, optional
    Value to use in order to pad the array along its border if the array cannot be divided
    by `block_size` without remainder.

preserve_dtype : bool, optional
    Whether to convert the array back to the input datatype if it is changed away from
    that in the pooling process.

Returns
-------
arr_reduced : (H',W') ndarray or (H',W',C') ndarray
    Array after pooling.


def avg_pool(arr, block_size, cval=<NUM_LIT:0>, preserve_dtype=True):

return pool(arr, block_size, np.average, cval=cval, preserve_dtype=preserve_dtype)<EOL>

Resize an array using average pooling.

dtype support::

    See :func:`imgaug.imgaug.pool`.

Parameters
----------
arr : (H,W) ndarray or (H,W,C) ndarray
    Image-like array to pool. See :func:`imgaug.pool` for details.

block_size : int or tuple of int or tuple of int
    Size of each block of values to pool. See :func:`imgaug.pool` for details.

cval : number, optional
    Padding value. See :func:`imgaug.pool` for details.

preserve_dtype : bool, optional
    Whether to preserve the input array dtype. See :func:`imgaug.pool` for details.

Returns
-------
arr_reduced : (H',W') ndarray or (H',W',C') ndarray
    Array after average pooling.


def max_pool(arr, block_size, cval=<NUM_LIT:0>, preserve_dtype=True):

return pool(arr, block_size, np.max, cval=cval, preserve_dtype=preserve_dtype)<EOL>

Resize an array using max-pooling.

dtype support::

    See :func:`imgaug.imgaug.pool`.

Parameters
----------
arr : (H,W) ndarray or (H,W,C) ndarray
    Image-like array to pool. See :func:`imgaug.pool` for details.

block_size : int or tuple of int or tuple of int
    Size of each block of values to pool. See `imgaug.pool` for details.

cval : number, optional
    Padding value. See :func:`imgaug.pool` for details.

preserve_dtype : bool, optional
    Whether to preserve the input array dtype. See :func:`imgaug.pool` for details.

Returns
-------
arr_reduced : (H',W') ndarray or (H',W',C') ndarray
    Array after max-pooling.


def draw_grid(images, rows=None, cols=None):

nb_images = len(images)<EOL>do_assert(nb_images > <NUM_LIT:0>)<EOL>if is_np_array(images):<EOL><INDENT>do_assert(images.ndim == <NUM_LIT:4>)<EOL><DEDENT>else:<EOL><INDENT>do_assert(is_iterable(images) and is_np_array(images[<NUM_LIT:0>]) and images[<NUM_LIT:0>].ndim == <NUM_LIT:3>)<EOL>dts = [image.dtype.name for image in images]<EOL>nb_dtypes = len(set(dts))<EOL>do_assert(nb_dtypes == <NUM_LIT:1>, ("<STR_LIT>"<EOL>+ "<STR_LIT>") % (nb_dtypes, "<STR_LIT:U+002CU+0020>".join(dts)))<EOL><DEDENT>cell_height = max([image.shape[<NUM_LIT:0>] for image in images])<EOL>cell_width = max([image.shape[<NUM_LIT:1>] for image in images])<EOL>channels = set([image.shape[<NUM_LIT:2>] for image in images])<EOL>do_assert(<EOL>len(channels) == <NUM_LIT:1>,<EOL>"<STR_LIT>"<EOL>+ "<STR_LIT>" % (str(channels), len(channels))<EOL>)<EOL>nb_channels = list(channels)[<NUM_LIT:0>]<EOL>if rows is None and cols is None:<EOL><INDENT>rows = cols = int(math.ceil(math.sqrt(nb_images)))<EOL><DEDENT>elif rows is not None:<EOL><INDENT>cols = int(math.ceil(nb_images / rows))<EOL><DEDENT>elif cols is not None:<EOL><INDENT>rows = int(math.ceil(nb_images / cols))<EOL><DEDENT>do_assert(rows * cols >= nb_images)<EOL>width = cell_width * cols<EOL>height = cell_height * rows<EOL>dt = images.dtype if is_np_array(images) else images[<NUM_LIT:0>].dtype<EOL>grid = np.zeros((height, width, nb_channels), dtype=dt)<EOL>cell_idx = <NUM_LIT:0><EOL>for row_idx in sm.xrange(rows):<EOL><INDENT>for col_idx in sm.xrange(cols):<EOL><INDENT>if cell_idx < nb_images:<EOL><INDENT>image = images[cell_idx]<EOL>cell_y1 = cell_height * row_idx<EOL>cell_y2 = cell_y1 + image.shape[<NUM_LIT:0>]<EOL>cell_x1 = cell_width * col_idx<EOL>cell_x2 = cell_x1 + image.shape[<NUM_LIT:1>]<EOL>grid[cell_y1:cell_y2, cell_x1:cell_x2, :] = image<EOL><DEDENT>cell_idx += <NUM_LIT:1><EOL><DEDENT><DEDENT>return grid<EOL>

Converts multiple input images into a single image showing them in a grid.

dtype support::

    * ``uint8``: yes; fully tested
    * ``uint16``: yes; fully tested
    * ``uint32``: yes; fully tested
    * ``uint64``: yes; fully tested
    * ``int8``: yes; fully tested
    * ``int16``: yes; fully tested
    * ``int32``: yes; fully tested
    * ``int64``: yes; fully tested
    * ``float16``: yes; fully tested
    * ``float32``: yes; fully tested
    * ``float64``: yes; fully tested
    * ``float128``: yes; fully tested
    * ``bool``: yes; fully tested

Parameters
----------
images : (N,H,W,3) ndarray or iterable of (H,W,3) array
    The input images to convert to a grid.

rows : None or int, optional
    The number of rows to show in the grid.
    If None, it will be automatically derived.

cols : None or int, optional
    The number of cols to show in the grid.
    If None, it will be automatically derived.

Returns
-------
grid : (H',W',3) ndarray
    Image of the generated grid.


def show_grid(images, rows=None, cols=None):

grid = draw_grid(images, rows=rows, cols=cols)<EOL>imshow(grid)<EOL>

Converts the input images to a grid image and shows it in a new window.

dtype support::

    minimum of (
        :func:`imgaug.imgaug.draw_grid`,
        :func:`imgaug.imgaug.imshow`
    )

Parameters
----------
images : (N,H,W,3) ndarray or iterable of (H,W,3) array
    See :func:`imgaug.draw_grid`.

rows : None or int, optional
    See :func:`imgaug.draw_grid`.

cols : None or int, optional
    See :func:`imgaug.draw_grid`.


do_assert(backend in ["<STR_LIT>", "<STR_LIT>"], "<STR_LIT>" % (backend,))<EOL>if backend == "<STR_LIT>":<EOL><INDENT>image_bgr = image<EOL>if image.ndim == <NUM_LIT:3> and image.shape[<NUM_LIT:2>] in [<NUM_LIT:3>, <NUM_LIT:4>]:<EOL><INDENT>image_bgr = image[..., <NUM_LIT:0>:<NUM_LIT:3>][..., ::-<NUM_LIT:1>]<EOL><DEDENT>win_name = "<STR_LIT>"<EOL>cv2.namedWindow(win_name, cv2.WINDOW_NORMAL)<EOL>cv2.imshow(win_name, image_bgr)<EOL>cv2.waitKey(<NUM_LIT:0>)<EOL>cv2.destroyWindow(win_name)<EOL><DEDENT>else:<EOL><INDENT>import matplotlib.pyplot as plt<EOL>dpi = <NUM_LIT><EOL>h, w = image.shape[<NUM_LIT:0>] / dpi, image.shape[<NUM_LIT:1>] / dpi<EOL>w = max(w, <NUM_LIT:6>)  <EOL>fig, ax = plt.subplots(figsize=(w, h), dpi=dpi)<EOL>fig.canvas.set_window_title("<STR_LIT>" % (image.shape,))<EOL>ax.imshow(image, cmap="<STR_LIT>")  <EOL>plt.show()<EOL><DEDENT>

Shows an image in a window.

dtype support::

    * ``uint8``: yes; not tested
    * ``uint16``: ?
    * ``uint32``: ?
    * ``uint64``: ?
    * ``int8``: ?
    * ``int16``: ?
    * ``int32``: ?
    * ``int64``: ?
    * ``float16``: ?
    * ``float32``: ?
    * ``float64``: ?
    * ``float128``: ?
    * ``bool``: ?

Parameters
----------
image : (H,W,3) ndarray
    Image to show.

backend : {'matplotlib', 'cv2'}, optional
    Library to use to show the image. May be either matplotlib or OpenCV ('cv2').
    OpenCV tends to be faster, but apparently causes more technical issues.


if not condition:<EOL><INDENT>raise AssertionError(str(message))<EOL><DEDENT>

Function that behaves equally to an `assert` statement, but raises an
Exception.

This is added because `assert` statements are removed in optimized code.
It replaces `assert` statements throughout the library that should be
kept even in optimized code.

Parameters
----------
condition : bool
    If False, an exception is raised.

message : str, optional
    Error message.


import warnings<EOL>warnings.warn(msg,<EOL>category=DeprecationWarning,<EOL>stacklevel=stacklevel)<EOL>

Generate a non-silent deprecation warning with stacktrace.

    The used warning is ``imgaug.imgaug.DeprecationWarning``.

    Parameters
    ----------
    msg : str
        The message of the warning.

    stacklevel : int, optional
        How many steps above this function to "jump" in the stacktrace for
        the displayed file and line number of the error message.
        Usually 2.


def is_activated(self, images, augmenter, parents, default):

if self.activator is None:<EOL><INDENT>return default<EOL><DEDENT>else:<EOL><INDENT>return self.activator(images, augmenter, parents, default)<EOL><DEDENT>

Returns whether an augmenter may be executed.

Returns
-------
bool
    If True, the augmenter may be executed. If False, it may not be executed.


def is_propagating(self, images, augmenter, parents, default):

if self.propagator is None:<EOL><INDENT>return default<EOL><DEDENT>else:<EOL><INDENT>return self.propagator(images, augmenter, parents, default)<EOL><DEDENT>

Returns whether an augmenter may call its children to augment an
image. This is independent of the augmenter itself possible changing
the image, without calling its children. (Most (all?) augmenters with
children currently dont perform any changes themselves.)

Returns
-------
bool
    If True, the augmenter may be propagate to its children. If False, it may not.


def preprocess(self, images, augmenter, parents):

if self.preprocessor is None:<EOL><INDENT>return images<EOL><DEDENT>else:<EOL><INDENT>return self.preprocessor(images, augmenter, parents)<EOL><DEDENT>

A function to be called before the augmentation of images starts (per augmenter).

Returns
-------
(N,H,W,C) ndarray or (N,H,W) ndarray or list of (H,W,C) ndarray or list of (H,W) ndarray
    The input images, optionally modified.


def postprocess(self, images, augmenter, parents):

if self.postprocessor is None:<EOL><INDENT>return images<EOL><DEDENT>else:<EOL><INDENT>return self.postprocessor(images, augmenter, parents)<EOL><DEDENT>

A function to be called after the augmentation of images was
performed.

Returns
-------
(N,H,W,C) ndarray or (N,H,W) ndarray or list of (H,W,C) ndarray or list of (H,W) ndarray
    The input images, optionally modified.


def __init__(self, augseq, processes=None, maxtasksperchild=None, seed=None):

<EOL>assert Pool._WORKER_AUGSEQ is None, "<STR_LIT>""<STR_LIT>"<EOL>assert processes is None or processes != <NUM_LIT:0><EOL>self.augseq = augseq<EOL>self.processes = processes<EOL>self.maxtasksperchild = maxtasksperchild<EOL>self.seed = seed<EOL>if self.seed is not None:<EOL><INDENT>assert ia.SEED_MIN_VALUE <= self.seed <= ia.SEED_MAX_VALUE<EOL><DEDENT>self._pool = None<EOL>self._batch_idx = <NUM_LIT:0><EOL>

Initialize augmentation pool.

Parameters
----------
augseq : Augmenter
    The augmentation sequence to apply to batches.

processes : None or int, optional
    The number of background workers, similar to the same parameter in multiprocessing.Pool.
    If ``None``, the number of the machine's CPU cores will be used (this counts hyperthreads as CPU cores).
    If this is set to a negative value ``p``, then ``P - abs(p)`` will be used, where ``P`` is the number
    of CPU cores. E.g. ``-1`` would use all cores except one (this is useful to e.g. reserve one core to
    feed batches to the GPU).

maxtasksperchild : None or int, optional
    The number of tasks done per worker process before the process is killed and restarted, similar to the
    same parameter in multiprocessing.Pool. If ``None``, worker processes will not be automatically restarted.

seed : None or int, optional
    The seed to use for child processes. If ``None``, a random seed will be used.


if self._pool is None:<EOL><INDENT>processes = self.processes<EOL>if processes is not None and processes < <NUM_LIT:0>:<EOL><INDENT>try:<EOL><INDENT>processes = multiprocessing.cpu_count() - abs(processes)<EOL>processes = max(processes, <NUM_LIT:1>)<EOL><DEDENT>except (ImportError, NotImplementedError):<EOL><INDENT>processes = None<EOL><DEDENT><DEDENT>self._pool = multiprocessing.Pool(processes,<EOL>initializer=_Pool_initialize_worker,<EOL>initargs=(self.augseq, self.seed),<EOL>maxtasksperchild=self.maxtasksperchild)<EOL><DEDENT>return self._pool<EOL>

Return the multiprocessing.Pool instance or create it if not done yet.

        Returns
        -------
        multiprocessing.Pool
            The multiprocessing.Pool used internally by this imgaug.multicore.Pool.


def map_batches(self, batches, chunksize=None):

assert isinstance(batches, list), ("<STR_LIT>"<EOL>+ "<STR_LIT>") % (type(batches),)<EOL>return self.pool.map(_Pool_starworker, self._handle_batch_ids(batches), chunksize=chunksize)<EOL>

Augment batches.

Parameters
----------
batches : list of imgaug.augmentables.batches.Batch
    The batches to augment.

chunksize : None or int, optional
    Rough indicator of how many tasks should be sent to each worker. Increasing this number can improve
    performance.

Returns
-------
list of imgaug.augmentables.batches.Batch
    Augmented batches.


def map_batches_async(self, batches, chunksize=None, callback=None, error_callback=None):

assert isinstance(batches, list), ("<STR_LIT>"<EOL>+ "<STR_LIT>") % (type(batches),)<EOL>return self.pool.map_async(_Pool_starworker, self._handle_batch_ids(batches),<EOL>chunksize=chunksize, callback=callback, error_callback=error_callback)<EOL>

Augment batches asynchonously.

Parameters
----------
batches : list of imgaug.augmentables.batches.Batch
    The batches to augment.

chunksize : None or int, optional
    Rough indicator of how many tasks should be sent to each worker. Increasing this number can improve
    performance.

callback : None or callable, optional
    Function to call upon finish. See `multiprocessing.Pool`.

error_callback : None or callable, optional
    Function to call upon errors. See `multiprocessing.Pool`.

Returns
-------
multiprocessing.MapResult
    Asynchonous result. See `multiprocessing.Pool`.


def imap_batches(self, batches, chunksize=<NUM_LIT:1>):

assert ia.is_generator(batches), ("<STR_LIT>"<EOL>+ "<STR_LIT>") % (type(batches),)<EOL>gen = self.pool.imap(_Pool_starworker, self._handle_batch_ids_gen(batches), chunksize=chunksize)<EOL>for batch in gen:<EOL><INDENT>yield batch<EOL><DEDENT>

Augment batches from a generator.

Parameters
----------
batches : generator of imgaug.augmentables.batches.Batch
    The batches to augment, provided as a generator. Each call to the generator should yield exactly one
    batch.

chunksize : None or int, optional
    Rough indicator of how many tasks should be sent to each worker. Increasing this number can improve
    performance.

Yields
------
imgaug.augmentables.batches.Batch
    Augmented batch.


def imap_batches_unordered(self, batches, chunksize=<NUM_LIT:1>):

assert ia.is_generator(batches), ("<STR_LIT>"<EOL>+ "<STR_LIT>") % (type(batches),)<EOL>gen = self.pool.imap_unordered(_Pool_starworker, self._handle_batch_ids_gen(batches), chunksize=chunksize)<EOL>for batch in gen:<EOL><INDENT>yield batch<EOL><DEDENT>

Augment batches from a generator in a way that does not guarantee to preserve order.

Parameters
----------
batches : generator of imgaug.augmentables.batches.Batch
    The batches to augment, provided as a generator. Each call to the generator should yield exactly one
    batch.

chunksize : None or int, optional
    Rough indicator of how many tasks should be sent to each worker. Increasing this number can improve
    performance.

Yields
------
imgaug.augmentables.batches.Batch
    Augmented batch.


if self._pool is not None:<EOL><INDENT>self._pool.close()<EOL>self._pool.join()<EOL>self._pool = None<EOL><DEDENT>


if self._pool is not None:<EOL><INDENT>self._pool.terminate()<EOL>self._pool.join()<EOL>self._pool = None<EOL><DEDENT>


if self._pool is not None:<EOL><INDENT>self._pool.join()<EOL><DEDENT>

Wait for the workers to exit.

This may only be called after calling :func:`imgaug.multicore.Pool.join` or
:func:`imgaug.multicore.Pool.terminate`.


return self.count_workers_alive() == <NUM_LIT:0><EOL>

Determine whether the workers have finished the loading process.

Returns
-------
out : bool
    True if all workers have finished. Else False.


if not self.join_signal.is_set():<EOL><INDENT>self.join_signal.set()<EOL><DEDENT>time.sleep(<NUM_LIT>)<EOL>if self.main_worker_thread.is_alive():<EOL><INDENT>self.main_worker_thread.join()<EOL><DEDENT>if self.threaded:<EOL><INDENT>for worker in self.workers:<EOL><INDENT>if worker.is_alive():<EOL><INDENT>worker.join()<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for worker in self.workers:<EOL><INDENT>if worker.is_alive():<EOL><INDENT>worker.terminate()<EOL>worker.join()<EOL><DEDENT><DEDENT>while not self.all_finished():<EOL><INDENT>time.sleep(<NUM_LIT>)<EOL><DEDENT><DEDENT>if self.queue.full():<EOL><INDENT>self.queue.get()<EOL><DEDENT>self.queue.put(pickle.dumps(None, protocol=-<NUM_LIT:1>))<EOL>time.sleep(<NUM_LIT>)<EOL>while True:<EOL><INDENT>try:<EOL><INDENT>self._queue_internal.get(timeout=<NUM_LIT>)<EOL><DEDENT>except QueueEmpty:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if not self._queue_internal._closed:<EOL><INDENT>self._queue_internal.close()<EOL><DEDENT>if not self.queue._closed:<EOL><INDENT>self.queue.close()<EOL><DEDENT>self._queue_internal.join_thread()<EOL>self.queue.join_thread()<EOL>time.sleep(<NUM_LIT>)<EOL>


if self.all_finished():<EOL><INDENT>return None<EOL><DEDENT>batch_str = self.queue_result.get()<EOL>batch = pickle.loads(batch_str)<EOL>if batch is not None:<EOL><INDENT>return batch<EOL><DEDENT>else:<EOL><INDENT>self.nb_workers_finished += <NUM_LIT:1><EOL>if self.nb_workers_finished >= self.nb_workers:<EOL><INDENT>try:<EOL><INDENT>self.queue_source.get(timeout=<NUM_LIT>)  <EOL><DEDENT>except QueueEmpty:<EOL><INDENT>pass<EOL><DEDENT>return None<EOL><DEDENT>else:<EOL><INDENT>return self.get_batch()<EOL><DEDENT><DEDENT>

Returns a batch from the queue of augmented batches.

If workers are still running and there are no batches in the queue,
it will automatically wait for the next batch.

Returns
-------
out : None or imgaug.Batch
    One batch or None if all workers have finished.


def _augment_images_worker(self, augseq, queue_source, queue_result, seedval):

np.random.seed(seedval)<EOL>random.seed(seedval)<EOL>augseq.reseed(seedval)<EOL>ia.seed(seedval)<EOL>loader_finished = False<EOL>while not loader_finished:<EOL><INDENT>try:<EOL><INDENT>batch_str = queue_source.get(timeout=<NUM_LIT:0.1>)<EOL>batch = pickle.loads(batch_str)<EOL>if batch is None:<EOL><INDENT>loader_finished = True<EOL>queue_source.put(pickle.dumps(None, protocol=-<NUM_LIT:1>))<EOL><DEDENT>else:<EOL><INDENT>batch_aug = augseq.augment_batch(batch)<EOL>batch_str = pickle.dumps(batch_aug, protocol=-<NUM_LIT:1>)<EOL>queue_result.put(batch_str)<EOL><DEDENT><DEDENT>except QueueEmpty:<EOL><INDENT>time.sleep(<NUM_LIT>)<EOL><DEDENT><DEDENT>queue_result.put(pickle.dumps(None, protocol=-<NUM_LIT:1>))<EOL>time.sleep(<NUM_LIT>)<EOL>

Augment endlessly images in the source queue.

This is a worker function for that endlessly queries the source queue (input batches),
augments batches in it and sends the result to the output queue.


for worker in self.workers:<EOL><INDENT>if worker.is_alive():<EOL><INDENT>worker.terminate()<EOL><DEDENT><DEDENT>self.nb_workers_finished = len(self.workers)<EOL>if not self.queue_result._closed:<EOL><INDENT>self.queue_result.close()<EOL><DEDENT>time.sleep(<NUM_LIT>)<EOL>

Terminates all background processes immediately.

This will also free their RAM.


y = np.mean(X, <NUM_LIT:0>)<EOL>while True:<EOL><INDENT>D = scipy.spatial.distance.cdist(X, [y])<EOL>nonzeros = (D != <NUM_LIT:0>)[:, <NUM_LIT:0>]<EOL>Dinv = <NUM_LIT:1> / D[nonzeros]<EOL>Dinvs = np.sum(Dinv)<EOL>W = Dinv / Dinvs<EOL>T = np.sum(W * X[nonzeros], <NUM_LIT:0>)<EOL>num_zeros = len(X) - np.sum(nonzeros)<EOL>if num_zeros == <NUM_LIT:0>:<EOL><INDENT>y1 = T<EOL><DEDENT>elif num_zeros == len(X):<EOL><INDENT>return y<EOL><DEDENT>else:<EOL><INDENT>R = (T - y) * Dinvs<EOL>r = np.linalg.norm(R)<EOL>rinv = <NUM_LIT:0> if r == <NUM_LIT:0> else num_zeros/r<EOL>y1 = max(<NUM_LIT:0>, <NUM_LIT:1>-rinv)*T + min(<NUM_LIT:1>, rinv)*y<EOL><DEDENT>if scipy.spatial.distance.euclidean(y, y1) < eps:<EOL><INDENT>return y1<EOL><DEDENT>y = y1<EOL><DEDENT>

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 when to return the median.

Returns
-------
(2,) ndarray
    Geometric median as xy-coordinate.


return int(np.round(self.x))<EOL>

Return the keypoint's x-coordinate, rounded to the closest integer.

Returns
-------
result : int
    Keypoint's x-coordinate, rounded to the closest integer.


return int(np.round(self.y))<EOL>

Return the keypoint's y-coordinate, rounded to the closest integer.

Returns
-------
result : int
    Keypoint's y-coordinate, rounded to the closest integer.


def project(self, from_shape, to_shape):

xy_proj = project_coords([(self.x, self.y)], from_shape, to_shape)<EOL>return self.deepcopy(x=xy_proj[<NUM_LIT:0>][<NUM_LIT:0>], y=xy_proj[<NUM_LIT:0>][<NUM_LIT:1>])<EOL>

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 position will be (20, 40).

This is intended for cases where the original image is resized.
It cannot be used for more complex changes (e.g. padding, cropping).

Parameters
----------
from_shape : tuple of int
    Shape of the original image. (Before resize.)

to_shape : tuple of int
    Shape of the new image. (After resize.)

Returns
-------
imgaug.Keypoint
    Keypoint object with new coordinates.


def shift(self, x=<NUM_LIT:0>, y=<NUM_LIT:0>):

return self.deepcopy(self.x + x, self.y + y)<EOL>

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
-------
imgaug.Keypoint
    Keypoint object with new coordinates.


def draw_on_image(self, image, color=(<NUM_LIT:0>, <NUM_LIT:255>, <NUM_LIT:0>), alpha=<NUM_LIT:1.0>, size=<NUM_LIT:3>,<EOL>copy=True, raise_if_out_of_image=False):

if copy:<EOL><INDENT>image = np.copy(image)<EOL><DEDENT>if image.ndim == <NUM_LIT:2>:<EOL><INDENT>assert ia.is_single_number(color), (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (str(color),))<EOL><DEDENT>elif image.ndim == <NUM_LIT:3> and ia.is_single_number(color):<EOL><INDENT>color = [color] * image.shape[-<NUM_LIT:1>]<EOL><DEDENT>input_dtype = image.dtype<EOL>alpha_color = color<EOL>if alpha < <NUM_LIT>:<EOL><INDENT>return image<EOL><DEDENT>elif alpha > <NUM_LIT>:<EOL><INDENT>alpha = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>image = image.astype(np.float32, copy=False)<EOL>alpha_color = alpha * np.array(color)<EOL><DEDENT>height, width = image.shape[<NUM_LIT:0>:<NUM_LIT:2>]<EOL>y, x = self.y_int, self.x_int<EOL>x1 = max(x - size//<NUM_LIT:2>, <NUM_LIT:0>)<EOL>x2 = min(x + <NUM_LIT:1> + size//<NUM_LIT:2>, width)<EOL>y1 = max(y - size//<NUM_LIT:2>, <NUM_LIT:0>)<EOL>y2 = min(y + <NUM_LIT:1> + size//<NUM_LIT:2>, height)<EOL>x1_clipped, x2_clipped = np.clip([x1, x2], <NUM_LIT:0>, width)<EOL>y1_clipped, y2_clipped = np.clip([y1, y2], <NUM_LIT:0>, height)<EOL>x1_clipped_ooi = (x1_clipped < <NUM_LIT:0> or x1_clipped >= width)<EOL>x2_clipped_ooi = (x2_clipped < <NUM_LIT:0> or x2_clipped >= width+<NUM_LIT:1>)<EOL>y1_clipped_ooi = (y1_clipped < <NUM_LIT:0> or y1_clipped >= height)<EOL>y2_clipped_ooi = (y2_clipped < <NUM_LIT:0> or y2_clipped >= height+<NUM_LIT:1>)<EOL>x_ooi = (x1_clipped_ooi and x2_clipped_ooi)<EOL>y_ooi = (y1_clipped_ooi and y2_clipped_ooi)<EOL>x_zero_size = (x2_clipped - x1_clipped) < <NUM_LIT:1>  <EOL>y_zero_size = (y2_clipped - y1_clipped) < <NUM_LIT:1><EOL>if not x_ooi and not y_ooi and not x_zero_size and not y_zero_size:<EOL><INDENT>if alpha == <NUM_LIT:1>:<EOL><INDENT>image[y1_clipped:y2_clipped, x1_clipped:x2_clipped] = color<EOL><DEDENT>else:<EOL><INDENT>image[y1_clipped:y2_clipped, x1_clipped:x2_clipped] = (<EOL>(<NUM_LIT:1> - alpha)<EOL>* image[y1_clipped:y2_clipped, x1_clipped:x2_clipped]<EOL>+ alpha_color<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if raise_if_out_of_image:<EOL><INDENT>raise Exception(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (y, x, image.shape))<EOL><DEDENT><DEDENT>if image.dtype.name != input_dtype.name:<EOL><INDENT>if input_dtype.name == "<STR_LIT>":<EOL><INDENT>image = np.clip(image, <NUM_LIT:0>, <NUM_LIT:255>, out=image)<EOL><DEDENT>image = image.astype(input_dtype, copy=False)<EOL><DEDENT>return image<EOL>

Draw the keypoint onto a given image.

The keypoint is drawn as a square.

Parameters
----------
image : (H,W,3) ndarray
    The image onto which to draw the keypoint.

color : int or list of int or tuple of int or (3,) ndarray, optional
    The RGB color of the keypoint. If a single int ``C``, then that is
    equivalent to ``(C,C,C)``.

alpha : float, optional
    The opacity of the drawn keypoint, where ``1.0`` denotes a fully
    visible keypoint and ``0.0`` an invisible one.

size : int, optional
    The size of the keypoint. If set to ``S``, each square will have
    size ``S x S``.

copy : bool, optional
    Whether to copy the image before drawing the keypoint.

raise_if_out_of_image : bool, optional
    Whether to raise an exception if the keypoint is outside of the
    image.

Returns
-------
image : (H,W,3) ndarray
    Image with drawn keypoint.


def generate_similar_points_manhattan(self, nb_steps, step_size, return_array=False):

<EOL>points = np.zeros((nb_steps + <NUM_LIT:1> + nb_steps + <NUM_LIT:2>*(nb_steps**<NUM_LIT:2>), <NUM_LIT:2>), dtype=np.float32)<EOL>yy = np.linspace(self.y - nb_steps * step_size, self.y + nb_steps * step_size, nb_steps + <NUM_LIT:1> + nb_steps)<EOL>width = <NUM_LIT:1><EOL>nth_point = <NUM_LIT:0><EOL>for i_y, y in enumerate(yy):<EOL><INDENT>if width == <NUM_LIT:1>:<EOL><INDENT>xx = [self.x]<EOL><DEDENT>else:<EOL><INDENT>xx = np.linspace(self.x - (width-<NUM_LIT:1>)//<NUM_LIT:2> * step_size, self.x + (width-<NUM_LIT:1>)//<NUM_LIT:2> * step_size, width)<EOL><DEDENT>for x in xx:<EOL><INDENT>points[nth_point] = [x, y]<EOL>nth_point += <NUM_LIT:1><EOL><DEDENT>if i_y < nb_steps:<EOL><INDENT>width += <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>width -= <NUM_LIT:2><EOL><DEDENT><DEDENT>if return_array:<EOL><INDENT>return points<EOL><DEDENT>return [self.deepcopy(x=points[i, <NUM_LIT:0>], y=points[i, <NUM_LIT:1>]) for i in sm.xrange(points.shape[<NUM_LIT:0>])]<EOL>

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, right, bottom and left, resulting in four new
points. From these new points, the pattern is repeated. Overlapping points are ignored.

The resulting points have a shape similar to a square rotated by 45 degrees.

Parameters
----------
nb_steps : int
    The number of steps to move from the center point. nb_steps=1 results in a total of
    5 output points (1 center point + 4 neighbours).

step_size : number
    The step size to move from every point to its neighbours.

return_array : bool, optional
    Whether to return the generated points as a list of keypoints or an array
    of shape ``(N,2)``, where ``N`` is the number of generated points and the second axis contains
    the x- (first value) and y- (second value) coordinates.

Returns
-------
points : list of imgaug.Keypoint or (N,2) ndarray
    If return_array was False, then a list of Keypoint.
    Otherwise a numpy array of shape ``(N,2)``, where ``N`` is the number of generated points and
    the second axis contains the x- (first value) and y- (second value) coordinates.
    The center keypoint (the one on which this function was called) is always included.


return self.deepcopy(x=x, y=y)<EOL>

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, optional
    Coordinate of the keypoint on the y axis.
    If ``None``, the instance's value will be copied.

Returns
-------
imgaug.Keypoint
    Shallow copy.


x = self.x if x is None else x<EOL>y = self.y if y is None else y<EOL>return Keypoint(x=x, y=y)<EOL>

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, optional
    Coordinate of the keypoint on the y axis.
    If ``None``, the instance's value will be copied.

Returns
-------
imgaug.Keypoint
    Deep copy.


return len(self.keypoints) == <NUM_LIT:0><EOL>

Returns whether this object contains zero keypoints.

Returns
-------
result : bool
    True if this object contains zero keypoints.


shape = normalize_shape(image)<EOL>if shape[<NUM_LIT:0>:<NUM_LIT:2>] == self.shape[<NUM_LIT:0>:<NUM_LIT:2>]:<EOL><INDENT>return self.deepcopy()<EOL><DEDENT>else:<EOL><INDENT>keypoints = [kp.project(self.shape, shape) for kp in self.keypoints]<EOL>return self.deepcopy(keypoints, shape)<EOL><DEDENT>

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
-------
keypoints : imgaug.KeypointsOnImage
    Object containing all projected keypoints.


image = np.copy(image) if copy else image<EOL>for keypoint in self.keypoints:<EOL><INDENT>image = keypoint.draw_on_image(<EOL>image, color=color, alpha=alpha, size=size, copy=False,<EOL>raise_if_out_of_image=raise_if_out_of_image)<EOL><DEDENT>return image<EOL>

Draw all keypoints onto a given image.

Each keypoint is marked by a square of a chosen color and size.

Parameters
----------
image : (H,W,3) ndarray
    The image onto which to draw the keypoints.
    This image should usually have the same shape as
    set in KeypointsOnImage.shape.

color : int or list of int or tuple of int or (3,) ndarray, optional
    The RGB color of all keypoints. If a single int ``C``, then that is
    equivalent to ``(C,C,C)``.

alpha : float, optional
    The opacity of the drawn keypoint, where ``1.0`` denotes a fully
    visible keypoint and ``0.0`` an invisible one.

size : int, optional
    The size of each point. If set to ``C``, each square will have
    size ``C x C``.

copy : bool, optional
    Whether to copy the image before drawing the points.

raise_if_out_of_image : bool, optional
    Whether to raise an exception if any keypoint is outside of the image.

Returns
-------
image : (H,W,3) ndarray
    Image with drawn keypoints.


keypoints = [keypoint.shift(x=x, y=y) for keypoint in self.keypoints]<EOL>return self.deepcopy(keypoints)<EOL>

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
-------
out : KeypointsOnImage
    Keypoints after moving them.


return self.to_xy_array()<EOL>

Convert the coordinates of all keypoints in this object to an array of shape (N,2).

Returns
-------
result : (N, 2) ndarray
    Where N is the number of keypoints. Each first value is the
    x coordinate, each second value is the y coordinate.


result = np.zeros((len(self.keypoints), <NUM_LIT:2>), dtype=np.float32)<EOL>for i, keypoint in enumerate(self.keypoints):<EOL><INDENT>result[i, <NUM_LIT:0>] = keypoint.x<EOL>result[i, <NUM_LIT:1>] = keypoint.y<EOL><DEDENT>return result<EOL>

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.


return KeypointsOnImage.from_xy_array(coords, shape)<EOL>

Convert an array (N,2) with a given image shape to a KeypointsOnImage object.

Parameters
----------
coords : (N, 2) ndarray
    Coordinates of ``N`` keypoints on the original image.
    Each first entry ``coords[i, 0]`` is expected to be the x coordinate.
    Each second entry ``coords[i, 1]`` is expected to be the y coordinate.

shape : tuple
    Shape tuple of the image on which the keypoints are placed.

Returns
-------
KeypointsOnImage
    KeypointsOnImage object that contains all keypoints from the array.


@classmethod<EOL><INDENT>def from_xy_array(cls, xy, shape):<DEDENT>

keypoints = [Keypoint(x=coord[<NUM_LIT:0>], y=coord[<NUM_LIT:1>]) for coord in xy]<EOL>return KeypointsOnImage(keypoints, shape)<EOL>

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.

shape : tuple of int or ndarray
    Shape tuple of the image on which the keypoints are placed.

Returns
-------
KeypointsOnImage
    KeypointsOnImage object that contains all keypoints from the array.


ia.do_assert(len(self.keypoints) > <NUM_LIT:0>)<EOL>height, width = self.shape[<NUM_LIT:0>:<NUM_LIT:2>]<EOL>image = np.zeros((height, width, len(self.keypoints)), dtype=np.uint8)<EOL>ia.do_assert(size % <NUM_LIT:2> != <NUM_LIT:0>)<EOL>sizeh = max(<NUM_LIT:0>, (size-<NUM_LIT:1>)//<NUM_LIT:2>)<EOL>for i, keypoint in enumerate(self.keypoints):<EOL><INDENT>y = keypoint.y_int<EOL>x = keypoint.x_int<EOL>x1 = np.clip(x - sizeh, <NUM_LIT:0>, width-<NUM_LIT:1>)<EOL>x2 = np.clip(x + sizeh + <NUM_LIT:1>, <NUM_LIT:0>, width)<EOL>y1 = np.clip(y - sizeh, <NUM_LIT:0>, height-<NUM_LIT:1>)<EOL>y2 = np.clip(y + sizeh + <NUM_LIT:1>, <NUM_LIT:0>, height)<EOL>if x1 < x2 and y1 < y2:<EOL><INDENT>image[y1:y2, x1:x2, i] = <NUM_LIT><EOL><DEDENT>if <NUM_LIT:0> <= y < height and <NUM_LIT:0> <= x < width:<EOL><INDENT>image[y, x, i] = <NUM_LIT:255><EOL><DEDENT><DEDENT>return image<EOL>

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 the
augmentation of images.

Parameters
-------
size : int
    Size of each (squared) point.

Returns
-------
image : (H,W,N) ndarray
    Image in which the keypoints are marked. H is the height,
    defined in KeypointsOnImage.shape[0] (analogous W). N is the
    number of keypoints.


@staticmethod<EOL><INDENT>def from_keypoint_image(image, if_not_found_coords={"<STR_LIT:x>": -<NUM_LIT:1>, "<STR_LIT:y>": -<NUM_LIT:1>}, threshold=<NUM_LIT:1>, nb_channels=None): <DEDENT>

ia.do_assert(len(image.shape) == <NUM_LIT:3>)<EOL>height, width, nb_keypoints = image.shape<EOL>drop_if_not_found = False<EOL>if if_not_found_coords is None:<EOL><INDENT>drop_if_not_found = True<EOL>if_not_found_x = -<NUM_LIT:1><EOL>if_not_found_y = -<NUM_LIT:1><EOL><DEDENT>elif isinstance(if_not_found_coords, (tuple, list)):<EOL><INDENT>ia.do_assert(len(if_not_found_coords) == <NUM_LIT:2>)<EOL>if_not_found_x = if_not_found_coords[<NUM_LIT:0>]<EOL>if_not_found_y = if_not_found_coords[<NUM_LIT:1>]<EOL><DEDENT>elif isinstance(if_not_found_coords, dict):<EOL><INDENT>if_not_found_x = if_not_found_coords["<STR_LIT:x>"]<EOL>if_not_found_y = if_not_found_coords["<STR_LIT:y>"]<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>" % (<EOL>type(if_not_found_coords),))<EOL><DEDENT>keypoints = []<EOL>for i in sm.xrange(nb_keypoints):<EOL><INDENT>maxidx_flat = np.argmax(image[..., i])<EOL>maxidx_ndim = np.unravel_index(maxidx_flat, (height, width))<EOL>found = (image[maxidx_ndim[<NUM_LIT:0>], maxidx_ndim[<NUM_LIT:1>], i] >= threshold)<EOL>if found:<EOL><INDENT>keypoints.append(Keypoint(x=maxidx_ndim[<NUM_LIT:1>], y=maxidx_ndim[<NUM_LIT:0>]))<EOL><DEDENT>else:<EOL><INDENT>if drop_if_not_found:<EOL><INDENT>pass  <EOL><DEDENT>else:<EOL><INDENT>keypoints.append(Keypoint(x=if_not_found_x, y=if_not_found_y))<EOL><DEDENT><DEDENT><DEDENT>out_shape = (height, width)<EOL>if nb_channels is not None:<EOL><INDENT>out_shape += (nb_channels,)<EOL><DEDENT>return KeypointsOnImage(keypoints, shape=out_shape)<EOL>

Converts an image generated by ``to_keypoint_image()`` back to a KeypointsOnImage object.

Parameters
----------
image : (H,W,N) ndarray
    The keypoints image. N is the number of keypoints.

if_not_found_coords : tuple or list or dict or None, optional
    Coordinates to use for keypoints that cannot be found in `image`.
    If this is a list/tuple, it must have two integer values.
    If it is a dictionary, it must have the keys ``x`` and ``y`` with
    each containing one integer value.
    If this is None, then the keypoint will not be added to the final
    KeypointsOnImage object.

threshold : int, optional
    The search for keypoints works by searching for the argmax in
    each channel. This parameters contains the minimum value that
    the max must have in order to be viewed as a keypoint.

nb_channels : None or int, optional
    Number of channels of the image on which the keypoints are placed.
    Some keypoint augmenters require that information.
    If set to None, the keypoint's shape will be set
    to ``(height, width)``, otherwise ``(height, width, nb_channels)``.

Returns
-------
out : KeypointsOnImage
    The extracted keypoints.


ia.do_assert(len(self.keypoints) > <NUM_LIT:0>)<EOL>height, width = self.shape[<NUM_LIT:0>:<NUM_LIT:2>]<EOL>distance_maps = np.zeros((height, width, len(self.keypoints)), dtype=np.float32)<EOL>yy = np.arange(<NUM_LIT:0>, height)<EOL>xx = np.arange(<NUM_LIT:0>, width)<EOL>grid_xx, grid_yy = np.meshgrid(xx, yy)<EOL>for i, keypoint in enumerate(self.keypoints):<EOL><INDENT>y, x = keypoint.y, keypoint.x<EOL>distance_maps[:, :, i] = (grid_xx - x) ** <NUM_LIT:2> + (grid_yy - y) ** <NUM_LIT:2><EOL><DEDENT>distance_maps = np.sqrt(distance_maps)<EOL>if inverted:<EOL><INDENT>return <NUM_LIT:1>/(distance_maps+<NUM_LIT:1>)<EOL><DEDENT>return distance_maps<EOL>

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 augmenting keypoints with a method that only supports
the augmentation of images.

Parameters
-------
inverted : bool, optional
    If True, inverted distance maps are returned where each distance value d is replaced
    by ``d/(d+1)``, i.e. the distance maps have values in the range ``(0.0, 1.0]`` with 1.0
    denoting exactly the position of the respective keypoint.

Returns
-------
distance_maps : (H,W,K) ndarray
    A ``float32`` array containing ``K`` distance maps for ``K`` keypoints. Each location
    ``(y, x, k)`` in the array denotes the euclidean distance at ``(y, x)`` to the ``k``-th keypoint.
    In inverted mode the distance ``d`` is replaced by ``d/(d+1)``. The height and width
    of the array match the height and width in ``KeypointsOnImage.shape``.


@staticmethod<EOL><INDENT>def from_distance_maps(distance_maps, inverted=False, if_not_found_coords={"<STR_LIT:x>": -<NUM_LIT:1>, "<STR_LIT:y>": -<NUM_LIT:1>}, threshold=None, <EOL>nb_channels=None):<DEDENT>

ia.do_assert(len(distance_maps.shape) == <NUM_LIT:3>)<EOL>height, width, nb_keypoints = distance_maps.shape<EOL>drop_if_not_found = False<EOL>if if_not_found_coords is None:<EOL><INDENT>drop_if_not_found = True<EOL>if_not_found_x = -<NUM_LIT:1><EOL>if_not_found_y = -<NUM_LIT:1><EOL><DEDENT>elif isinstance(if_not_found_coords, (tuple, list)):<EOL><INDENT>ia.do_assert(len(if_not_found_coords) == <NUM_LIT:2>)<EOL>if_not_found_x = if_not_found_coords[<NUM_LIT:0>]<EOL>if_not_found_y = if_not_found_coords[<NUM_LIT:1>]<EOL><DEDENT>elif isinstance(if_not_found_coords, dict):<EOL><INDENT>if_not_found_x = if_not_found_coords["<STR_LIT:x>"]<EOL>if_not_found_y = if_not_found_coords["<STR_LIT:y>"]<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>" % (<EOL>type(if_not_found_coords),))<EOL><DEDENT>keypoints = []<EOL>for i in sm.xrange(nb_keypoints):<EOL><INDENT>if inverted:<EOL><INDENT>hitidx_flat = np.argmax(distance_maps[..., i])<EOL><DEDENT>else:<EOL><INDENT>hitidx_flat = np.argmin(distance_maps[..., i])<EOL><DEDENT>hitidx_ndim = np.unravel_index(hitidx_flat, (height, width))<EOL>if not inverted and threshold is not None:<EOL><INDENT>found = (distance_maps[hitidx_ndim[<NUM_LIT:0>], hitidx_ndim[<NUM_LIT:1>], i] < threshold)<EOL><DEDENT>elif inverted and threshold is not None:<EOL><INDENT>found = (distance_maps[hitidx_ndim[<NUM_LIT:0>], hitidx_ndim[<NUM_LIT:1>], i] >= threshold)<EOL><DEDENT>else:<EOL><INDENT>found = True<EOL><DEDENT>if found:<EOL><INDENT>keypoints.append(Keypoint(x=hitidx_ndim[<NUM_LIT:1>], y=hitidx_ndim[<NUM_LIT:0>]))<EOL><DEDENT>else:<EOL><INDENT>if drop_if_not_found:<EOL><INDENT>pass  <EOL><DEDENT>else:<EOL><INDENT>keypoints.append(Keypoint(x=if_not_found_x, y=if_not_found_y))<EOL><DEDENT><DEDENT><DEDENT>out_shape = (height, width)<EOL>if nb_channels is not None:<EOL><INDENT>out_shape += (nb_channels,)<EOL><DEDENT>return KeypointsOnImage(keypoints, shape=out_shape)<EOL>

Converts maps generated by ``to_distance_maps()`` back to a KeypointsOnImage object.

Parameters
----------
distance_maps : (H,W,N) ndarray
    The distance maps. N is the number of keypoints.

inverted : bool, optional
    Whether the given distance maps were generated in inverted or normal mode.

if_not_found_coords : tuple or list or dict or None, optional
    Coordinates to use for keypoints that cannot be found in ``distance_maps``.
    If this is a list/tuple, it must have two integer values.
    If it is a dictionary, it must have the keys ``x`` and ``y``, with each
    containing one integer value.
    If this is None, then the keypoint will not be added to the final
    KeypointsOnImage object.

threshold : float, optional
    The search for keypoints works by searching for the argmin (non-inverted) or
    argmax (inverted) in each channel. This parameters contains the maximum (non-inverted)
    or minimum (inverted) value to accept in order to view a hit as a keypoint.
    Use None to use no min/max.

nb_channels : None or int, optional
    Number of channels of the image on which the keypoints are placed.
    Some keypoint augmenters require that information.
    If set to None, the keypoint's shape will be set
    to ``(height, width)``, otherwise ``(height, width, nb_channels)``.

Returns
-------
imgaug.KeypointsOnImage
    The extracted keypoints.


def copy(self, keypoints=None, shape=None):

result = copy.copy(self)<EOL>if keypoints is not None:<EOL><INDENT>result.keypoints = keypoints<EOL><DEDENT>if shape is not None:<EOL><INDENT>result.shape = shape<EOL><DEDENT>return result<EOL>

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 copied.

shape : tuple of int, optional
    The shape of the image on which the keypoints are placed.
    If ``None``, the instance's shape will be copied.

Returns
-------
imgaug.KeypointsOnImage
    Shallow copy.


def deepcopy(self, keypoints=None, shape=None):

<EOL>if keypoints is None:<EOL><INDENT>keypoints = [kp.deepcopy() for kp in self.keypoints]<EOL><DEDENT>if shape is None:<EOL><INDENT>shape = tuple(self.shape)<EOL><DEDENT>return KeypointsOnImage(keypoints, shape)<EOL>

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 be copied.

shape : tuple of int, optional
    The shape of the image on which the keypoints are placed.
    If ``None``, the instance's shape will be copied.

Returns
-------
imgaug.KeypointsOnImage
    Deep copy.


<EOL>if ia.is_np_array(coords):<EOL><INDENT>if coords.dtype.name != "<STR_LIT>":<EOL><INDENT>coords = coords.astype(np.float32)<EOL><DEDENT><DEDENT>elif len(coords) == <NUM_LIT:0>:<EOL><INDENT>coords = np.zeros((<NUM_LIT:0>, <NUM_LIT:2>), dtype=np.float32)<EOL><DEDENT>else:<EOL><INDENT>assert ia.is_iterable(coords), (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (type(coords),))<EOL>assert all([len(coords_i) == <NUM_LIT:2> for coords_i in coords]), (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (str(coords),))<EOL>coords = np.float32(coords)<EOL><DEDENT>assert coords.ndim == <NUM_LIT:2> and coords.shape[-<NUM_LIT:1>] == <NUM_LIT:2>, (<EOL>"<STR_LIT>" % (<EOL>coords.shape,))<EOL>self.coords = coords<EOL>self.label = label<EOL>


if len(self.coords) == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>return np.sum(self.compute_neighbour_distances())<EOL>

Get the total euclidean length of the line string.

Returns
-------
float
    The length based on euclidean distance.


return self.coords[:, <NUM_LIT:0>]<EOL>

Get an array of x-coordinates of all points of the line string.


return self.coords[:, <NUM_LIT:1>]<EOL>

Get an array of y-coordinates of all points of the line string.


return np.round(self.xx).astype(np.int32)<EOL>

Get an array of discrete x-coordinates of all points.


return np.round(self.yy).astype(np.int32)<EOL>

Get an array of discrete y-coordinates of all points.


if len(self.coords) <= <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>return np.max(self.yy) - np.min(self.yy)<EOL>

Get the height of a bounding box encapsulating the line.


if len(self.coords) <= <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>return np.max(self.xx) - np.min(self.xx)<EOL>

Get the width of a bounding box encapsulating the line.


if len(self.coords) == <NUM_LIT:0>:<EOL><INDENT>return np.zeros((<NUM_LIT:0>,), dtype=bool)<EOL><DEDENT>shape = normalize_shape(image)<EOL>height, width = shape[<NUM_LIT:0>:<NUM_LIT:2>]<EOL>x_within = np.logical_and(<NUM_LIT:0> <= self.xx, self.xx < width)<EOL>y_within = np.logical_and(<NUM_LIT:0> <= self.yy, self.yy < height)<EOL>return np.logical_and(x_within, y_within)<EOL>

Get for each point whether it is inside of the given image plane.

Parameters
----------
image : ndarray or tuple of int
    Either an image with shape ``(H,W,[C])`` or a tuple denoting
    such an image shape.

Returns
-------
ndarray
    Boolean array with one value per point indicating whether it is
    inside of the provided image plane (``True``) or not (``False``).


if len(self.coords) <= <NUM_LIT:1>:<EOL><INDENT>return np.zeros((<NUM_LIT:0>,), dtype=np.float32)<EOL><DEDENT>return np.sqrt(<EOL>np.sum(<EOL>(self.coords[:-<NUM_LIT:1>, :] - self.coords[<NUM_LIT:1>:, :]) ** <NUM_LIT:2>,<EOL>axis=<NUM_LIT:1><EOL>)<EOL>)<EOL>

Get the euclidean distance between each two consecutive points.

Returns
-------
ndarray
    Euclidean distances between point pairs.
    Same order as in `coords`. For ``N`` points, ``N-1`` distances
    are returned.


def compute_pointwise_distances(self, other, default=None):

import shapely.geometry<EOL>from .kps import Keypoint<EOL>if isinstance(other, Keypoint):<EOL><INDENT>other = shapely.geometry.Point((other.x, other.y))<EOL><DEDENT>elif isinstance(other, LineString):<EOL><INDENT>if len(other.coords) == <NUM_LIT:0>:<EOL><INDENT>return default<EOL><DEDENT>elif len(other.coords) == <NUM_LIT:1>:<EOL><INDENT>other = shapely.geometry.Point(other.coords[<NUM_LIT:0>, :])<EOL><DEDENT>else:<EOL><INDENT>other = shapely.geometry.LineString(other.coords)<EOL><DEDENT><DEDENT>elif isinstance(other, tuple):<EOL><INDENT>assert len(other) == <NUM_LIT:2><EOL>other = shapely.geometry.Point(other)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>("<STR_LIT>"<EOL>+ "<STR_LIT>") % (type(other),))<EOL><DEDENT>return [shapely.geometry.Point(point).distance(other)<EOL>for point in self.coords]<EOL>

Compute the minimal distance between each point on self and other.

Parameters
----------
other : tuple of number \
        or imgaug.augmentables.kps.Keypoint \
        or imgaug.augmentables.LineString
    Other object to which to compute the distances.

default
    Value to return if `other` contains no points.

Returns
-------
list of float
    Distances to `other` or `default` if not distance could be computed.


def compute_distance(self, other, default=None):

<EOL>distances = self.compute_pointwise_distances(other, default=[])<EOL>if len(distances) == <NUM_LIT:0>:<EOL><INDENT>return default<EOL><DEDENT>return min(distances)<EOL>

Compute the minimal distance between the line string and `other`.

Parameters
----------
other : tuple of number \
        or imgaug.augmentables.kps.Keypoint \
        or imgaug.augmentables.LineString
    Other object to which to compute the distance.

default
    Value to return if this line string or `other` contain no points.

Returns
-------
float
    Distance to `other` or `default` if not distance could be computed.


def contains(self, other, max_distance=<NUM_LIT>):

return self.compute_distance(other, default=np.inf) < max_distance<EOL>

Estimate whether the bounding box contains a point.

Parameters
----------
other : tuple of number or imgaug.augmentables.kps.Keypoint
    Point to check for.

max_distance : float
    Maximum allowed euclidean distance between the point and the
    closest point on the line. If the threshold is exceeded, the point
    is not considered to be contained in the line.

Returns
-------
bool
    True if the point is contained in the line string, False otherwise.
    It is contained if its distance to the line or any of its points
    is below a threshold.


coords_proj = project_coords(self.coords, from_shape, to_shape)<EOL>return self.copy(coords=coords_proj)<EOL>

Project the line string onto a differently shaped image.

E.g. if a point of the line string 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
position will be ``(x=20, y=40)``.

This is intended for cases where the original image is resized.
It cannot be used for more complex changes (e.g. padding, cropping).

Parameters
----------
from_shape : tuple of int or ndarray
    Shape of the original image. (Before resize.)

to_shape : tuple of int or ndarray
    Shape of the new image. (After resize.)

Returns
-------
out : imgaug.augmentables.lines.LineString
    Line string with new coordinates.


def is_fully_within_image(self, image, default=False):

if len(self.coords) == <NUM_LIT:0>:<EOL><INDENT>return default<EOL><DEDENT>return np.all(self.get_pointwise_inside_image_mask(image))<EOL>

Estimate whether the line string is fully inside the image area.

Parameters
----------
image : ndarray or tuple of int
    Either an image with shape ``(H,W,[C])`` or a tuple denoting
    such an image shape.

default
    Default value to return if the line string contains no points.

Returns
-------
bool
    True if the line string is fully inside the image area.
    False otherwise.


def is_partly_within_image(self, image, default=False):

if len(self.coords) == <NUM_LIT:0>:<EOL><INDENT>return default<EOL><DEDENT>mask = self.get_pointwise_inside_image_mask(image)<EOL>if np.any(mask):<EOL><INDENT>return True<EOL><DEDENT>return len(self.clip_out_of_image(image)) > <NUM_LIT:0><EOL>

Estimate whether the line string is at least partially inside the image.

Parameters
----------
image : ndarray or tuple of int
    Either an image with shape ``(H,W,[C])`` or a tuple denoting
    such an image shape.

default
    Default value to return if the line string contains no points.

Returns
-------
bool
    True if the line string is at least partially inside the image area.
    False otherwise.


def is_out_of_image(self, image, fully=True, partly=False, default=True):

if len(self.coords) == <NUM_LIT:0>:<EOL><INDENT>return default<EOL><DEDENT>if self.is_fully_within_image(image):<EOL><INDENT>return False<EOL><DEDENT>elif self.is_partly_within_image(image):<EOL><INDENT>return partly<EOL><DEDENT>else:<EOL><INDENT>return fully<EOL><DEDENT>

Estimate whether the line is partially/fully outside of the image area.

Parameters
----------
image : ndarray or tuple of int
    Either an image with shape ``(H,W,[C])`` or a tuple denoting
    such an image shape.

fully : bool, optional
    Whether to return True if the bounding box is fully outside fo the
    image area.

partly : bool, optional
    Whether to return True if the bounding box is at least partially
    outside fo the image area.

default
    Default value to return if the line string contains no points.

Returns
-------
bool
    `default` if the line string has no points.
    True if the line string is partially/fully outside of the image
    area, depending on defined parameters.
    False otherwise.


if len(self.coords) == <NUM_LIT:0>:<EOL><INDENT>return []<EOL><DEDENT>inside_image_mask = self.get_pointwise_inside_image_mask(image)<EOL>ooi_mask = ~inside_image_mask<EOL>if len(self.coords) == <NUM_LIT:1>:<EOL><INDENT>if not np.any(inside_image_mask):<EOL><INDENT>return []<EOL><DEDENT>return [self.copy()]<EOL><DEDENT>if np.all(inside_image_mask):<EOL><INDENT>return [self.copy()]<EOL><DEDENT>height, width = normalize_shape(image)[<NUM_LIT:0>:<NUM_LIT:2>]<EOL>eps = <NUM_LIT><EOL>edges = [<EOL>LineString([(<NUM_LIT:0.0>, <NUM_LIT:0.0>), (width - eps, <NUM_LIT:0.0>)]),<EOL>LineString([(width - eps, <NUM_LIT:0.0>), (width - eps, height - eps)]),<EOL>LineString([(width - eps, height - eps), (<NUM_LIT:0.0>, height - eps)]),<EOL>LineString([(<NUM_LIT:0.0>, height - eps), (<NUM_LIT:0.0>, <NUM_LIT:0.0>)])<EOL>]<EOL>intersections = self.find_intersections_with(edges)<EOL>points = []<EOL>gen = enumerate(zip(self.coords[:-<NUM_LIT:1>], self.coords[<NUM_LIT:1>:],<EOL>ooi_mask[:-<NUM_LIT:1>], ooi_mask[<NUM_LIT:1>:],<EOL>intersections))<EOL>for i, (line_start, line_end, ooi_start, ooi_end, inter_line) in gen:<EOL><INDENT>points.append((line_start, False, ooi_start))<EOL>for p_inter in inter_line:<EOL><INDENT>points.append((p_inter, True, False))<EOL><DEDENT>is_last = (i == len(self.coords) - <NUM_LIT:2>)<EOL>if is_last and not ooi_end:<EOL><INDENT>points.append((line_end, False, ooi_end))<EOL><DEDENT><DEDENT>lines = []<EOL>line = []<EOL>for i, (coord, was_added, ooi) in enumerate(points):<EOL><INDENT>if ooi:<EOL><INDENT>if len(line) > <NUM_LIT:0>:<EOL><INDENT>lines.append(line)<EOL>line = []<EOL><DEDENT>continue<EOL><DEDENT>if not was_added:<EOL><INDENT>line.append(coord)<EOL><DEDENT>else:<EOL><INDENT>is_last_point = (i == len(points)-<NUM_LIT:1>)<EOL>is_next_ooi = (not is_last_point<EOL>and bool(points[i+<NUM_LIT:1>][<NUM_LIT:2>]) is True)<EOL>p_prev = line[-<NUM_LIT:1>] if len(line) > <NUM_LIT:0> else None<EOL>p_next = None<EOL>if not is_last_point and not is_next_ooi:<EOL><INDENT>p_next = points[i+<NUM_LIT:1>][<NUM_LIT:0>]<EOL><DEDENT>dist_prev = None<EOL>dist_next = None<EOL>if p_prev is not None:<EOL><INDENT>dist_prev = np.linalg.norm(<EOL>np.float32(coord) - np.float32(p_prev))<EOL><DEDENT>if p_next is not None:<EOL><INDENT>dist_next = np.linalg.norm(<EOL>np.float32(coord) - np.float32(p_next))<EOL><DEDENT>dist_prev_ok = (dist_prev is None or dist_prev > <NUM_LIT>)<EOL>dist_next_ok = (dist_next is None or dist_next > <NUM_LIT>)<EOL>if dist_prev_ok and dist_next_ok:<EOL><INDENT>line.append(coord)<EOL><DEDENT><DEDENT><DEDENT>if len(line) > <NUM_LIT:0>:<EOL><INDENT>lines.append(line)<EOL><DEDENT>lines = [line for line in lines if len(line) > <NUM_LIT:0>]<EOL>return [self.deepcopy(coords=line) for line in lines]<EOL>

Clip off all parts of the line_string that are outside of the image.

Parameters
----------
image : ndarray or tuple of int
    Either an image with shape ``(H,W,[C])`` or a tuple denoting
    such an image shape.

Returns
-------
list of imgaug.augmentables.lines.LineString
    Line strings, clipped to the image shape.
    The result may contain any number of line strins, including zero.


import shapely.geometry<EOL>geom = _convert_var_to_shapely_geometry(other)<EOL>result = []<EOL>for p_start, p_end in zip(self.coords[:-<NUM_LIT:1>], self.coords[<NUM_LIT:1>:]):<EOL><INDENT>ls = shapely.geometry.LineString([p_start, p_end])<EOL>intersections = ls.intersection(geom)<EOL>intersections = list(_flatten_shapely_collection(intersections))<EOL>intersections_points = []<EOL>for inter in intersections:<EOL><INDENT>if isinstance(inter, shapely.geometry.linestring.LineString):<EOL><INDENT>inter_start = (inter.coords[<NUM_LIT:0>][<NUM_LIT:0>], inter.coords[<NUM_LIT:0>][<NUM_LIT:1>])<EOL>inter_end = (inter.coords[-<NUM_LIT:1>][<NUM_LIT:0>], inter.coords[-<NUM_LIT:1>][<NUM_LIT:1>])<EOL>intersections_points.extend([inter_start, inter_end])<EOL><DEDENT>else:<EOL><INDENT>assert isinstance(inter, shapely.geometry.point.Point), (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (type(inter),))<EOL>intersections_points.append((inter.x, inter.y))<EOL><DEDENT><DEDENT>inter_sorted = sorted(<EOL>intersections_points,<EOL>key=lambda p: np.linalg.norm(np.float32(p) - p_start)<EOL>)<EOL>result.append(inter_sorted)<EOL><DEDENT>return result<EOL>

Find all intersection points between the line string and `other`.

Parameters
----------
other : tuple of number or list of tuple of number or \
        list of LineString or LineString
    The other geometry to use during intersection tests.

Returns
-------
list of list of tuple of number
    All intersection points. One list per pair of consecutive start
    and end point, i.e. `N-1` lists of `N` points. Each list may
    be empty or may contain multiple points.


def shift(self, top=None, right=None, bottom=None, left=None):

top = top if top is not None else <NUM_LIT:0><EOL>right = right if right is not None else <NUM_LIT:0><EOL>bottom = bottom if bottom is not None else <NUM_LIT:0><EOL>left = left if left is not None else <NUM_LIT:0><EOL>coords = np.copy(self.coords)<EOL>coords[:, <NUM_LIT:0>] += left - right<EOL>coords[:, <NUM_LIT:1>] += top - bottom<EOL>return self.copy(coords=coords)<EOL>

Shift/move the line string from one or more image sides.

Parameters
----------
top : None or int, optional
    Amount of pixels by which to shift the bounding box from the
    top.

right : None or int, optional
    Amount of pixels by which to shift the bounding box from the
    right.

bottom : None or int, optional
    Amount of pixels by which to shift the bounding box from the
    bottom.

left : None or int, optional
    Amount of pixels by which to shift the bounding box from the
    left.

Returns
-------
result : imgaug.augmentables.lines.LineString
    Shifted line string.


def draw_mask(self, image_shape, size_lines=<NUM_LIT:1>, size_points=<NUM_LIT:0>,<EOL>raise_if_out_of_image=False):

heatmap = self.draw_heatmap_array(<EOL>image_shape,<EOL>alpha_lines=<NUM_LIT:1.0>, alpha_points=<NUM_LIT:1.0>,<EOL>size_lines=size_lines, size_points=size_points,<EOL>antialiased=False,<EOL>raise_if_out_of_image=raise_if_out_of_image)<EOL>return heatmap > <NUM_LIT:0.5><EOL>

Draw this line segment as a binary image mask.

Parameters
----------
image_shape : tuple of int
    The shape of the image onto which to draw the line mask.

size_lines : int, optional
    Thickness of the line segments.

size_points : int, optional
    Size of the points in pixels.

raise_if_out_of_image : bool, optional
    Whether to raise an error if the line string is fully
    outside of the image. If set to False, no error will be raised and
    only the parts inside the image will be drawn.

Returns
-------
ndarray
    Boolean line mask of shape `image_shape` (no channel axis).


def draw_lines_heatmap_array(self, image_shape, alpha=<NUM_LIT:1.0>,<EOL>size=<NUM_LIT:1>, antialiased=True,<EOL>raise_if_out_of_image=False):

assert len(image_shape) == <NUM_LIT:2> or (<EOL>len(image_shape) == <NUM_LIT:3> and image_shape[-<NUM_LIT:1>] == <NUM_LIT:1>), (<EOL>"<STR_LIT>" % (<EOL>image_shape,))<EOL>arr = self.draw_lines_on_image(<EOL>np.zeros(image_shape, dtype=np.uint8),<EOL>color=<NUM_LIT:255>, alpha=alpha, size=size,<EOL>antialiased=antialiased,<EOL>raise_if_out_of_image=raise_if_out_of_image<EOL>)<EOL>return arr.astype(np.float32) / <NUM_LIT><EOL>

Draw the line segments of the line string as a heatmap array.

Parameters
----------
image_shape : tuple of int
    The shape of the image onto which to draw the line mask.

alpha : float, optional
    Opacity of the line string. Higher values denote a more visible
    line string.

size : int, optional
    Thickness of the line segments.

antialiased : bool, optional
    Whether to draw the line with anti-aliasing activated.

raise_if_out_of_image : bool, optional
    Whether to raise an error if the line string is fully
    outside of the image. If set to False, no error will be raised and
    only the parts inside the image will be drawn.

Returns
-------
ndarray
    Float array of shape `image_shape` (no channel axis) with drawn
    line string. All values are in the interval ``[0.0, 1.0]``.


def draw_points_heatmap_array(self, image_shape, alpha=<NUM_LIT:1.0>,<EOL>size=<NUM_LIT:1>, raise_if_out_of_image=False):

assert len(image_shape) == <NUM_LIT:2> or (<EOL>len(image_shape) == <NUM_LIT:3> and image_shape[-<NUM_LIT:1>] == <NUM_LIT:1>), (<EOL>"<STR_LIT>" % (<EOL>image_shape,))<EOL>arr = self.draw_points_on_image(<EOL>np.zeros(image_shape, dtype=np.uint8),<EOL>color=<NUM_LIT:255>, alpha=alpha, size=size,<EOL>raise_if_out_of_image=raise_if_out_of_image<EOL>)<EOL>return arr.astype(np.float32) / <NUM_LIT><EOL>

Draw the points of the line string as a heatmap array.

Parameters
----------
image_shape : tuple of int
    The shape of the image onto which to draw the point mask.

alpha : float, optional
    Opacity of the line string points. Higher values denote a more
    visible points.

size : int, optional
    Size of the points in pixels.

raise_if_out_of_image : bool, optional
    Whether to raise an error if the line string is fully
    outside of the image. If set to False, no error will be raised and
    only the parts inside the image will be drawn.

Returns
-------
ndarray
    Float array of shape `image_shape` (no channel axis) with drawn
    line string points. All values are in the interval ``[0.0, 1.0]``.


def draw_heatmap_array(self, image_shape, alpha_lines=<NUM_LIT:1.0>, alpha_points=<NUM_LIT:1.0>,<EOL>size_lines=<NUM_LIT:1>, size_points=<NUM_LIT:0>, antialiased=True,<EOL>raise_if_out_of_image=False):

heatmap_lines = self.draw_lines_heatmap_array(<EOL>image_shape,<EOL>alpha=alpha_lines,<EOL>size=size_lines,<EOL>antialiased=antialiased,<EOL>raise_if_out_of_image=raise_if_out_of_image)<EOL>if size_points <= <NUM_LIT:0>:<EOL><INDENT>return heatmap_lines<EOL><DEDENT>heatmap_points = self.draw_points_heatmap_array(<EOL>image_shape,<EOL>alpha=alpha_points,<EOL>size=size_points,<EOL>raise_if_out_of_image=raise_if_out_of_image)<EOL>heatmap = np.dstack([heatmap_lines, heatmap_points])<EOL>return np.max(heatmap, axis=<NUM_LIT:2>)<EOL>

Draw the line segments and points of the line string as a heatmap array.

Parameters
----------
image_shape : tuple of int
    The shape of the image onto which to draw the line mask.

alpha_lines : float, optional
    Opacity of the line string. Higher values denote a more visible
    line string.

alpha_points : float, optional
    Opacity of the line string points. Higher values denote a more
    visible points.

size_lines : int, optional
    Thickness of the line segments.

size_points : int, optional
    Size of the points in pixels.

antialiased : bool, optional
    Whether to draw the line with anti-aliasing activated.

raise_if_out_of_image : bool, optional
    Whether to raise an error if the line string is fully
    outside of the image. If set to False, no error will be raised and
    only the parts inside the image will be drawn.

Returns
-------
ndarray
    Float array of shape `image_shape` (no channel axis) with drawn
    line segments and points. All values are in the
    interval ``[0.0, 1.0]``.


def draw_lines_on_image(self, image, color=(<NUM_LIT:0>, <NUM_LIT:255>, <NUM_LIT:0>),<EOL>alpha=<NUM_LIT:1.0>, size=<NUM_LIT:3>,<EOL>antialiased=True,<EOL>raise_if_out_of_image=False):

from .. import dtypes as iadt<EOL>from ..augmenters import blend as blendlib<EOL>image_was_empty = False<EOL>if isinstance(image, tuple):<EOL><INDENT>image_was_empty = True<EOL>image = np.zeros(image, dtype=np.uint8)<EOL><DEDENT>assert image.ndim in [<NUM_LIT:2>, <NUM_LIT:3>], (<EOL>("<STR_LIT>"<EOL>+ "<STR_LIT>") % (image.shape,))<EOL>if len(self.coords) <= <NUM_LIT:1> or alpha < <NUM_LIT:0> + <NUM_LIT> or size < <NUM_LIT:1>:<EOL><INDENT>return np.copy(image)<EOL><DEDENT>if raise_if_out_of_imageand self.is_out_of_image(image, partly=False, fully=True):<EOL><INDENT>raise Exception(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (<EOL>self.__str__(), image.shape))<EOL><DEDENT>if image.ndim == <NUM_LIT:2>:<EOL><INDENT>assert ia.is_single_number(color), (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (str(color),))<EOL>color = [color]<EOL><DEDENT>elif image.ndim == <NUM_LIT:3> and ia.is_single_number(color):<EOL><INDENT>color = [color] * image.shape[-<NUM_LIT:1>]<EOL><DEDENT>image = image.astype(np.float32)<EOL>height, width = image.shape[<NUM_LIT:0>:<NUM_LIT:2>]<EOL>lines = []<EOL>for line_start, line_end in zip(self.coords[:-<NUM_LIT:1>], self.coords[<NUM_LIT:1>:]):<EOL><INDENT>lines.append((line_start[<NUM_LIT:1>], line_start[<NUM_LIT:0>],<EOL>line_end[<NUM_LIT:1>], line_end[<NUM_LIT:0>]))<EOL><DEDENT>lines = np.round(np.float32(lines)).astype(np.int32)<EOL>color = np.float32(color)<EOL>heatmap = np.zeros(image.shape[<NUM_LIT:0>:<NUM_LIT:2>], dtype=np.float32)<EOL>for line in lines:<EOL><INDENT>if antialiased:<EOL><INDENT>rr, cc, val = skimage.draw.line_aa(*line)<EOL><DEDENT>else:<EOL><INDENT>rr, cc = skimage.draw.line(*line)<EOL>val = <NUM_LIT:1.0><EOL><DEDENT>rr_mask = np.logical_and(<NUM_LIT:0> <= rr, rr < height)<EOL>cc_mask = np.logical_and(<NUM_LIT:0> <= cc, cc < width)<EOL>mask = np.logical_and(rr_mask, cc_mask)<EOL>if np.any(mask):<EOL><INDENT>rr = rr[mask]<EOL>cc = cc[mask]<EOL>val = val[mask] if not ia.is_single_number(val) else val<EOL>heatmap[rr, cc] = val * alpha<EOL><DEDENT><DEDENT>if size > <NUM_LIT:1>:<EOL><INDENT>kernel = np.ones((size, size), dtype=np.uint8)<EOL>heatmap = cv2.dilate(heatmap, kernel)<EOL><DEDENT>if image_was_empty:<EOL><INDENT>image_blend = image + heatmap * color<EOL><DEDENT>else:<EOL><INDENT>image_color_shape = image.shape[<NUM_LIT:0>:<NUM_LIT:2>]<EOL>if image.ndim == <NUM_LIT:3>:<EOL><INDENT>image_color_shape = image_color_shape + (<NUM_LIT:1>,)<EOL><DEDENT>image_color = np.tile(color, image_color_shape)<EOL>image_blend = blendlib.blend_alpha(image_color, image, heatmap)<EOL><DEDENT>image_blend = iadt.restore_dtypes_(image_blend, np.uint8)<EOL>return image_blend<EOL>

Draw the line segments of the line string on a given image.

Parameters
----------
image : ndarray or tuple of int
    The image onto which to draw.
    Expected to be ``uint8`` and of shape ``(H, W, C)`` with ``C``
    usually being ``3`` (other values are not tested).
    If a tuple, expected to be ``(H, W, C)`` and will lead to a new
    ``uint8`` array of zeros being created.

color : int or iterable of int
    Color to use as RGB, i.e. three values.

alpha : float, optional
    Opacity of the line string. Higher values denote a more visible
    line string.

size : int, optional
    Thickness of the line segments.

antialiased : bool, optional
    Whether to draw the line with anti-aliasing activated.

raise_if_out_of_image : bool, optional
    Whether to raise an error if the line string is fully
    outside of the image. If set to False, no error will be raised and
    only the parts inside the image will be drawn.

Returns
-------
ndarray
    `image` with line drawn on it.


def draw_points_on_image(self, image, color=(<NUM_LIT:0>, <NUM_LIT>, <NUM_LIT:0>),<EOL>alpha=<NUM_LIT:1.0>, size=<NUM_LIT:3>,<EOL>copy=True, raise_if_out_of_image=False):

from .kps import KeypointsOnImage<EOL>kpsoi = KeypointsOnImage.from_xy_array(self.coords, shape=image.shape)<EOL>image = kpsoi.draw_on_image(<EOL>image, color=color, alpha=alpha,<EOL>size=size, copy=copy,<EOL>raise_if_out_of_image=raise_if_out_of_image)<EOL>return image<EOL>

Draw the points of the line string on a given image.

Parameters
----------
image : ndarray or tuple of int
    The image onto which to draw.
    Expected to be ``uint8`` and of shape ``(H, W, C)`` with ``C``
    usually being ``3`` (other values are not tested).
    If a tuple, expected to be ``(H, W, C)`` and will lead to a new
    ``uint8`` array of zeros being created.

color : iterable of int
    Color to use as RGB, i.e. three values.

alpha : float, optional
    Opacity of the line string points. Higher values denote a more
    visible points.

size : int, optional
    Size of the points in pixels.

copy : bool, optional
    Whether it is allowed to draw directly in the input
    array (``False``) or it has to be copied (``True``).
    The routine may still have to copy, even if ``copy=False`` was
    used. Always use the return value.

raise_if_out_of_image : bool, optional
    Whether to raise an error if the line string is fully
    outside of the image. If set to False, no error will be raised and
    only the parts inside the image will be drawn.

Returns
-------
ndarray
    Float array of shape `image_shape` (no channel axis) with drawn
    line string points. All values are in the interval ``[0.0, 1.0]``.


def draw_on_image(self, image,<EOL>color=(<NUM_LIT:0>, <NUM_LIT:255>, <NUM_LIT:0>), color_lines=None, color_points=None,<EOL>alpha=<NUM_LIT:1.0>, alpha_lines=None, alpha_points=None,<EOL>size=<NUM_LIT:1>, size_lines=None, size_points=None,<EOL>antialiased=True,<EOL>raise_if_out_of_image=False):

assert color is not None<EOL>assert alpha is not None<EOL>assert size is not None<EOL>color_lines = color_lines if color_lines is not Noneelse np.float32(color)<EOL>color_points = color_points if color_points is not Noneelse np.float32(color) * <NUM_LIT:0.5><EOL>alpha_lines = alpha_lines if alpha_lines is not Noneelse np.float32(alpha)<EOL>alpha_points = alpha_points if alpha_points is not Noneelse np.float32(alpha)<EOL>size_lines = size_lines if size_lines is not None else size<EOL>size_points = size_points if size_points is not None else size * <NUM_LIT:3><EOL>image = self.draw_lines_on_image(<EOL>image, color=np.array(color_lines).astype(np.uint8),<EOL>alpha=alpha_lines, size=size_lines,<EOL>antialiased=antialiased,<EOL>raise_if_out_of_image=raise_if_out_of_image)<EOL>image = self.draw_points_on_image(<EOL>image, color=np.array(color_points).astype(np.uint8),<EOL>alpha=alpha_points, size=size_points,<EOL>copy=False,<EOL>raise_if_out_of_image=raise_if_out_of_image)<EOL>return image<EOL>

Draw the line string on an image.

Parameters
----------
image : ndarray
    The `(H,W,C)` `uint8` image onto which to draw the line string.

color : iterable of int, optional
    Color to use as RGB, i.e. three values.
    The color of the line and points are derived from this value,
    unless they are set.

color_lines : None or iterable of int
    Color to use for the line segments as RGB, i.e. three values.
    If ``None``, this value is derived from `color`.

color_points : None or iterable of int
    Color to use for the points as RGB, i.e. three values.
    If ``None``, this value is derived from ``0.5 * color``.

alpha : float, optional
    Opacity of the line string. Higher values denote more visible
    points.
    The alphas of the line and points are derived from this value,
    unless they are set.

alpha_lines : None or float, optional
    Opacity of the line string. Higher values denote more visible
    line string.
    If ``None``, this value is derived from `alpha`.

alpha_points : None or float, optional
    Opacity of the line string points. Higher values denote more
    visible points.
    If ``None``, this value is derived from `alpha`.

size : int, optional
    Size of the line string.
    The sizes of the line and points are derived from this value,
    unless they are set.

size_lines : None or int, optional
    Thickness of the line segments.
    If ``None``, this value is derived from `size`.

size_points : None or int, optional
    Size of the points in pixels.
    If ``None``, this value is derived from ``3 * size``.

antialiased : bool, optional
    Whether to draw the line with anti-aliasing activated.
    This does currently not affect the point drawing.

raise_if_out_of_image : bool, optional
    Whether to raise an error if the line string is fully
    outside of the image. If set to False, no error will be raised and
    only the parts inside the image will be drawn.

Returns
-------
ndarray
    Image with line string drawn on it.


def extract_from_image(self, image, size=<NUM_LIT:1>, pad=True, pad_max=None,<EOL>antialiased=True, prevent_zero_size=True):

from .bbs import BoundingBox<EOL>assert image.ndim in [<NUM_LIT:2>, <NUM_LIT:3>], (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (image.shape,))<EOL>if len(self.coords) == <NUM_LIT:0> or size <= <NUM_LIT:0>:<EOL><INDENT>if prevent_zero_size:<EOL><INDENT>return np.zeros((<NUM_LIT:1>, <NUM_LIT:1>) + image.shape[<NUM_LIT:2>:], dtype=image.dtype)<EOL><DEDENT>return np.zeros((<NUM_LIT:0>, <NUM_LIT:0>) + image.shape[<NUM_LIT:2>:], dtype=image.dtype)<EOL><DEDENT>xx = self.xx_int<EOL>yy = self.yy_int<EOL>sizeh = (size - <NUM_LIT:1>) / <NUM_LIT:2><EOL>x1 = np.min(xx) - sizeh<EOL>y1 = np.min(yy) - sizeh<EOL>x2 = np.max(xx) + <NUM_LIT:1> + sizeh<EOL>y2 = np.max(yy) + <NUM_LIT:1> + sizeh<EOL>bb = BoundingBox(x1=x1, y1=y1, x2=x2, y2=y2)<EOL>if len(self.coords) == <NUM_LIT:1>:<EOL><INDENT>return bb.extract_from_image(image, pad=pad, pad_max=pad_max,<EOL>prevent_zero_size=prevent_zero_size)<EOL><DEDENT>heatmap = self.draw_lines_heatmap_array(<EOL>image.shape[<NUM_LIT:0>:<NUM_LIT:2>], alpha=<NUM_LIT:1.0>, size=size, antialiased=antialiased)<EOL>if image.ndim == <NUM_LIT:3>:<EOL><INDENT>heatmap = np.atleast_3d(heatmap)<EOL><DEDENT>image_masked = image.astype(np.float32) * heatmap<EOL>extract = bb.extract_from_image(image_masked, pad=pad, pad_max=pad_max,<EOL>prevent_zero_size=prevent_zero_size)<EOL>return np.clip(np.round(extract), <NUM_LIT:0>, <NUM_LIT:255>).astype(np.uint8)<EOL>

Extract the image pixels covered by the line string.

It will only extract pixels overlapped by the line string.

This function will by default zero-pad the image if the line string is
partially/fully outside of the image. This is for consistency with
the same implementations for bounding boxes and polygons.

Parameters
----------
image : ndarray
    The image of shape `(H,W,[C])` from which to extract the pixels
    within the line string.

size : int, optional
    Thickness of the line.

pad : bool, optional
    Whether to zero-pad the image if the object is partially/fully
    outside of it.

pad_max : None or int, optional
    The maximum number of pixels that may be zero-paded on any side,
    i.e. if this has value ``N`` the total maximum of added pixels
    is ``4*N``.
    This option exists to prevent extremely large images as a result of
    single points being moved very far away during augmentation.

antialiased : bool, optional
    Whether to apply anti-aliasing to the line string.

prevent_zero_size : bool, optional
    Whether to prevent height or width of the extracted image from
    becoming zero. If this is set to True and height or width of the
    line string is below 1, the height/width will be increased to 1.
    This can be useful to prevent problems, e.g. with image saving or
    plotting. If it is set to False, images will be returned as
    ``(H', W')`` or ``(H', W', 3)`` with ``H`` or ``W`` potentially
    being 0.

Returns
-------
image : (H',W') ndarray or (H',W',C) ndarray
    Pixels overlapping with the line string. Zero-padded if the
    line string is partially/fully outside of the image and
    ``pad=True``. If `prevent_zero_size` is activated, it is
    guarantueed that ``H'>0`` and ``W'>0``, otherwise only
    ``H'>=0`` and ``W'>=0``.


if not isinstance(other, LineString):<EOL><INDENT>other = LineString(other)<EOL><DEDENT>return self.deepcopy(<EOL>coords=np.concatenate([self.coords, other.coords], axis=<NUM_LIT:0>))<EOL>

Concatenate this line string with another one.

This will add a line segment between the end point of this line string
and the start point of `other`.

Parameters
----------
other : imgaug.augmentables.lines.LineString or ndarray \
        or iterable of tuple of number
    The points to add to this line string.

Returns
-------
imgaug.augmentables.lines.LineString
    New line string with concatenated points.
    The `label` of this line string will be kept.


if len(self.coords) <= <NUM_LIT:1> or points_per_edge < <NUM_LIT:1>:<EOL><INDENT>return self.deepcopy()<EOL><DEDENT>coords = interpolate_points(self.coords, nb_steps=points_per_edge,<EOL>closed=False)<EOL>return self.deepcopy(coords=coords)<EOL>

Adds ``N`` interpolated points with uniform spacing to each edge.

For each edge between points ``A`` and ``B`` this adds points
at ``A + (i/(1+N)) * (B - A)``, where ``i`` is the index of the added
point and ``N`` is the number of points to add per edge.

Calling this method two times will split each edge at its center
and then again split each newly created edge at their center.
It is equivalent to calling `subdivide(3)`.

Parameters
----------
points_per_edge : int
    Number of points to interpolate on each edge.

Returns
-------
LineString
    Line string with subdivided edges.


<EOL>from imgaug.augmentables.kps import Keypoint<EOL>return [Keypoint(x=x, y=y) for (x, y) in self.coords]<EOL>

Convert the line string points to keypoints.

Returns
-------
list of imgaug.augmentables.kps.Keypoint
    Points of the line string as keypoints.


from .bbs import BoundingBox<EOL>if len(self.coords) == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>return BoundingBox(x1=np.min(self.xx), y1=np.min(self.yy),<EOL>x2=np.max(self.xx), y2=np.max(self.yy),<EOL>label=self.label)<EOL>

Generate a bounding box encapsulating the line string.

Returns
-------
None or imgaug.augmentables.bbs.BoundingBox
    Bounding box encapsulating the line string.
    ``None`` if the line string contained no points.


from .polys import Polygon<EOL>return Polygon(self.coords, label=self.label)<EOL>

Generate a polygon from the line string points.

Returns
-------
imgaug.augmentables.polys.Polygon
    Polygon with the same corner points as the line string.
    Note that the polygon might be invalid, e.g. contain less than 3
    points or have self-intersections.


def to_heatmap(self, image_shape, size_lines=<NUM_LIT:1>, size_points=<NUM_LIT:0>,<EOL>antialiased=True, raise_if_out_of_image=False):

from .heatmaps import HeatmapsOnImage<EOL>return HeatmapsOnImage(<EOL>self.draw_heatmap_array(<EOL>image_shape, size_lines=size_lines, size_points=size_points,<EOL>antialiased=antialiased,<EOL>raise_if_out_of_image=raise_if_out_of_image),<EOL>shape=image_shape<EOL>)<EOL>

Generate a heatmap object from the line string.

This is similar to
:func:`imgaug.augmentables.lines.LineString.draw_lines_heatmap_array`
executed with ``alpha=1.0``. The result is wrapped in a
``HeatmapsOnImage`` object instead of just an array.
No points are drawn.

Parameters
----------
image_shape : tuple of int
    The shape of the image onto which to draw the line mask.

size_lines : int, optional
    Thickness of the line.

size_points : int, optional
    Size of the points in pixels.

antialiased : bool, optional
    Whether to draw the line with anti-aliasing activated.

raise_if_out_of_image : bool, optional
    Whether to raise an error if the line string is fully
    outside of the image. If set to False, no error will be raised and
    only the parts inside the image will be drawn.

Returns
-------
imgaug.augmentables.heatmaps.HeatmapOnImage
    Heatmap object containing drawn line string.


def to_segmentation_map(self, image_shape, size_lines=<NUM_LIT:1>, size_points=<NUM_LIT:0>,<EOL>raise_if_out_of_image=False):

from .segmaps import SegmentationMapOnImage<EOL>return SegmentationMapOnImage(<EOL>self.draw_mask(<EOL>image_shape, size_lines=size_lines, size_points=size_points,<EOL>raise_if_out_of_image=raise_if_out_of_image),<EOL>shape=image_shape<EOL>)<EOL>

Generate a segmentation map object from the line string.

This is similar to
:func:`imgaug.augmentables.lines.LineString.draw_mask`.
The result is wrapped in a ``SegmentationMapOnImage`` object
instead of just an array.

Parameters
----------
image_shape : tuple of int
    The shape of the image onto which to draw the line mask.

size_lines : int, optional
    Thickness of the line.

size_points : int, optional
    Size of the points in pixels.

raise_if_out_of_image : bool, optional
    Whether to raise an error if the line string is fully
    outside of the image. If set to False, no error will be raised and
    only the parts inside the image will be drawn.

Returns
-------
imgaug.augmentables.segmaps.SegmentationMapOnImage
    Segmentation map object containing drawn line string.


def coords_almost_equals(self, other, max_distance=<NUM_LIT>, points_per_edge=<NUM_LIT:8>):

if isinstance(other, LineString):<EOL><INDENT>pass<EOL><DEDENT>elif isinstance(other, tuple):<EOL><INDENT>other = LineString([other])<EOL><DEDENT>else:<EOL><INDENT>other = LineString(other)<EOL><DEDENT>if len(self.coords) == <NUM_LIT:0> and len(other.coords) == <NUM_LIT:0>:<EOL><INDENT>return True<EOL><DEDENT>elif <NUM_LIT:0> in [len(self.coords), len(other.coords)]:<EOL><INDENT>return False<EOL><DEDENT>self_subd = self.subdivide(points_per_edge)<EOL>other_subd = other.subdivide(points_per_edge)<EOL>dist_self2other = self_subd.compute_pointwise_distances(other_subd)<EOL>dist_other2self = other_subd.compute_pointwise_distances(self_subd)<EOL>dist = max(np.max(dist_self2other), np.max(dist_other2self))<EOL>return  dist < max_distance<EOL>

Compare this and another LineString's coordinates.

This is an approximate method based on pointwise distances and can
in rare corner cases produce wrong outputs.

Parameters
----------
other : imgaug.augmentables.lines.LineString \
        or tuple of number \
        or ndarray \
        or list of ndarray \
        or list of tuple of number
    The other line string or its coordinates.

max_distance : float
    Max distance of any point from the other line string before
    the two line strings are evaluated to be unequal.

points_per_edge : int, optional
    How many points to interpolate on each edge.

Returns
-------
bool
    Whether the two LineString's coordinates are almost identical,
    i.e. the max distance is below the threshold.
    If both have no coordinates, ``True`` is returned.
    If only one has no coordinates, ``False`` is returned.
    Beyond that, the number of points is not evaluated.


def almost_equals(self, other, max_distance=<NUM_LIT>, points_per_edge=<NUM_LIT:8>):

if self.label != other.label:<EOL><INDENT>return False<EOL><DEDENT>return self.coords_almost_equals(<EOL>other, max_distance=max_distance, points_per_edge=points_per_edge)<EOL>

Compare this and another LineString.

Parameters
----------
other: imgaug.augmentables.lines.LineString
    The other line string. Must be a LineString instance, not just
    its coordinates.

max_distance : float, optional
    See :func:`imgaug.augmentables.lines.LineString.coords_almost_equals`.

points_per_edge : int, optional
    See :func:`imgaug.augmentables.lines.LineString.coords_almost_equals`.

Returns
-------
bool
    ``True`` if the coordinates are almost equal according to
    :func:`imgaug.augmentables.lines.LineString.coords_almost_equals`
    and additionally the labels are identical. Otherwise ``False``.


def copy(self, coords=None, label=None):

return LineString(coords=self.coords if coords is None else coords,<EOL>label=self.label if label is None else label)<EOL>

Create a shallow copy of the LineString object.

Parameters
----------
coords : None or iterable of tuple of number or ndarray
    If not ``None``, then the coords of the copied object will be set
    to this value.

label : None or str
    If not ``None``, then the label of the copied object will be set to
    this value.

Returns
-------
imgaug.augmentables.lines.LineString
    Shallow copy.


def deepcopy(self, coords=None, label=None):

return LineString(<EOL>coords=np.copy(self.coords) if coords is None else coords,<EOL>label=copylib.deepcopy(self.label) if label is None else label)<EOL>

Create a deep copy of the BoundingBox object.

Parameters
----------
coords : None or iterable of tuple of number or ndarray
    If not ``None``, then the coords of the copied object will be set
    to this value.

label : None or str
    If not ``None``, then the label of the copied object will be set to
    this value.

Returns
-------
imgaug.augmentables.lines.LineString
    Deep copy.


return len(self.line_strings) == <NUM_LIT:0><EOL>

Returns whether this object contains zero line strings.

Returns
-------
bool
    True if this object contains zero line strings.


shape = normalize_shape(image)<EOL>if shape[<NUM_LIT:0>:<NUM_LIT:2>] == self.shape[<NUM_LIT:0>:<NUM_LIT:2>]:<EOL><INDENT>return self.deepcopy()<EOL><DEDENT>line_strings = [ls.project(self.shape, shape)<EOL>for ls in self.line_strings]<EOL>return self.deepcopy(line_strings=line_strings, shape=shape)<EOL>

Project bounding boxes from one image to a new one.

Parameters
----------
image : ndarray or tuple of int
    The new image onto which to project.
    Either an image with shape ``(H,W,[C])`` or a tuple denoting
    such an image shape.

Returns
-------
line_strings : imgaug.augmentables.lines.LineStrings
    Object containing all projected line strings.


@classmethod<EOL><INDENT>def from_xy_arrays(cls, xy, shape):<DEDENT>

lss = []<EOL>for xy_ls in xy:<EOL><INDENT>lss.append(LineString(xy_ls))<EOL><DEDENT>return cls(lss, shape)<EOL>

Convert an `(N,M,2)` ndarray to a LineStringsOnImage object.

This is the inverse of
:func:`imgaug.augmentables.lines.LineStringsOnImage.to_xy_array`.

Parameters
----------
xy : (N,M,2) ndarray or iterable of (M,2) ndarray
    Array containing the point coordinates ``N`` line strings
    with each ``M`` points given as ``(x,y)`` coordinates.
    ``M`` may differ if an iterable of arrays is used.
    Each array should usually be of dtype ``float32``.

shape : tuple of int
    ``(H,W,[C])`` shape of the image on which the line strings are
    placed.

Returns
-------
imgaug.augmentables.lines.LineStringsOnImage
    Object containing a list of ``LineString`` objects following the
    provided point coordinates.


from .. import dtypes as iadt<EOL>return [iadt.restore_dtypes_(np.copy(ls.coords), dtype)<EOL>for ls in self.line_strings]<EOL>

Convert this object to an iterable of ``(M,2)`` arrays of points.

This is the inverse of
:func:`imgaug.augmentables.lines.LineStringsOnImage.from_xy_array`.

Parameters
----------
dtype : numpy.dtype, optional
    Desired output datatype of the ndarray.

Returns
-------
list of ndarray
    The arrays of point coordinates, each given as ``(M,2)``.


<EOL>for ls in self.line_strings:<EOL><INDENT>image = ls.draw_on_image(<EOL>image,<EOL>color=color, color_lines=color_lines, color_points=color_points,<EOL>alpha=alpha, alpha_lines=alpha_lines, alpha_points=alpha_points,<EOL>size=size, size_lines=size_lines, size_points=size_points,<EOL>antialiased=antialiased,<EOL>raise_if_out_of_image=raise_if_out_of_image<EOL>)<EOL><DEDENT>return image<EOL>

Draw all line strings onto a given image.

Parameters
----------
image : ndarray
    The `(H,W,C)` `uint8` image onto which to draw the line strings.

color : iterable of int, optional
    Color to use as RGB, i.e. three values.
    The color of the lines and points are derived from this value,
    unless they are set.

color_lines : None or iterable of int
    Color to use for the line segments as RGB, i.e. three values.
    If ``None``, this value is derived from `color`.

color_points : None or iterable of int
    Color to use for the points as RGB, i.e. three values.
    If ``None``, this value is derived from ``0.5 * color``.

alpha : float, optional
    Opacity of the line strings. Higher values denote more visible
    points.
    The alphas of the line and points are derived from this value,
    unless they are set.

alpha_lines : None or float, optional
    Opacity of the line strings. Higher values denote more visible
    line string.
    If ``None``, this value is derived from `alpha`.

alpha_points : None or float, optional
    Opacity of the line string points. Higher values denote more
    visible points.
    If ``None``, this value is derived from `alpha`.

size : int, optional
    Size of the line strings.
    The sizes of the line and points are derived from this value,
    unless they are set.

size_lines : None or int, optional
    Thickness of the line segments.
    If ``None``, this value is derived from `size`.

size_points : None or int, optional
    Size of the points in pixels.
    If ``None``, this value is derived from ``3 * size``.

antialiased : bool, optional
    Whether to draw the lines with anti-aliasing activated.
    This does currently not affect the point drawing.

raise_if_out_of_image : bool, optional
    Whether to raise an error if a line string is fully
    outside of the image. If set to False, no error will be raised and
    only the parts inside the image will be drawn.

Returns
-------
ndarray
    Image with line strings drawn on it.


def remove_out_of_image(self, fully=True, partly=False):

lss_clean = [ls for ls in self.line_strings<EOL>if not ls.is_out_of_image(<EOL>self.shape, fully=fully, partly=partly)]<EOL>return LineStringsOnImage(lss_clean, shape=self.shape)<EOL>

Remove all line strings that are fully/partially outside of the image.

Parameters
----------
fully : bool, optional
    Whether to remove line strings that are fully outside of the image.

partly : bool, optional
    Whether to remove line strings that are partially outside of the
    image.

Returns
-------
imgaug.augmentables.lines.LineStringsOnImage
    Reduced set of line strings, with those that were fully/partially
    outside of the image removed.


lss_cut = [ls_clipped<EOL>for ls in self.line_strings<EOL>for ls_clipped in ls.clip_out_of_image(self.shape)]<EOL>return LineStringsOnImage(lss_cut, shape=self.shape)<EOL>

Clip off all parts of the line strings that are outside of the image.

Returns
-------
imgaug.augmentables.lines.LineStringsOnImage
    Line strings, clipped to fall within the image dimensions.


def shift(self, top=None, right=None, bottom=None, left=None):

lss_new = [ls.shift(top=top, right=right, bottom=bottom, left=left)<EOL>for ls in self.line_strings]<EOL>return LineStringsOnImage(lss_new, shape=self.shape)<EOL>

Shift/move the line strings from one or more image sides.

Parameters
----------
top : None or int, optional
    Amount of pixels by which to shift all bounding boxes from the
    top.

right : None or int, optional
    Amount of pixels by which to shift all bounding boxes from the
    right.

bottom : None or int, optional
    Amount of pixels by which to shift all bounding boxes from the
    bottom.

left : None or int, optional
    Amount of pixels by which to shift all bounding boxes from the
    left.

Returns
-------
imgaug.augmentables.lines.LineStringsOnImage
    Shifted line strings.


def copy(self, line_strings=None, shape=None):

lss = self.line_strings if line_strings is None else line_strings<EOL>shape = self.shape if shape is None else shape<EOL>return LineStringsOnImage(line_strings=lss, shape=shape)<EOL>

Create a shallow copy of the LineStringsOnImage object.

Parameters
----------
line_strings : None \
               or list of imgaug.augmentables.lines.LineString, optional
    List of line strings on the image.
    If not ``None``, then the ``line_strings`` attribute of the copied
    object will be set to this value.

shape : None or tuple of int or ndarray, optional
    The shape of the image on which the objects are placed.
    Either an image with shape ``(H,W,[C])`` or a tuple denoting
    such an image shape.
    If not ``None``, then the ``shape`` attribute of the copied object
    will be set to this value.

Returns
-------
imgaug.augmentables.lines.LineStringsOnImage
    Shallow copy.


def deepcopy(self, line_strings=None, shape=None):

lss = self.line_strings if line_strings is None else line_strings<EOL>shape = self.shape if shape is None else shape<EOL>return LineStringsOnImage(<EOL>line_strings=[ls.deepcopy() for ls in lss],<EOL>shape=tuple(shape))<EOL>

Create a deep copy of the LineStringsOnImage object.

Parameters
----------
line_strings : None \
               or list of imgaug.augmentables.lines.LineString, optional
    List of line strings on the image.
    If not ``None``, then the ``line_strings`` attribute of the copied
    object will be set to this value.

shape : None or tuple of int or ndarray, optional
    The shape of the image on which the objects are placed.
    Either an image with shape ``(H,W,[C])`` or a tuple denoting
    such an image shape.
    If not ``None``, then the ``shape`` attribute of the copied object
    will be set to this value.

Returns
-------
imgaug.augmentables.lines.LineStringsOnImage
    Deep copy.


def __init__(self, x1, y1, x2, y2, label=None):

if x1 > x2:<EOL><INDENT>x2, x1 = x1, x2<EOL><DEDENT>ia.do_assert(x2 >= x1)<EOL>if y1 > y2:<EOL><INDENT>y2, y1 = y1, y2<EOL><DEDENT>ia.do_assert(y2 >= y1)<EOL>self.x1 = x1<EOL>self.y1 = y1<EOL>self.x2 = x2<EOL>self.y2 = y2<EOL>self.label = label<EOL>


return int(np.round(self.x1))<EOL>

Return the x-coordinate of the top left corner as an integer.

Returns
-------
int
    X-coordinate of the top left corner, rounded to the closest integer.


return int(np.round(self.y1))<EOL>

Return the y-coordinate of the top left corner as an integer.

Returns
-------
int
    Y-coordinate of the top left corner, rounded to the closest integer.


return int(np.round(self.x2))<EOL>

Return the x-coordinate of the bottom left corner as an integer.

Returns
-------
int
    X-coordinate of the bottom left corner, rounded to the closest integer.


return int(np.round(self.y2))<EOL>

Return the y-coordinate of the bottom left corner as an integer.

Returns
-------
int
    Y-coordinate of the bottom left corner, rounded to the closest integer.


return self.y2 - self.y1<EOL>

Estimate the height of the bounding box.

Returns
-------
number
    Height of the bounding box.


return self.x2 - self.x1<EOL>

Estimate the width of the bounding box.

Returns
-------
number
    Width of the bounding box.


return self.x1 + self.width/<NUM_LIT:2><EOL>

Estimate the x-coordinate of the center point of the bounding box.

Returns
-------
number
    X-coordinate of the center point of the bounding box.


return self.y1 + self.height/<NUM_LIT:2><EOL>

Estimate the y-coordinate of the center point of the bounding box.

Returns
-------
number
    Y-coordinate of the center point of the bounding box.


return self.height * self.width<EOL>

Estimate the area of the bounding box.

Returns
-------
number
    Area of the bounding box, i.e. `height * width`.