g = tf.get_default_graph()<EOL>with g.gradient_override_map({"<STR_LIT>": "<STR_LIT>"}):<EOL><INDENT>threshold = _compute_threshold(x)<EOL>x = tf.sign(tf.add(tf.sign(tf.add(x, threshold)), tf.sign(tf.add(x, -threshold))))<EOL>return x<EOL><DEDENT>

Ternary operation use threshold computed with weights.


return tf.clip_by_value(grad, -<NUM_LIT:1>, <NUM_LIT:1>)<EOL>

Clip and binarize tensor using the straight through estimator (STE) for the gradient.


x_sum = tf.reduce_sum(tf.abs(x), reduction_indices=None, keepdims=False, name=None)<EOL>threshold = tf.div(x_sum, tf.cast(tf.size(x), tf.float32), name=None)<EOL>threshold = tf.multiply(<NUM_LIT>, threshold, name=None)<EOL>return threshold<EOL>

ref: https://github.com/XJTUWYD/TWN
Computing the threshold.


def _conv_linear(args, filter_size, num_features, bias, bias_start=<NUM_LIT:0.0>, scope=None):

<EOL>total_arg_size_depth = <NUM_LIT:0><EOL>shapes = [a.get_shape().as_list() for a in args]<EOL>for shape in shapes:<EOL><INDENT>if len(shape) != <NUM_LIT:4>:<EOL><INDENT>raise ValueError("<STR_LIT>" % str(shapes))<EOL><DEDENT>if not shape[<NUM_LIT:3>]:<EOL><INDENT>raise ValueError("<STR_LIT>" % str(shapes))<EOL><DEDENT>else:<EOL><INDENT>total_arg_size_depth += shape[<NUM_LIT:3>]<EOL><DEDENT><DEDENT>dtype = [a.dtype for a in args][<NUM_LIT:0>]<EOL>with tf.variable_scope(scope or "<STR_LIT>"):<EOL><INDENT>matrix = tf.get_variable(<EOL>"<STR_LIT>", [filter_size[<NUM_LIT:0>], filter_size[<NUM_LIT:1>], total_arg_size_depth, num_features], dtype=dtype<EOL>)<EOL>if len(args) == <NUM_LIT:1>:<EOL><INDENT>res = tf.nn.conv2d(args[<NUM_LIT:0>], matrix, strides=[<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>], padding='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>res = tf.nn.conv2d(tf.concat(args, <NUM_LIT:3>), matrix, strides=[<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>], padding='<STR_LIT>')<EOL><DEDENT>if not bias:<EOL><INDENT>return res<EOL><DEDENT>bias_term = tf.get_variable(<EOL>"<STR_LIT>", [num_features], dtype=dtype, initializer=tf.constant_initializer(bias_start, dtype=dtype)<EOL>)<EOL><DEDENT>return res + bias_term<EOL>

convolution:

    Parameters
    ----------
    args : tensor
        4D Tensor or a list of 4D, batch x n, Tensors.
    filter_size : tuple of int
        Filter height and width.
    num_features : int
        Nnumber of features.
    bias_start : float
        Starting value to initialize the bias; 0 by default.
    scope : VariableScope
        For the created subgraph; defaults to "Linear".

    Returns
    --------
    - A 4D Tensor with shape [batch h w num_features]

    Raises
    -------
    - ValueError : if some of the arguments has unspecified or wrong shape.


batch_size = tf.shape(inputs)[<NUM_LIT:0>]<EOL>max_length = tf.shape(inputs)[<NUM_LIT:1>]  <EOL>dim_size = int(inputs.get_shape()[<NUM_LIT:2>])<EOL>index = tf.range(<NUM_LIT:0>, batch_size) * max_length + (index - <NUM_LIT:1>)<EOL>flat = tf.reshape(inputs, [-<NUM_LIT:1>, dim_size])<EOL>relevant = tf.gather(flat, index)<EOL>return relevant<EOL>

Advanced Indexing for Sequences, returns the outputs by given sequence lengths.
    When return the last output :class:`DynamicRNNLayer` uses it to get the last outputs with the sequence lengths.

    Parameters
    -----------
    inputs : tensor for data
        With shape of [batch_size, n_step(max), n_features]
    index : tensor for indexing
        Sequence length in Dynamic RNN. [batch_size]

    Examples
    ---------
    >>> import numpy as np
    >>> import tensorflow as tf
    >>> import tensorlayer as tl
    >>> batch_size, max_length, n_features = 3, 5, 2
    >>> z = np.random.uniform(low=-1, high=1, size=[batch_size, max_length, n_features]).astype(np.float32)
    >>> b_z = tf.constant(z)
    >>> sl = tf.placeholder(dtype=tf.int32, shape=[batch_size])
    >>> o = advanced_indexing_op(b_z, sl)
    >>>
    >>> sess = tf.InteractiveSession()
    >>> tl.layers.initialize_global_variables(sess)
    >>>
    >>> order = np.asarray([1,1,2])
    >>> print("real",z[0][order[0]-1], z[1][order[1]-1], z[2][order[2]-1])
    >>> y = sess.run([o], feed_dict={sl:order})
    >>> print("given",order)
    >>> print("out", y)
    real [-0.93021595  0.53820813] [-0.92548317 -0.77135968] [ 0.89952248  0.19149846]
    given [1 1 2]
    out [array([[-0.93021595,  0.53820813],
                [-0.92548317, -0.77135968],
                [ 0.89952248,  0.19149846]], dtype=float32)]

    References
    -----------
    - Modified from TFlearn (the original code is used for fixed length rnn), `references <https://github.com/tflearn/tflearn/blob/master/tflearn/layers/recurrent.py>`__.


with tf.name_scope('<STR_LIT>'):<EOL><INDENT>used = tf.sign(tf.reduce_max(tf.abs(data), <NUM_LIT:2>))<EOL>length = tf.reduce_sum(used, <NUM_LIT:1>)<EOL>return tf.cast(length, tf.int32)<EOL><DEDENT>

An op to compute the length of a sequence from input shape of [batch_size, n_step(max), n_features],
    it can be used when the features of padding (on right hand side) are all zeros.

    Parameters
    -----------
    data : tensor
        [batch_size, n_step(max), n_features] with zero padding on right hand side.

    Examples
    ---------
    >>> data = [[[1],[2],[0],[0],[0]],
    ...         [[1],[2],[3],[0],[0]],
    ...         [[1],[2],[6],[1],[0]]]
    >>> data = np.asarray(data)
    >>> print(data.shape)
    (3, 5, 1)
    >>> data = tf.constant(data)
    >>> sl = retrieve_seq_length_op(data)
    >>> sess = tf.InteractiveSession()
    >>> tl.layers.initialize_global_variables(sess)
    >>> y = sl.eval()
    [2 3 4]

    Multiple features
    >>> data = [[[1,2],[2,2],[1,2],[1,2],[0,0]],
    ...         [[2,3],[2,4],[3,2],[0,0],[0,0]],
    ...         [[3,3],[2,2],[5,3],[1,2],[0,0]]]
    >>> print(sl)
    [4 3 4]

    References
    ------------
    Borrow from `TFlearn <https://github.com/tflearn/tflearn/blob/master/tflearn/layers/recurrent.py>`__.


return tf.reduce_sum(tf.cast(tf.greater(data, tf.zeros_like(data)), tf.int32), <NUM_LIT:1>)<EOL>

An op to compute the length of a sequence, from input shape of [batch_size, n_step(max)],
    it can be used when the features of padding (on right hand side) are all zeros.

    Parameters
    -----------
    data : tensor
        [batch_size, n_step(max)] with zero padding on right hand side.

    Examples
    --------
    >>> data = [[1,2,0,0,0],
    ...         [1,2,3,0,0],
    ...         [1,2,6,1,0]]
    >>> o = retrieve_seq_length_op2(data)
    >>> sess = tf.InteractiveSession()
    >>> tl.layers.initialize_global_variables(sess)
    >>> print(o.eval())
    [2 3 4]


data_shape_size = data.get_shape().ndims<EOL>if data_shape_size == <NUM_LIT:3>:<EOL><INDENT>return tf.reduce_sum(tf.cast(tf.reduce_any(tf.not_equal(data, pad_val), axis=<NUM_LIT:2>), dtype=tf.int32), <NUM_LIT:1>)<EOL><DEDENT>elif data_shape_size == <NUM_LIT:2>:<EOL><INDENT>return tf.reduce_sum(tf.cast(tf.not_equal(data, pad_val), dtype=tf.int32), <NUM_LIT:1>)<EOL><DEDENT>elif data_shape_size == <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" % (data_shape_size)<EOL>)<EOL><DEDENT>

Return tensor for sequence length, if input is ``tf.string``.


data_shape_size = data.get_shape().ndims<EOL>if data_shape_size == <NUM_LIT:3>:<EOL><INDENT>return tf.cast(tf.reduce_any(tf.not_equal(data, pad_val), axis=<NUM_LIT:2>), dtype=tf.int32)<EOL><DEDENT>elif data_shape_size == <NUM_LIT:2>:<EOL><INDENT>return tf.cast(tf.not_equal(data, pad_val), dtype=tf.int32)<EOL><DEDENT>elif data_shape_size == <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % (data_shape_size))<EOL><DEDENT>

Return tensor for mask, if input is ``tf.string``.


def __call__(self, inputs, state, scope=None):

raise NotImplementedError("<STR_LIT>")<EOL>

Run this RNN cell on inputs, starting from the given state.


Integer or TensorShape: size of outputs produced by this cell.


def zero_state(self, batch_size, dtype=LayersConfig.tf_dtype):

shape = self.shape<EOL>num_features = self.num_features<EOL>zeros = tf.zeros([batch_size, shape[<NUM_LIT:0>], shape[<NUM_LIT:1>], num_features * <NUM_LIT:2>], dtype=dtype)<EOL>return zeros<EOL>

Return zero-filled state tensor(s).
        Args:
          batch_size: int, float, or unit Tensor representing the batch size.
        Returns:
          tensor of shape '[batch_size x shape[0] x shape[1] x num_features]
          filled with zeros


def __init__(<EOL>self, shape, filter_size, num_features, forget_bias=<NUM_LIT:1.0>, input_size=None, state_is_tuple=False,<EOL>act=tf.nn.tanh<EOL>):

<EOL>if input_size is not None:<EOL><INDENT>logging.warn("<STR_LIT>", self)<EOL><DEDENT>self.shape = shape<EOL>self.filter_size = filter_size<EOL>self.num_features = num_features<EOL>self._forget_bias = forget_bias<EOL>self._state_is_tuple = state_is_tuple<EOL>self._activation = act<EOL>


return (LSTMStateTuple(self._num_units, self._num_units) if self._state_is_tuple else <NUM_LIT:2> * self._num_units)<EOL>


return self._num_units<EOL>


with tf.variable_scope(scope or type(self).__name__):  <EOL><INDENT>if self._state_is_tuple:<EOL><INDENT>c, h = state<EOL><DEDENT>else:<EOL><INDENT>c, h = tf.split(state, <NUM_LIT:2>, <NUM_LIT:3>)<EOL><DEDENT>concat = _conv_linear([inputs, h], self.filter_size, self.num_features * <NUM_LIT:4>, True)<EOL>i, j, f, o = tf.split(concat, <NUM_LIT:4>, <NUM_LIT:3>)<EOL>new_c = (c * tf.nn.sigmoid(f + self._forget_bias) + tf.nn.sigmoid(i) * self._activation(j))<EOL>new_h = self._activation(new_c) * tf.nn.sigmoid(o)<EOL>if self._state_is_tuple:<EOL><INDENT>new_state = LSTMStateTuple(new_c, new_h)<EOL><DEDENT>else:<EOL><INDENT>new_state = tf.concat([new_c, new_h], <NUM_LIT:3>)<EOL><DEDENT>return new_h, new_state<EOL><DEDENT>


def threading_data(data=None, fn=None, thread_count=None, **kwargs):

def apply_fn(results, i, data, kwargs):<EOL><INDENT>results[i] = fn(data, **kwargs)<EOL><DEDENT>if thread_count is None:<EOL><INDENT>results = [None] * len(data)<EOL>threads = []<EOL>for i, d in enumerate(data):<EOL><INDENT>t = threading.Thread(name='<STR_LIT>', target=apply_fn, args=(results, i, d, kwargs))<EOL>t.start()<EOL>threads.append(t)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>divs = np.linspace(<NUM_LIT:0>, len(data), thread_count + <NUM_LIT:1>)<EOL>divs = np.round(divs).astype(int)<EOL>results = [None] * thread_count<EOL>threads = []<EOL>for i in range(thread_count):<EOL><INDENT>t = threading.Thread(<EOL>name='<STR_LIT>', target=apply_fn, args=(results, i, data[divs[i]:divs[i + <NUM_LIT:1>]], kwargs)<EOL>)<EOL>t.start()<EOL>threads.append(t)<EOL><DEDENT><DEDENT>for t in threads:<EOL><INDENT>t.join()<EOL><DEDENT>if thread_count is None:<EOL><INDENT>try:<EOL><INDENT>return np.asarray(results)<EOL><DEDENT>except Exception:<EOL><INDENT>return results<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return np.concatenate(results)<EOL><DEDENT>

Process a batch of data by given function by threading.

    Usually be used for data augmentation.

    Parameters
    -----------
    data : numpy.array or others
        The data to be processed.
    thread_count : int
        The number of threads to use.
    fn : function
        The function for data processing.
    more args : the args for `fn`
        Ssee Examples below.

    Examples
    --------
    Process images.

    >>> images, _, _, _ = tl.files.load_cifar10_dataset(shape=(-1, 32, 32, 3))
    >>> images = tl.prepro.threading_data(images[0:32], tl.prepro.zoom, zoom_range=[0.5, 1])

    Customized image preprocessing function.

    >>> def distort_img(x):
    >>>     x = tl.prepro.flip_axis(x, axis=0, is_random=True)
    >>>     x = tl.prepro.flip_axis(x, axis=1, is_random=True)
    >>>     x = tl.prepro.crop(x, 100, 100, is_random=True)
    >>>     return x
    >>> images = tl.prepro.threading_data(images, distort_img)

    Process images and masks together (Usually be used for image segmentation).

    >>> X, Y --> [batch_size, row, col, 1]
    >>> data = tl.prepro.threading_data([_ for _ in zip(X, Y)], tl.prepro.zoom_multi, zoom_range=[0.5, 1], is_random=True)
    data --> [batch_size, 2, row, col, 1]
    >>> X_, Y_ = data.transpose((1,0,2,3,4))
    X_, Y_ --> [batch_size, row, col, 1]
    >>> tl.vis.save_image(X_, 'images.png')
    >>> tl.vis.save_image(Y_, 'masks.png')

    Process images and masks together by using ``thread_count``.

    >>> X, Y --> [batch_size, row, col, 1]
    >>> data = tl.prepro.threading_data(X, tl.prepro.zoom_multi, 8, zoom_range=[0.5, 1], is_random=True)
    data --> [batch_size, 2, row, col, 1]
    >>> X_, Y_ = data.transpose((1,0,2,3,4))
    X_, Y_ --> [batch_size, row, col, 1]
    >>> tl.vis.save_image(X_, 'after.png')
    >>> tl.vis.save_image(Y_, 'before.png')

    Customized function for processing images and masks together.

    >>> def distort_img(data):
    >>>    x, y = data
    >>>    x, y = tl.prepro.flip_axis_multi([x, y], axis=0, is_random=True)
    >>>    x, y = tl.prepro.flip_axis_multi([x, y], axis=1, is_random=True)
    >>>    x, y = tl.prepro.crop_multi([x, y], 100, 100, is_random=True)
    >>>    return x, y

    >>> X, Y --> [batch_size, row, col, channel]
    >>> data = tl.prepro.threading_data([_ for _ in zip(X, Y)], distort_img)
    >>> X_, Y_ = data.transpose((1,0,2,3,4))

    Returns
    -------
    list or numpyarray
        The processed results.

    References
    ----------
    - `python queue <https://pymotw.com/2/Queue/index.html#module-Queue>`__
    - `run with limited queue <http://effbot.org/librarybook/queue.htm>`__


if isinstance(angle, tuple):<EOL><INDENT>theta = np.pi / <NUM_LIT> * np.random.uniform(angle[<NUM_LIT:0>], angle[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>theta = np.pi / <NUM_LIT> * angle<EOL><DEDENT>rotation_matrix = np.array([[np.cos(theta), np.sin(theta), <NUM_LIT:0>],[-np.sin(theta), np.cos(theta), <NUM_LIT:0>],[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]])<EOL>return rotation_matrix<EOL>

Create an affine transform matrix for image rotation.
    NOTE: In OpenCV, x is width and y is height.

    Parameters
    -----------
    angle : int/float or tuple of two int/float
        Degree to rotate, usually -180 ~ 180.
            - int/float, a fixed angle.
            - tuple of 2 floats/ints, randomly sample a value as the angle between these 2 values.

    Returns
    -------
    numpy.array
        An affine transform matrix.


factor = np.random.uniform(<NUM_LIT:0>, <NUM_LIT:1>)<EOL>if prob >= factor:<EOL><INDENT>filp_matrix = np.array([[ -<NUM_LIT:1.> , <NUM_LIT:0.>, <NUM_LIT:0.> ],[ <NUM_LIT:0.>, <NUM_LIT:1.>, <NUM_LIT:0.> ],[ <NUM_LIT:0.>, <NUM_LIT:0.>, <NUM_LIT:1.> ]])<EOL>return filp_matrix<EOL><DEDENT>else:<EOL><INDENT>filp_matrix = np.array([[ <NUM_LIT:1.> , <NUM_LIT:0.>, <NUM_LIT:0.> ],[ <NUM_LIT:0.>, <NUM_LIT:1.>, <NUM_LIT:0.> ],[ <NUM_LIT:0.>, <NUM_LIT:0.>, <NUM_LIT:1.> ]])<EOL>return filp_matrix<EOL><DEDENT>

Create an affine transformation matrix for image horizontal flipping.
    NOTE: In OpenCV, x is width and y is height.

    Parameters
    ----------
    prob : float
        Probability to flip the image. 1.0 means always flip.

    Returns
    -------
    numpy.array
        An affine transform matrix.


factor = np.random.uniform(<NUM_LIT:0>, <NUM_LIT:1>)<EOL>if prob >= factor:<EOL><INDENT>filp_matrix = np.array([[ <NUM_LIT:1.> , <NUM_LIT:0.>, <NUM_LIT:0.> ],[ <NUM_LIT:0.>, -<NUM_LIT:1.>, <NUM_LIT:0.> ],[ <NUM_LIT:0.>, <NUM_LIT:0.>, <NUM_LIT:1.> ]])<EOL>return filp_matrix<EOL><DEDENT>else:<EOL><INDENT>filp_matrix = np.array([[ <NUM_LIT:1.> , <NUM_LIT:0.>, <NUM_LIT:0.> ],[ <NUM_LIT:0.>, <NUM_LIT:1.>, <NUM_LIT:0.> ],[ <NUM_LIT:0.>, <NUM_LIT:0.>, <NUM_LIT:1.> ]])<EOL>return filp_matrix<EOL><DEDENT>

Create an affine transformation for image vertical flipping.
    NOTE: In OpenCV, x is width and y is height.

    Parameters
    ----------
    prob : float
        Probability to flip the image. 1.0 means always flip.

    Returns
    -------
    numpy.array
        An affine transform matrix.


def affine_shift_matrix(wrg=(-<NUM_LIT:0.1>, <NUM_LIT:0.1>), hrg=(-<NUM_LIT:0.1>, <NUM_LIT:0.1>), w=<NUM_LIT:200>, h=<NUM_LIT:200>):

if isinstance(wrg, tuple):<EOL><INDENT>tx = np.random.uniform(wrg[<NUM_LIT:0>], wrg[<NUM_LIT:1>]) * w<EOL><DEDENT>else:<EOL><INDENT>tx = wrg * w<EOL><DEDENT>if isinstance(hrg, tuple):<EOL><INDENT>ty = np.random.uniform(hrg[<NUM_LIT:0>], hrg[<NUM_LIT:1>]) * h<EOL><DEDENT>else:<EOL><INDENT>ty = hrg * h<EOL><DEDENT>shift_matrix = np.array([[<NUM_LIT:1>, <NUM_LIT:0>, tx],[<NUM_LIT:0>, <NUM_LIT:1>, ty],[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]])<EOL>return shift_matrix<EOL>

Create an affine transform matrix for image shifting.
    NOTE: In OpenCV, x is width and y is height.

    Parameters
    -----------
    wrg : float or tuple of floats
        Range to shift on width axis, -1 ~ 1.
            - float, a fixed distance.
            - tuple of 2 floats, randomly sample a value as the distance between these 2 values.
    hrg : float or tuple of floats
        Range to shift on height axis, -1 ~ 1.
            - float, a fixed distance.
            - tuple of 2 floats, randomly sample a value as the distance between these 2 values.
    w, h : int
        The width and height of the image.

    Returns
    -------
    numpy.array
        An affine transform matrix.


def affine_shear_matrix(x_shear=(-<NUM_LIT:0.1>, <NUM_LIT:0.1>), y_shear=(-<NUM_LIT:0.1>, <NUM_LIT:0.1>)):

<EOL>if isinstance(x_shear, tuple):<EOL><INDENT>x_shear = np.random.uniform(x_shear[<NUM_LIT:0>], x_shear[<NUM_LIT:1>])<EOL><DEDENT>if isinstance(y_shear, tuple):<EOL><INDENT>y_shear = np.random.uniform(y_shear[<NUM_LIT:0>], y_shear[<NUM_LIT:1>])<EOL><DEDENT>shear_matrix = np.array([[<NUM_LIT:1>, x_shear, <NUM_LIT:0>],[y_shear, <NUM_LIT:1>, <NUM_LIT:0>],[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]])<EOL>return shear_matrix<EOL>

Create affine transform matrix for image shearing.
    NOTE: In OpenCV, x is width and y is height.

    Parameters
    -----------
    shear : tuple of two floats
        Percentage of shears for width and height directions.

    Returns
    -------
    numpy.array
        An affine transform matrix.


if isinstance(zoom_range, (float, int)):<EOL><INDENT>scale = zoom_range<EOL><DEDENT>elif isinstance(zoom_range, tuple):<EOL><INDENT>scale = np.random.uniform(zoom_range[<NUM_LIT:0>], zoom_range[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>zoom_matrix = np.array([[scale, <NUM_LIT:0>, <NUM_LIT:0>],[<NUM_LIT:0>, scale, <NUM_LIT:0>],[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]])<EOL>return zoom_matrix<EOL>

Create an affine transform matrix for zooming/scaling an image's height and width.
    OpenCV format, x is width.

    Parameters
    -----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    zoom_range : float or tuple of 2 floats
        The zooming/scaling ratio, greater than 1 means larger.
            - float, a fixed ratio.
            - tuple of 2 floats, randomly sample a value as the ratio between these 2 values.

    Returns
    -------
    numpy.array
        An affine transform matrix.


if isinstance(h_range, (float, int)):<EOL><INDENT>zy = h_range<EOL><DEDENT>elif isinstance(h_range, tuple):<EOL><INDENT>zy = np.random.uniform(h_range[<NUM_LIT:0>], h_range[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>if isinstance(w_range, (float, int)):<EOL><INDENT>zx = w_range<EOL><DEDENT>elif isinstance(w_range, tuple):<EOL><INDENT>zx = np.random.uniform(w_range[<NUM_LIT:0>], w_range[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>zoom_matrix = np.array([[zx, <NUM_LIT:0>, <NUM_LIT:0>],[<NUM_LIT:0>, zy, <NUM_LIT:0>],[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]])<EOL>return zoom_matrix<EOL>

Get affine transform matrix for zooming/scaling that height and width are changed independently.
    OpenCV format, x is width.

    Parameters
    -----------
    w_range : float or tuple of 2 floats
        The zooming/scaling ratio of width, greater than 1 means larger.
            - float, a fixed ratio.
            - tuple of 2 floats, randomly sample a value as the ratio between 2 values.
    h_range : float or tuple of 2 floats
        The zooming/scaling ratio of height, greater than 1 means larger.
            - float, a fixed ratio.
            - tuple of 2 floats, randomly sample a value as the ratio between 2 values.

    Returns
    -------
    numpy.array
        An affine transform matrix.


def transform_matrix_offset_center(matrix, y, x):

o_x = (x - <NUM_LIT:1>) / <NUM_LIT><EOL>o_y = (y - <NUM_LIT:1>) / <NUM_LIT><EOL>offset_matrix = np.array([[<NUM_LIT:1>, <NUM_LIT:0>, o_x], [<NUM_LIT:0>, <NUM_LIT:1>, o_y], [<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]])<EOL>reset_matrix = np.array([[<NUM_LIT:1>, <NUM_LIT:0>, -o_x], [<NUM_LIT:0>, <NUM_LIT:1>, -o_y], [<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]])<EOL>transform_matrix = np.dot(np.dot(offset_matrix, matrix), reset_matrix)<EOL>return transform_matrix<EOL>

Convert the matrix from Cartesian coordinates (the origin in the middle of image) to Image coordinates (the origin on the top-left of image).

    Parameters
    ----------
    matrix : numpy.array
        Transform matrix.
    x and y : 2 int
        Size of image.

    Returns
    -------
    numpy.array
        The transform matrix.

    Examples
    --------
    - See ``tl.prepro.rotation``, ``tl.prepro.shear``, ``tl.prepro.zoom``.


def affine_transform(x, transform_matrix, channel_index=<NUM_LIT:2>, fill_mode='<STR_LIT>', cval=<NUM_LIT:0.>, order=<NUM_LIT:1>):

<EOL>x = np.rollaxis(x, channel_index, <NUM_LIT:0>)<EOL>final_affine_matrix = transform_matrix[:<NUM_LIT:2>, :<NUM_LIT:2>]<EOL>final_offset = transform_matrix[:<NUM_LIT:2>, <NUM_LIT:2>]<EOL>channel_images = [<EOL>ndi.interpolation.<EOL>affine_transform(x_channel, final_affine_matrix, final_offset, order=order, mode=fill_mode, cval=cval)<EOL>for x_channel in x<EOL>]<EOL>x = np.stack(channel_images, axis=<NUM_LIT:0>)<EOL>x = np.rollaxis(x, <NUM_LIT:0>, channel_index + <NUM_LIT:1>)<EOL>return x<EOL>

Return transformed images by given an affine matrix in Scipy format (x is height).

    Parameters
    ----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    transform_matrix : numpy.array
        Transform matrix (offset center), can be generated by ``transform_matrix_offset_center``
    channel_index : int
        Index of channel, default 2.
    fill_mode : str
        Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
    cval : float
        Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0
    order : int
        The order of interpolation. The order has to be in the range 0-5:
            - 0 Nearest-neighbor
            - 1 Bi-linear (default)
            - 2 Bi-quadratic
            - 3 Bi-cubic
            - 4 Bi-quartic
            - 5 Bi-quintic
            - `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__

    Returns
    -------
    numpy.array
        A processed image.

    Examples
    --------
    >>> M_shear = tl.prepro.affine_shear_matrix(intensity=0.2, is_random=False)
    >>> M_zoom = tl.prepro.affine_zoom_matrix(zoom_range=0.8)
    >>> M_combined = M_shear.dot(M_zoom)
    >>> transform_matrix = tl.prepro.transform_matrix_offset_center(M_combined, h, w)
    >>> result = tl.prepro.affine_transform(image, transform_matrix)


def affine_transform_cv2(x, transform_matrix, flags=None, border_mode='<STR_LIT>'):

rows, cols = x.shape[<NUM_LIT:0>], x.shape[<NUM_LIT:1>]<EOL>if flags is None:<EOL><INDENT>flags = cv2.INTER_AREA<EOL><DEDENT>if border_mode is '<STR_LIT>':<EOL><INDENT>border_mode = cv2.BORDER_CONSTANT<EOL><DEDENT>elif border_mode is '<STR_LIT>':<EOL><INDENT>border_mode = cv2.BORDER_REPLICATE<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>return cv2.warpAffine(x, transform_matrix[<NUM_LIT:0>:<NUM_LIT:2>,:],(cols,rows), flags=flags, borderMode=border_mode)<EOL>

Return transformed images by given an affine matrix in OpenCV format (x is width). (Powered by OpenCV2, faster than ``tl.prepro.affine_transform``)

    Parameters
    ----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    transform_matrix : numpy.array
        A transform matrix, OpenCV format.
    border_mode : str
        - `constant`, pad the image with a constant value (i.e. black or 0)
        - `replicate`, the row or column at the very edge of the original is replicated to the extra border.

    Examples
    --------
    >>> M_shear = tl.prepro.affine_shear_matrix(intensity=0.2, is_random=False)
    >>> M_zoom = tl.prepro.affine_zoom_matrix(zoom_range=0.8)
    >>> M_combined = M_shear.dot(M_zoom)
    >>> result = tl.prepro.affine_transform_cv2(image, M_combined)


coords_result_list = []<EOL>for coords in coords_list:<EOL><INDENT>coords = np.asarray(coords)<EOL>coords = coords.transpose([<NUM_LIT:1>, <NUM_LIT:0>])<EOL>coords = np.insert(coords, <NUM_LIT:2>, <NUM_LIT:1>, axis=<NUM_LIT:0>)<EOL>coords_result = np.matmul(transform_matrix, coords)<EOL>coords_result = coords_result[<NUM_LIT:0>:<NUM_LIT:2>, :].transpose([<NUM_LIT:1>, <NUM_LIT:0>])<EOL>coords_result_list.append(coords_result)<EOL><DEDENT>return coords_result_list<EOL>

Transform keypoint coordinates according to a given affine transform matrix.
    OpenCV format, x is width.

    Note that, for pose estimation task, flipping requires maintaining the left and right body information.
    We should not flip the left and right body, so please use ``tl.prepro.keypoint_random_flip``.

    Parameters
    -----------
    coords_list : list of list of tuple/list
        The coordinates
        e.g., the keypoint coordinates of every person in an image.
    transform_matrix : numpy.array
        Transform matrix, OpenCV format.

    Examples
    ---------
    >>> # 1. get all affine transform matrices
    >>> M_rotate = tl.prepro.affine_rotation_matrix(angle=20)
    >>> M_flip = tl.prepro.affine_horizontal_flip_matrix(prob=1)
    >>> # 2. combine all affine transform matrices to one matrix
    >>> M_combined = dot(M_flip).dot(M_rotate)
    >>> # 3. transfrom the matrix from Cartesian coordinate (the origin in the middle of image)
    >>> # to Image coordinate (the origin on the top-left of image)
    >>> transform_matrix = tl.prepro.transform_matrix_offset_center(M_combined, x=w, y=h)
    >>> # 4. then we can transfrom the image once for all transformations
    >>> result = tl.prepro.affine_transform_cv2(image, transform_matrix)  # 76 times faster
    >>> # 5. transform keypoint coordinates
    >>> coords = [[(50, 100), (100, 100), (100, 50), (200, 200)], [(250, 50), (200, 50), (200, 100)]]
    >>> coords_result = tl.prepro.affine_transform_keypoints(coords, transform_matrix)


def projective_transform_by_points(<EOL>x, src, dst, map_args=None, output_shape=None, order=<NUM_LIT:1>, mode='<STR_LIT>', cval=<NUM_LIT:0.0>, clip=True,<EOL>preserve_range=False<EOL>):

if map_args is None:<EOL><INDENT>map_args = {}<EOL><DEDENT>if isinstance(src, list):  <EOL><INDENT>src = np.array(src)<EOL><DEDENT>if isinstance(dst, list):<EOL><INDENT>dst = np.array(dst)<EOL><DEDENT>if np.max(x) > <NUM_LIT:1>:  <EOL><INDENT>x = x / <NUM_LIT:255><EOL><DEDENT>m = transform.ProjectiveTransform()<EOL>m.estimate(dst, src)<EOL>warped = transform.warp(<EOL>x, m, map_args=map_args, output_shape=output_shape, order=order, mode=mode, cval=cval, clip=clip,<EOL>preserve_range=preserve_range<EOL>)<EOL>return warped<EOL>

Projective transform by given coordinates, usually 4 coordinates.

    see `scikit-image <http://scikit-image.org/docs/dev/auto_examples/applications/plot_geometric.html>`__.

    Parameters
    -----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    src : list or numpy
        The original coordinates, usually 4 coordinates of (width, height).
    dst : list or numpy
        The coordinates after transformation, the number of coordinates is the same with src.
    map_args : dictionary or None
        Keyword arguments passed to inverse map.
    output_shape : tuple of 2 int
        Shape of the output image generated. By default the shape of the input image is preserved. Note that, even for multi-band images, only rows and columns need to be specified.
    order : int
        The order of interpolation. The order has to be in the range 0-5:
            - 0 Nearest-neighbor
            - 1 Bi-linear (default)
            - 2 Bi-quadratic
            - 3 Bi-cubic
            - 4 Bi-quartic
            - 5 Bi-quintic
    mode : str
        One of `constant` (default), `edge`, `symmetric`, `reflect` or `wrap`.
        Points outside the boundaries of the input are filled according to the given mode. Modes match the behaviour of numpy.pad.
    cval : float
        Used in conjunction with mode `constant`, the value outside the image boundaries.
    clip : boolean
        Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range.
    preserve_range : boolean
        Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float.

    Returns
    -------
    numpy.array
        A processed image.

    Examples
    --------
    Assume X is an image from CIFAR-10, i.e. shape == (32, 32, 3)

    >>> src = [[0,0],[0,32],[32,0],[32,32]]     # [w, h]
    >>> dst = [[10,10],[0,32],[32,0],[32,32]]
    >>> x = tl.prepro.projective_transform_by_points(X, src, dst)

    References
    -----------
    - `scikit-image : geometric transformations <http://scikit-image.org/docs/dev/auto_examples/applications/plot_geometric.html>`__
    - `scikit-image : examples <http://scikit-image.org/docs/dev/auto_examples/index.html>`__


def rotation(<EOL>x, rg=<NUM_LIT:20>, is_random=False, row_index=<NUM_LIT:0>, col_index=<NUM_LIT:1>, channel_index=<NUM_LIT:2>, fill_mode='<STR_LIT>', cval=<NUM_LIT:0.>, order=<NUM_LIT:1><EOL>):

if is_random:<EOL><INDENT>theta = np.pi / <NUM_LIT> * np.random.uniform(-rg, rg)<EOL><DEDENT>else:<EOL><INDENT>theta = np.pi / <NUM_LIT> * rg<EOL><DEDENT>rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), <NUM_LIT:0>], [np.sin(theta), np.cos(theta), <NUM_LIT:0>], [<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]])<EOL>h, w = x.shape[row_index], x.shape[col_index]<EOL>transform_matrix = transform_matrix_offset_center(rotation_matrix, h, w)<EOL>x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order)<EOL>return x<EOL>

Rotate an image randomly or non-randomly.

    Parameters
    -----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    rg : int or float
        Degree to rotate, usually 0 ~ 180.
    is_random : boolean
        If True, randomly rotate. Default is False
    row_index col_index and channel_index : int
        Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
    fill_mode : str
        Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
    cval : float
        Value used for points outside the boundaries of the input if mode=`constant`. Default is 0.0
    order : int
        The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__

    Returns
    -------
    numpy.array
        A processed image.

    Examples
    ---------
    >>> x --> [row, col, 1]
    >>> x = tl.prepro.rotation(x, rg=40, is_random=False)
    >>> tl.vis.save_image(x, 'im.png')


def rotation_multi(<EOL>x, rg=<NUM_LIT:20>, is_random=False, row_index=<NUM_LIT:0>, col_index=<NUM_LIT:1>, channel_index=<NUM_LIT:2>, fill_mode='<STR_LIT>', cval=<NUM_LIT:0.>, order=<NUM_LIT:1><EOL>):

if is_random:<EOL><INDENT>theta = np.pi / <NUM_LIT> * np.random.uniform(-rg, rg)<EOL><DEDENT>else:<EOL><INDENT>theta = np.pi / <NUM_LIT> * rg<EOL><DEDENT>rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), <NUM_LIT:0>], [np.sin(theta), np.cos(theta), <NUM_LIT:0>], [<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]])<EOL>h, w = x[<NUM_LIT:0>].shape[row_index], x[<NUM_LIT:0>].shape[col_index]<EOL>transform_matrix = transform_matrix_offset_center(rotation_matrix, h, w)<EOL>results = []<EOL>for data in x:<EOL><INDENT>results.append(affine_transform(data, transform_matrix, channel_index, fill_mode, cval, order))<EOL><DEDENT>return np.asarray(results)<EOL>

Rotate multiple images with the same arguments, randomly or non-randomly.
    Usually be used for image segmentation which x=[X, Y], X and Y should be matched.

    Parameters
    -----------
    x : list of numpy.array
        List of images with dimension of [n_images, row, col, channel] (default).
    others : args
        See ``tl.prepro.rotation``.

    Returns
    -------
    numpy.array
        A list of processed images.

    Examples
    --------
    >>> x, y --> [row, col, 1]  greyscale
    >>> x, y = tl.prepro.rotation_multi([x, y], rg=90, is_random=False)


def crop(x, wrg, hrg, is_random=False, row_index=<NUM_LIT:0>, col_index=<NUM_LIT:1>):

h, w = x.shape[row_index], x.shape[col_index]<EOL>if (h < hrg) or (w < wrg):<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT>if is_random:<EOL><INDENT>h_offset = int(np.random.uniform(<NUM_LIT:0>, h - hrg))<EOL>w_offset = int(np.random.uniform(<NUM_LIT:0>, w - wrg))<EOL>return x[h_offset:hrg + h_offset, w_offset:wrg + w_offset]<EOL><DEDENT>else:  <EOL><INDENT>h_offset = int(np.floor((h - hrg) / <NUM_LIT>))<EOL>w_offset = int(np.floor((w - wrg) / <NUM_LIT>))<EOL>h_end = h_offset + hrg<EOL>w_end = w_offset + wrg<EOL>return x[h_offset:h_end, w_offset:w_end]<EOL><DEDENT>

Randomly or centrally crop an image.

    Parameters
    ----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    wrg : int
        Size of width.
    hrg : int
        Size of height.
    is_random : boolean,
        If True, randomly crop, else central crop. Default is False.
    row_index: int
        index of row.
    col_index: int
        index of column.

    Returns
    -------
    numpy.array
        A processed image.


def crop_multi(x, wrg, hrg, is_random=False, row_index=<NUM_LIT:0>, col_index=<NUM_LIT:1>):

h, w = x[<NUM_LIT:0>].shape[row_index], x[<NUM_LIT:0>].shape[col_index]<EOL>if (h < hrg) or (w < wrg):<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT>if is_random:<EOL><INDENT>h_offset = int(np.random.uniform(<NUM_LIT:0>, h - hrg))<EOL>w_offset = int(np.random.uniform(<NUM_LIT:0>, w - wrg))<EOL>results = []<EOL>for data in x:<EOL><INDENT>results.append(data[h_offset:hrg + h_offset, w_offset:wrg + w_offset])<EOL><DEDENT>return np.asarray(results)<EOL><DEDENT>else:<EOL><INDENT>h_offset = (h - hrg) / <NUM_LIT:2><EOL>w_offset = (w - wrg) / <NUM_LIT:2><EOL>results = []<EOL>for data in x:<EOL><INDENT>results.append(data[h_offset:h - h_offset, w_offset:w - w_offset])<EOL><DEDENT>return np.asarray(results)<EOL><DEDENT>

Randomly or centrally crop multiple images.

    Parameters
    ----------
    x : list of numpy.array
        List of images with dimension of [n_images, row, col, channel] (default).
    others : args
        See ``tl.prepro.crop``.

    Returns
    -------
    numpy.array
        A list of processed images.


def flip_axis(x, axis=<NUM_LIT:1>, is_random=False):

if is_random:<EOL><INDENT>factor = np.random.uniform(-<NUM_LIT:1>, <NUM_LIT:1>)<EOL>if factor > <NUM_LIT:0>:<EOL><INDENT>x = np.asarray(x).swapaxes(axis, <NUM_LIT:0>)<EOL>x = x[::-<NUM_LIT:1>, ...]<EOL>x = x.swapaxes(<NUM_LIT:0>, axis)<EOL>return x<EOL><DEDENT>else:<EOL><INDENT>return x<EOL><DEDENT><DEDENT>else:<EOL><INDENT>x = np.asarray(x).swapaxes(axis, <NUM_LIT:0>)<EOL>x = x[::-<NUM_LIT:1>, ...]<EOL>x = x.swapaxes(<NUM_LIT:0>, axis)<EOL>return x<EOL><DEDENT>

Flip the axis of an image, such as flip left and right, up and down, randomly or non-randomly,

    Parameters
    ----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    axis : int
        Which axis to flip.
            - 0, flip up and down
            - 1, flip left and right
            - 2, flip channel
    is_random : boolean
        If True, randomly flip. Default is False.

    Returns
    -------
    numpy.array
        A processed image.


def flip_axis_multi(x, axis, is_random=False):

if is_random:<EOL><INDENT>factor = np.random.uniform(-<NUM_LIT:1>, <NUM_LIT:1>)<EOL>if factor > <NUM_LIT:0>:<EOL><INDENT>results = []<EOL>for data in x:<EOL><INDENT>data = np.asarray(data).swapaxes(axis, <NUM_LIT:0>)<EOL>data = data[::-<NUM_LIT:1>, ...]<EOL>data = data.swapaxes(<NUM_LIT:0>, axis)<EOL>results.append(data)<EOL><DEDENT>return np.asarray(results)<EOL><DEDENT>else:<EOL><INDENT>return np.asarray(x)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>results = []<EOL>for data in x:<EOL><INDENT>data = np.asarray(data).swapaxes(axis, <NUM_LIT:0>)<EOL>data = data[::-<NUM_LIT:1>, ...]<EOL>data = data.swapaxes(<NUM_LIT:0>, axis)<EOL>results.append(data)<EOL><DEDENT>return np.asarray(results)<EOL><DEDENT>

Flip the axises of multiple images together, such as flip left and right, up and down, randomly or non-randomly,

    Parameters
    -----------
    x : list of numpy.array
        List of images with dimension of [n_images, row, col, channel] (default).
    others : args
        See ``tl.prepro.flip_axis``.

    Returns
    -------
    numpy.array
        A list of processed images.


def shift(<EOL>x, wrg=<NUM_LIT:0.1>, hrg=<NUM_LIT:0.1>, is_random=False, row_index=<NUM_LIT:0>, col_index=<NUM_LIT:1>, channel_index=<NUM_LIT:2>, fill_mode='<STR_LIT>', cval=<NUM_LIT:0.>,<EOL>order=<NUM_LIT:1><EOL>):

h, w = x.shape[row_index], x.shape[col_index]<EOL>if is_random:<EOL><INDENT>tx = np.random.uniform(-hrg, hrg) * h<EOL>ty = np.random.uniform(-wrg, wrg) * w<EOL><DEDENT>else:<EOL><INDENT>tx, ty = hrg * h, wrg * w<EOL><DEDENT>translation_matrix = np.array([[<NUM_LIT:1>, <NUM_LIT:0>, tx], [<NUM_LIT:0>, <NUM_LIT:1>, ty], [<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]])<EOL>transform_matrix = translation_matrix  <EOL>x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order)<EOL>return x<EOL>

Shift an image randomly or non-randomly.

    Parameters
    -----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    wrg : float
        Percentage of shift in axis x, usually -0.25 ~ 0.25.
    hrg : float
        Percentage of shift in axis y, usually -0.25 ~ 0.25.
    is_random : boolean
        If True, randomly shift. Default is False.
    row_index col_index and channel_index : int
        Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
    fill_mode : str
        Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
    cval : float
        Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0.
    order : int
        The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__

    Returns
    -------
    numpy.array
        A processed image.


def shift_multi(<EOL>x, wrg=<NUM_LIT:0.1>, hrg=<NUM_LIT:0.1>, is_random=False, row_index=<NUM_LIT:0>, col_index=<NUM_LIT:1>, channel_index=<NUM_LIT:2>, fill_mode='<STR_LIT>', cval=<NUM_LIT:0.>,<EOL>order=<NUM_LIT:1><EOL>):

h, w = x[<NUM_LIT:0>].shape[row_index], x[<NUM_LIT:0>].shape[col_index]<EOL>if is_random:<EOL><INDENT>tx = np.random.uniform(-hrg, hrg) * h<EOL>ty = np.random.uniform(-wrg, wrg) * w<EOL><DEDENT>else:<EOL><INDENT>tx, ty = hrg * h, wrg * w<EOL><DEDENT>translation_matrix = np.array([[<NUM_LIT:1>, <NUM_LIT:0>, tx], [<NUM_LIT:0>, <NUM_LIT:1>, ty], [<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]])<EOL>transform_matrix = translation_matrix  <EOL>results = []<EOL>for data in x:<EOL><INDENT>results.append(affine_transform(data, transform_matrix, channel_index, fill_mode, cval, order))<EOL><DEDENT>return np.asarray(results)<EOL>

Shift images with the same arguments, randomly or non-randomly.
    Usually be used for image segmentation which x=[X, Y], X and Y should be matched.

    Parameters
    -----------
    x : list of numpy.array
        List of images with dimension of [n_images, row, col, channel] (default).
    others : args
        See ``tl.prepro.shift``.

    Returns
    -------
    numpy.array
        A list of processed images.


def shear(<EOL>x, intensity=<NUM_LIT:0.1>, is_random=False, row_index=<NUM_LIT:0>, col_index=<NUM_LIT:1>, channel_index=<NUM_LIT:2>, fill_mode='<STR_LIT>', cval=<NUM_LIT:0.>,<EOL>order=<NUM_LIT:1><EOL>):

if is_random:<EOL><INDENT>shear = np.random.uniform(-intensity, intensity)<EOL><DEDENT>else:<EOL><INDENT>shear = intensity<EOL><DEDENT>shear_matrix = np.array([[<NUM_LIT:1>, -np.sin(shear), <NUM_LIT:0>], [<NUM_LIT:0>, np.cos(shear), <NUM_LIT:0>], [<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]])<EOL>h, w = x.shape[row_index], x.shape[col_index]<EOL>transform_matrix = transform_matrix_offset_center(shear_matrix, h, w)<EOL>x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order)<EOL>return x<EOL>

Shear an image randomly or non-randomly.

    Parameters
    -----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    intensity : float
        Percentage of shear, usually -0.5 ~ 0.5 (is_random==True), 0 ~ 0.5 (is_random==False),
        you can have a quick try by shear(X, 1).
    is_random : boolean
        If True, randomly shear. Default is False.
    row_index col_index and channel_index : int
        Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
    fill_mode : str
        Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
    cval : float
        Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0.
    order : int
        The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__

    Returns
    -------
    numpy.array
        A processed image.

    References
    -----------
    - `Affine transformation <https://uk.mathworks.com/discovery/affine-transformation.html>`__


def shear_multi(<EOL>x, intensity=<NUM_LIT:0.1>, is_random=False, row_index=<NUM_LIT:0>, col_index=<NUM_LIT:1>, channel_index=<NUM_LIT:2>, fill_mode='<STR_LIT>', cval=<NUM_LIT:0.>,<EOL>order=<NUM_LIT:1><EOL>):

if is_random:<EOL><INDENT>shear = np.random.uniform(-intensity, intensity)<EOL><DEDENT>else:<EOL><INDENT>shear = intensity<EOL><DEDENT>shear_matrix = np.array([[<NUM_LIT:1>, -np.sin(shear), <NUM_LIT:0>], [<NUM_LIT:0>, np.cos(shear), <NUM_LIT:0>], [<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]])<EOL>h, w = x[<NUM_LIT:0>].shape[row_index], x[<NUM_LIT:0>].shape[col_index]<EOL>transform_matrix = transform_matrix_offset_center(shear_matrix, h, w)<EOL>results = []<EOL>for data in x:<EOL><INDENT>results.append(affine_transform(data, transform_matrix, channel_index, fill_mode, cval, order))<EOL><DEDENT>return np.asarray(results)<EOL>

Shear images with the same arguments, randomly or non-randomly.
    Usually be used for image segmentation which x=[X, Y], X and Y should be matched.

    Parameters
    -----------
    x : list of numpy.array
        List of images with dimension of [n_images, row, col, channel] (default).
    others : args
        See ``tl.prepro.shear``.

    Returns
    -------
    numpy.array
        A list of processed images.


def shear2(<EOL>x, shear=(<NUM_LIT:0.1>, <NUM_LIT:0.1>), is_random=False, row_index=<NUM_LIT:0>, col_index=<NUM_LIT:1>, channel_index=<NUM_LIT:2>, fill_mode='<STR_LIT>', cval=<NUM_LIT:0.>,<EOL>order=<NUM_LIT:1><EOL>):

if len(shear) != <NUM_LIT:2>:<EOL><INDENT>raise AssertionError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>if isinstance(shear, tuple):<EOL><INDENT>shear = list(shear)<EOL><DEDENT>if is_random:<EOL><INDENT>shear[<NUM_LIT:0>] = np.random.uniform(-shear[<NUM_LIT:0>], shear[<NUM_LIT:0>])<EOL>shear[<NUM_LIT:1>] = np.random.uniform(-shear[<NUM_LIT:1>], shear[<NUM_LIT:1>])<EOL><DEDENT>shear_matrix = np.array([[<NUM_LIT:1>, shear[<NUM_LIT:0>], <NUM_LIT:0>],[shear[<NUM_LIT:1>], <NUM_LIT:1>, <NUM_LIT:0>],[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]])<EOL>h, w = x.shape[row_index], x.shape[col_index]<EOL>transform_matrix = transform_matrix_offset_center(shear_matrix, h, w)<EOL>x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order)<EOL>return x<EOL>

Shear an image randomly or non-randomly.

    Parameters
    -----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    shear : tuple of two floats
        Percentage of shear for height and width direction (0, 1).
    is_random : boolean
        If True, randomly shear. Default is False.
    row_index col_index and channel_index : int
        Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
    fill_mode : str
        Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
    cval : float
        Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0.
    order : int
        The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__

    Returns
    -------
    numpy.array
        A processed image.

    References
    -----------
    - `Affine transformation <https://uk.mathworks.com/discovery/affine-transformation.html>`__


def shear_multi2(<EOL>x, shear=(<NUM_LIT:0.1>, <NUM_LIT:0.1>), is_random=False, row_index=<NUM_LIT:0>, col_index=<NUM_LIT:1>, channel_index=<NUM_LIT:2>, fill_mode='<STR_LIT>', cval=<NUM_LIT:0.>,<EOL>order=<NUM_LIT:1><EOL>):

if len(shear) != <NUM_LIT:2>:<EOL><INDENT>raise AssertionError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>if isinstance(shear, tuple):<EOL><INDENT>shear = list(shear)<EOL><DEDENT>if is_random:<EOL><INDENT>shear[<NUM_LIT:0>] = np.random.uniform(-shear[<NUM_LIT:0>], shear[<NUM_LIT:0>])<EOL>shear[<NUM_LIT:1>] = np.random.uniform(-shear[<NUM_LIT:1>], shear[<NUM_LIT:1>])<EOL><DEDENT>shear_matrix = np.array([[<NUM_LIT:1>, shear[<NUM_LIT:0>], <NUM_LIT:0>], [shear[<NUM_LIT:1>], <NUM_LIT:1>, <NUM_LIT:0>], [<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>]])<EOL>h, w = x[<NUM_LIT:0>].shape[row_index], x[<NUM_LIT:0>].shape[col_index]<EOL>transform_matrix = transform_matrix_offset_center(shear_matrix, h, w)<EOL>results = []<EOL>for data in x:<EOL><INDENT>results.append(affine_transform(data, transform_matrix, channel_index, fill_mode, cval, order))<EOL><DEDENT>return np.asarray(results)<EOL>

Shear images with the same arguments, randomly or non-randomly.
    Usually be used for image segmentation which x=[X, Y], X and Y should be matched.

    Parameters
    -----------
    x : list of numpy.array
        List of images with dimension of [n_images, row, col, channel] (default).
    others : args
        See ``tl.prepro.shear2``.

    Returns
    -------
    numpy.array
        A list of processed images.


def swirl(<EOL>x, center=None, strength=<NUM_LIT:1>, radius=<NUM_LIT:100>, rotation=<NUM_LIT:0>, output_shape=None, order=<NUM_LIT:1>, mode='<STR_LIT>', cval=<NUM_LIT:0>,<EOL>clip=True, preserve_range=False, is_random=False<EOL>):

if radius == <NUM_LIT:0>:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT>rotation = np.pi / <NUM_LIT> * rotation<EOL>if is_random:<EOL><INDENT>center_h = int(np.random.uniform(<NUM_LIT:0>, x.shape[<NUM_LIT:0>]))<EOL>center_w = int(np.random.uniform(<NUM_LIT:0>, x.shape[<NUM_LIT:1>]))<EOL>center = (center_h, center_w)<EOL>strength = np.random.uniform(<NUM_LIT:0>, strength)<EOL>radius = np.random.uniform(<NUM_LIT>, radius)<EOL>rotation = np.random.uniform(-rotation, rotation)<EOL><DEDENT>max_v = np.max(x)<EOL>if max_v > <NUM_LIT:1>:  <EOL><INDENT>x = x / max_v<EOL><DEDENT>swirled = skimage.transform.swirl(<EOL>x, center=center, strength=strength, radius=radius, rotation=rotation, output_shape=output_shape, order=order,<EOL>mode=mode, cval=cval, clip=clip, preserve_range=preserve_range<EOL>)<EOL>if max_v > <NUM_LIT:1>:<EOL><INDENT>swirled = swirled * max_v<EOL><DEDENT>return swirled<EOL>

Swirl an image randomly or non-randomly, see `scikit-image swirl API <http://scikit-image.org/docs/dev/api/skimage.transform.html#skimage.transform.swirl>`__
    and `example <http://scikit-image.org/docs/dev/auto_examples/plot_swirl.html>`__.

    Parameters
    -----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    center : tuple or 2 int or None
        Center coordinate of transformation (optional).
    strength : float
        The amount of swirling applied.
    radius : float
        The extent of the swirl in pixels. The effect dies out rapidly beyond radius.
    rotation : float
        Additional rotation applied to the image, usually [0, 360], relates to center.
    output_shape : tuple of 2 int or None
        Shape of the output image generated (height, width). By default the shape of the input image is preserved.
    order : int, optional
        The order of the spline interpolation, default is 1. The order has to be in the range 0-5. See skimage.transform.warp for detail.
    mode : str
        One of `constant` (default), `edge`, `symmetric` `reflect` and `wrap`.
        Points outside the boundaries of the input are filled according to the given mode, with `constant` used as the default. Modes match the behaviour of numpy.pad.
    cval : float
        Used in conjunction with mode `constant`, the value outside the image boundaries.
    clip : boolean
        Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range.
    preserve_range : boolean
        Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float.
    is_random : boolean,
        If True, random swirl. Default is False.
            - random center = [(0 ~ x.shape[0]), (0 ~ x.shape[1])]
            - random strength = [0, strength]
            - random radius = [1e-10, radius]
            - random rotation = [-rotation, rotation]

    Returns
    -------
    numpy.array
        A processed image.

    Examples
    ---------
    >>> x --> [row, col, 1] greyscale
    >>> x = tl.prepro.swirl(x, strength=4, radius=100)


def swirl_multi(<EOL>x, center=None, strength=<NUM_LIT:1>, radius=<NUM_LIT:100>, rotation=<NUM_LIT:0>, output_shape=None, order=<NUM_LIT:1>, mode='<STR_LIT>', cval=<NUM_LIT:0>,<EOL>clip=True, preserve_range=False, is_random=False<EOL>):

if radius == <NUM_LIT:0>:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT>rotation = np.pi / <NUM_LIT> * rotation<EOL>if is_random:<EOL><INDENT>center_h = int(np.random.uniform(<NUM_LIT:0>, x[<NUM_LIT:0>].shape[<NUM_LIT:0>]))<EOL>center_w = int(np.random.uniform(<NUM_LIT:0>, x[<NUM_LIT:0>].shape[<NUM_LIT:1>]))<EOL>center = (center_h, center_w)<EOL>strength = np.random.uniform(<NUM_LIT:0>, strength)<EOL>radius = np.random.uniform(<NUM_LIT>, radius)<EOL>rotation = np.random.uniform(-rotation, rotation)<EOL><DEDENT>results = []<EOL>for data in x:<EOL><INDENT>max_v = np.max(data)<EOL>if max_v > <NUM_LIT:1>:  <EOL><INDENT>data = data / max_v<EOL><DEDENT>swirled = skimage.transform.swirl(<EOL>data, center=center, strength=strength, radius=radius, rotation=rotation, output_shape=output_shape,<EOL>order=order, mode=mode, cval=cval, clip=clip, preserve_range=preserve_range<EOL>)<EOL>if max_v > <NUM_LIT:1>:<EOL><INDENT>swirled = swirled * max_v<EOL><DEDENT>results.append(swirled)<EOL><DEDENT>return np.asarray(results)<EOL>

Swirl multiple images with the same arguments, randomly or non-randomly.
    Usually be used for image segmentation which x=[X, Y], X and Y should be matched.

    Parameters
    -----------
    x : list of numpy.array
        List of images with dimension of [n_images, row, col, channel] (default).
    others : args
        See ``tl.prepro.swirl``.

    Returns
    -------
    numpy.array
        A list of processed images.


def elastic_transform(x, alpha, sigma, mode="<STR_LIT>", cval=<NUM_LIT:0>, is_random=False):

if is_random is False:<EOL><INDENT>random_state = np.random.RandomState(None)<EOL><DEDENT>else:<EOL><INDENT>random_state = np.random.RandomState(int(time.time()))<EOL><DEDENT>is_3d = False<EOL>if len(x.shape) == <NUM_LIT:3> and x.shape[-<NUM_LIT:1>] == <NUM_LIT:1>:<EOL><INDENT>x = x[:, :, <NUM_LIT:0>]<EOL>is_3d = True<EOL><DEDENT>elif len(x.shape) == <NUM_LIT:3> and x.shape[-<NUM_LIT:1>] != <NUM_LIT:1>:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>if len(x.shape) != <NUM_LIT:2>:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT>shape = x.shape<EOL>dx = gaussian_filter((random_state.rand(*shape) * <NUM_LIT:2> - <NUM_LIT:1>), sigma, mode=mode, cval=cval) * alpha<EOL>dy = gaussian_filter((random_state.rand(*shape) * <NUM_LIT:2> - <NUM_LIT:1>), sigma, mode=mode, cval=cval) * alpha<EOL>x_, y_ = np.meshgrid(np.arange(shape[<NUM_LIT:0>]), np.arange(shape[<NUM_LIT:1>]), indexing='<STR_LIT>')<EOL>indices = np.reshape(x_ + dx, (-<NUM_LIT:1>, <NUM_LIT:1>)), np.reshape(y_ + dy, (-<NUM_LIT:1>, <NUM_LIT:1>))<EOL>if is_3d:<EOL><INDENT>return map_coordinates(x, indices, order=<NUM_LIT:1>).reshape((shape[<NUM_LIT:0>], shape[<NUM_LIT:1>], <NUM_LIT:1>))<EOL><DEDENT>else:<EOL><INDENT>return map_coordinates(x, indices, order=<NUM_LIT:1>).reshape(shape)<EOL><DEDENT>

Elastic transformation for image as described in `[Simard2003] <http://deeplearning.cs.cmu.edu/pdfs/Simard.pdf>`__.

    Parameters
    -----------
    x : numpy.array
        A greyscale image.
    alpha : float
        Alpha value for elastic transformation.
    sigma : float or sequence of float
        The smaller the sigma, the more transformation. Standard deviation for Gaussian kernel. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes.
    mode : str
        See `scipy.ndimage.filters.gaussian_filter <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.filters.gaussian_filter.html>`__. Default is `constant`.
    cval : float,
        Used in conjunction with `mode` of `constant`, the value outside the image boundaries.
    is_random : boolean
        Default is False.

    Returns
    -------
    numpy.array
        A processed image.

    Examples
    ---------
    >>> x = tl.prepro.elastic_transform(x, alpha=x.shape[1]*3, sigma=x.shape[1]*0.07)

    References
    ------------
    - `Github <https://gist.github.com/chsasank/4d8f68caf01f041a6453e67fb30f8f5a>`__.
    - `Kaggle <https://www.kaggle.com/pscion/ultrasound-nerve-segmentation/elastic-transform-for-data-augmentation-0878921a>`__


def elastic_transform_multi(x, alpha, sigma, mode="<STR_LIT>", cval=<NUM_LIT:0>, is_random=False):

if is_random is False:<EOL><INDENT>random_state = np.random.RandomState(None)<EOL><DEDENT>else:<EOL><INDENT>random_state = np.random.RandomState(int(time.time()))<EOL><DEDENT>shape = x[<NUM_LIT:0>].shape<EOL>if len(shape) == <NUM_LIT:3>:<EOL><INDENT>shape = (shape[<NUM_LIT:0>], shape[<NUM_LIT:1>])<EOL><DEDENT>new_shape = random_state.rand(*shape)<EOL>results = []<EOL>for data in x:<EOL><INDENT>is_3d = False<EOL>if len(data.shape) == <NUM_LIT:3> and data.shape[-<NUM_LIT:1>] == <NUM_LIT:1>:<EOL><INDENT>data = data[:, :, <NUM_LIT:0>]<EOL>is_3d = True<EOL><DEDENT>elif len(data.shape) == <NUM_LIT:3> and data.shape[-<NUM_LIT:1>] != <NUM_LIT:1>:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>if len(data.shape) != <NUM_LIT:2>:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT>dx = gaussian_filter((new_shape * <NUM_LIT:2> - <NUM_LIT:1>), sigma, mode=mode, cval=cval) * alpha<EOL>dy = gaussian_filter((new_shape * <NUM_LIT:2> - <NUM_LIT:1>), sigma, mode=mode, cval=cval) * alpha<EOL>x_, y_ = np.meshgrid(np.arange(shape[<NUM_LIT:0>]), np.arange(shape[<NUM_LIT:1>]), indexing='<STR_LIT>')<EOL>indices = np.reshape(x_ + dx, (-<NUM_LIT:1>, <NUM_LIT:1>)), np.reshape(y_ + dy, (-<NUM_LIT:1>, <NUM_LIT:1>))<EOL>if is_3d:<EOL><INDENT>results.append(map_coordinates(data, indices, order=<NUM_LIT:1>).reshape((shape[<NUM_LIT:0>], shape[<NUM_LIT:1>], <NUM_LIT:1>)))<EOL><DEDENT>else:<EOL><INDENT>results.append(map_coordinates(data, indices, order=<NUM_LIT:1>).reshape(shape))<EOL><DEDENT><DEDENT>return np.asarray(results)<EOL>

Elastic transformation for images as described in `[Simard2003] <http://deeplearning.cs.cmu.edu/pdfs/Simard.pdf>`__.

    Parameters
    -----------
    x : list of numpy.array
        List of greyscale images.
    others : args
        See ``tl.prepro.elastic_transform``.

    Returns
    -------
    numpy.array
        A list of processed images.


def zoom(x, zoom_range=(<NUM_LIT>, <NUM_LIT>), flags=None, border_mode='<STR_LIT>'):

zoom_matrix = affine_zoom_matrix(zoom_range=zoom_range)<EOL>h, w = x.shape[<NUM_LIT:0>], x.shape[<NUM_LIT:1>]<EOL>transform_matrix = transform_matrix_offset_center(zoom_matrix, h, w)<EOL>x = affine_transform_cv2(x, transform_matrix, flags=flags, border_mode=border_mode)<EOL>return x<EOL>

Zooming/Scaling a single image that height and width are changed together.

    Parameters
    -----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    zoom_range : float or tuple of 2 floats
        The zooming/scaling ratio, greater than 1 means larger.
            - float, a fixed ratio.
            - tuple of 2 floats, randomly sample a value as the ratio between 2 values.
    border_mode : str
        - `constant`, pad the image with a constant value (i.e. black or 0)
        - `replicate`, the row or column at the very edge of the original is replicated to the extra border.

    Returns
    -------
    numpy.array
        A processed image.


def respective_zoom(x, h_range=(<NUM_LIT>, <NUM_LIT>), w_range=(<NUM_LIT>, <NUM_LIT>), flags=None, border_mode='<STR_LIT>'):

zoom_matrix = affine_respective_zoom_matrix(h_range=h_range, w_range=w_range)<EOL>h, w = x.shape[<NUM_LIT:0>], x.shape[<NUM_LIT:1>]<EOL>transform_matrix = transform_matrix_offset_center(zoom_matrix, h, w)<EOL>x = affine_transform_cv2(<EOL>x, transform_matrix, flags=flags, border_mode=border_mode<EOL>)  <EOL>return x<EOL>

Zooming/Scaling a single image that height and width are changed independently.

    Parameters
    -----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    h_range : float or tuple of 2 floats
        The zooming/scaling ratio of height, greater than 1 means larger.
            - float, a fixed ratio.
            - tuple of 2 floats, randomly sample a value as the ratio between 2 values.
    w_range : float or tuple of 2 floats
        The zooming/scaling ratio of width, greater than 1 means larger.
            - float, a fixed ratio.
            - tuple of 2 floats, randomly sample a value as the ratio between 2 values.
    border_mode : str
        - `constant`, pad the image with a constant value (i.e. black or 0)
        - `replicate`, the row or column at the very edge of the original is replicated to the extra border.

    Returns
    -------
    numpy.array
        A processed image.


def zoom_multi(x, zoom_range=(<NUM_LIT>, <NUM_LIT>), flags=None, border_mode='<STR_LIT>'):

zoom_matrix = affine_zoom_matrix(zoom_range=zoom_range)<EOL>results = []<EOL>for img in x:<EOL><INDENT>h, w = x.shape[<NUM_LIT:0>], x.shape[<NUM_LIT:1>]<EOL>transform_matrix = transform_matrix_offset_center(zoom_matrix, h, w)<EOL>results.append(affine_transform_cv2(x, transform_matrix, flags=flags, border_mode=border_mode))<EOL><DEDENT>return result<EOL>

Zoom in and out of images with the same arguments, randomly or non-randomly.
    Usually be used for image segmentation which x=[X, Y], X and Y should be matched.

    Parameters
    -----------
    x : list of numpy.array
        List of images with dimension of [n_images, row, col, channel] (default).
    others : args
        See ``tl.prepro.zoom``.

    Returns
    -------
    numpy.array
        A list of processed images.


def brightness(x, gamma=<NUM_LIT:1>, gain=<NUM_LIT:1>, is_random=False):

if is_random:<EOL><INDENT>gamma = np.random.uniform(<NUM_LIT:1> - gamma, <NUM_LIT:1> + gamma)<EOL><DEDENT>x = exposure.adjust_gamma(x, gamma, gain)<EOL>return x<EOL>

Change the brightness of a single image, randomly or non-randomly.

    Parameters
    -----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    gamma : float
        Non negative real number. Default value is 1.
            - Small than 1 means brighter.
            - If `is_random` is True, gamma in a range of (1-gamma, 1+gamma).
    gain : float
        The constant multiplier. Default value is 1.
    is_random : boolean
        If True, randomly change brightness. Default is False.

    Returns
    -------
    numpy.array
        A processed image.

    References
    -----------
    - `skimage.exposure.adjust_gamma <http://scikit-image.org/docs/dev/api/skimage.exposure.html>`__
    - `chinese blog <http://www.cnblogs.com/denny402/p/5124402.html>`__


def brightness_multi(x, gamma=<NUM_LIT:1>, gain=<NUM_LIT:1>, is_random=False):

if is_random:<EOL><INDENT>gamma = np.random.uniform(<NUM_LIT:1> - gamma, <NUM_LIT:1> + gamma)<EOL><DEDENT>results = []<EOL>for data in x:<EOL><INDENT>results.append(exposure.adjust_gamma(data, gamma, gain))<EOL><DEDENT>return np.asarray(results)<EOL>

Change the brightness of multiply images, randomly or non-randomly.
    Usually be used for image segmentation which x=[X, Y], X and Y should be matched.

    Parameters
    -----------
    x : list of numpyarray
        List of images with dimension of [n_images, row, col, channel] (default).
    others : args
        See ``tl.prepro.brightness``.

    Returns
    -------
    numpy.array
        A list of processed images.


def illumination(x, gamma=<NUM_LIT:1.>, contrast=<NUM_LIT:1.>, saturation=<NUM_LIT:1.>, is_random=False):

if is_random:<EOL><INDENT>if not (len(gamma) == len(contrast) == len(saturation) == <NUM_LIT:2>):<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT>illum_settings = np.random.randint(<NUM_LIT:0>, <NUM_LIT:3>)  <EOL>if illum_settings == <NUM_LIT:0>:  <EOL><INDENT>gamma = np.random.uniform(gamma[<NUM_LIT:0>], <NUM_LIT:1.0>)  <EOL><DEDENT>elif illum_settings == <NUM_LIT:1>:  <EOL><INDENT>gamma = np.random.uniform(<NUM_LIT:1.0>, gamma[<NUM_LIT:1>])  <EOL><DEDENT>else:<EOL><INDENT>gamma = <NUM_LIT:1><EOL><DEDENT>im_ = brightness(x, gamma=gamma, gain=<NUM_LIT:1>, is_random=False)<EOL>image = PIL.Image.fromarray(im_)  <EOL>contrast_adjust = PIL.ImageEnhance.Contrast(image)<EOL>image = contrast_adjust.enhance(np.random.uniform(contrast[<NUM_LIT:0>], contrast[<NUM_LIT:1>]))  <EOL>saturation_adjust = PIL.ImageEnhance.Color(image)<EOL>image = saturation_adjust.enhance(np.random.uniform(saturation[<NUM_LIT:0>], saturation[<NUM_LIT:1>]))  <EOL>im_ = np.array(image)  <EOL><DEDENT>else:<EOL><INDENT>im_ = brightness(x, gamma=gamma, gain=<NUM_LIT:1>, is_random=False)<EOL>image = PIL.Image.fromarray(im_)  <EOL>contrast_adjust = PIL.ImageEnhance.Contrast(image)<EOL>image = contrast_adjust.enhance(contrast)<EOL>saturation_adjust = PIL.ImageEnhance.Color(image)<EOL>image = saturation_adjust.enhance(saturation)<EOL>im_ = np.array(image)  <EOL><DEDENT>return np.asarray(im_)<EOL>

Perform illumination augmentation for a single image, randomly or non-randomly.

    Parameters
    -----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    gamma : float
        Change brightness (the same with ``tl.prepro.brightness``)
            - if is_random=False, one float number, small than one means brighter, greater than one means darker.
            - if is_random=True, tuple of two float numbers, (min, max).
    contrast : float
        Change contrast.
            - if is_random=False, one float number, small than one means blur.
            - if is_random=True, tuple of two float numbers, (min, max).
    saturation : float
        Change saturation.
            - if is_random=False, one float number, small than one means unsaturation.
            - if is_random=True, tuple of two float numbers, (min, max).
    is_random : boolean
        If True, randomly change illumination. Default is False.

    Returns
    -------
    numpy.array
        A processed image.

    Examples
    ---------
    Random

    >>> x = tl.prepro.illumination(x, gamma=(0.5, 5.0), contrast=(0.3, 1.0), saturation=(0.7, 1.0), is_random=True)

    Non-random

    >>> x = tl.prepro.illumination(x, 0.5, 0.6, 0.8, is_random=False)


<EOL>rgb = rgb.astype('<STR_LIT:float>')<EOL>hsv = np.zeros_like(rgb)<EOL>hsv[..., <NUM_LIT:3>:] = rgb[..., <NUM_LIT:3>:]<EOL>r, g, b = rgb[..., <NUM_LIT:0>], rgb[..., <NUM_LIT:1>], rgb[..., <NUM_LIT:2>]<EOL>maxc = np.max(rgb[..., :<NUM_LIT:3>], axis=-<NUM_LIT:1>)<EOL>minc = np.min(rgb[..., :<NUM_LIT:3>], axis=-<NUM_LIT:1>)<EOL>hsv[..., <NUM_LIT:2>] = maxc<EOL>mask = maxc != minc<EOL>hsv[mask, <NUM_LIT:1>] = (maxc - minc)[mask] / maxc[mask]<EOL>rc = np.zeros_like(r)<EOL>gc = np.zeros_like(g)<EOL>bc = np.zeros_like(b)<EOL>rc[mask] = (maxc - r)[mask] / (maxc - minc)[mask]<EOL>gc[mask] = (maxc - g)[mask] / (maxc - minc)[mask]<EOL>bc[mask] = (maxc - b)[mask] / (maxc - minc)[mask]<EOL>hsv[..., <NUM_LIT:0>] = np.select([r == maxc, g == maxc], [bc - gc, <NUM_LIT> + rc - bc], default=<NUM_LIT> + gc - rc)<EOL>hsv[..., <NUM_LIT:0>] = (hsv[..., <NUM_LIT:0>] / <NUM_LIT>) % <NUM_LIT:1.0><EOL>return hsv<EOL>

Input RGB image [0~255] return HSV image [0~1].

    Parameters
    ------------
    rgb : numpy.array
        An image with values between 0 and 255.

    Returns
    -------
    numpy.array
        A processed image.


<EOL>rgb = np.empty_like(hsv)<EOL>rgb[..., <NUM_LIT:3>:] = hsv[..., <NUM_LIT:3>:]<EOL>h, s, v = hsv[..., <NUM_LIT:0>], hsv[..., <NUM_LIT:1>], hsv[..., <NUM_LIT:2>]<EOL>i = (h * <NUM_LIT>).astype('<STR_LIT>')<EOL>f = (h * <NUM_LIT>) - i<EOL>p = v * (<NUM_LIT:1.0> - s)<EOL>q = v * (<NUM_LIT:1.0> - s * f)<EOL>t = v * (<NUM_LIT:1.0> - s * (<NUM_LIT:1.0> - f))<EOL>i = i % <NUM_LIT:6><EOL>conditions = [s == <NUM_LIT:0.0>, i == <NUM_LIT:1>, i == <NUM_LIT:2>, i == <NUM_LIT:3>, i == <NUM_LIT:4>, i == <NUM_LIT:5>]<EOL>rgb[..., <NUM_LIT:0>] = np.select(conditions, [v, q, p, p, t, v], default=v)<EOL>rgb[..., <NUM_LIT:1>] = np.select(conditions, [v, v, v, q, p, p], default=t)<EOL>rgb[..., <NUM_LIT:2>] = np.select(conditions, [v, p, t, v, v, q], default=p)<EOL>return rgb.astype('<STR_LIT>')<EOL>

Input HSV image [0~1] return RGB image [0~255].

    Parameters
    -------------
    hsv : numpy.array
        An image with values between 0.0 and 1.0

    Returns
    -------
    numpy.array
        A processed image.


def adjust_hue(im, hout=<NUM_LIT>, is_offset=True, is_clip=True, is_random=False):

hsv = rgb_to_hsv(im)<EOL>if is_random:<EOL><INDENT>hout = np.random.uniform(-hout, hout)<EOL><DEDENT>if is_offset:<EOL><INDENT>hsv[..., <NUM_LIT:0>] += hout<EOL><DEDENT>else:<EOL><INDENT>hsv[..., <NUM_LIT:0>] = hout<EOL><DEDENT>if is_clip:<EOL><INDENT>hsv[..., <NUM_LIT:0>] = np.clip(hsv[..., <NUM_LIT:0>], <NUM_LIT:0>, np.inf)  <EOL><DEDENT>rgb = hsv_to_rgb(hsv)<EOL>return rgb<EOL>

Adjust hue of an RGB image.

    This is a convenience method that converts an RGB image to float representation, converts it to HSV, add an offset to the hue channel, converts back to RGB and then back to the original data type.
    For TF, see `tf.image.adjust_hue <https://www.tensorflow.org/api_docs/python/tf/image/adjust_hue>`__.and `tf.image.random_hue <https://www.tensorflow.org/api_docs/python/tf/image/random_hue>`__.

    Parameters
    -----------
    im : numpy.array
        An image with values between 0 and 255.
    hout : float
        The scale value for adjusting hue.
            - If is_offset is False, set all hue values to this value. 0 is red; 0.33 is green; 0.66 is blue.
            - If is_offset is True, add this value as the offset to the hue channel.
    is_offset : boolean
        Whether `hout` is added on HSV as offset or not. Default is True.
    is_clip : boolean
        If HSV value smaller than 0, set to 0. Default is True.
    is_random : boolean
        If True, randomly change hue. Default is False.

    Returns
    -------
    numpy.array
        A processed image.

    Examples
    ---------
    Random, add a random value between -0.2 and 0.2 as the offset to every hue values.

    >>> im_hue = tl.prepro.adjust_hue(image, hout=0.2, is_offset=True, is_random=False)

    Non-random, make all hue to green.

    >>> im_green = tl.prepro.adjust_hue(image, hout=0.66, is_offset=False, is_random=False)

    References
    -----------
    - `tf.image.random_hue <https://www.tensorflow.org/api_docs/python/tf/image/random_hue>`__.
    - `tf.image.adjust_hue <https://www.tensorflow.org/api_docs/python/tf/image/adjust_hue>`__.
    - `StackOverflow: Changing image hue with python PIL <https://stackoverflow.com/questions/7274221/changing-image-hue-with-python-pil>`__.


def imresize(x, size=None, interp='<STR_LIT>', mode=None):

if size is None:<EOL><INDENT>size = [<NUM_LIT:100>, <NUM_LIT:100>]<EOL><DEDENT>if x.shape[-<NUM_LIT:1>] == <NUM_LIT:1>:<EOL><INDENT>x = scipy.misc.imresize(x[:, :, <NUM_LIT:0>], size, interp=interp, mode=mode)<EOL>return x[:, :, np.newaxis]<EOL><DEDENT>else:<EOL><INDENT>return scipy.misc.imresize(x, size, interp=interp, mode=mode)<EOL><DEDENT>

Resize an image by given output size and method.

    Warning, this function will rescale the value to [0, 255].

    Parameters
    -----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    size : list of 2 int or None
        For height and width.
    interp : str
        Interpolation method for re-sizing (`nearest`, `lanczos`, `bilinear`, `bicubic` (default) or `cubic`).
    mode : str
        The PIL image mode (`P`, `L`, etc.) to convert image before resizing.

    Returns
    -------
    numpy.array
        A processed image.

    References
    ------------
    - `scipy.misc.imresize <https://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imresize.html>`__


def pixel_value_scale(im, val=<NUM_LIT>, clip=None, is_random=False):

clip = clip if clip is not None else (-np.inf, np.inf)<EOL>if is_random:<EOL><INDENT>scale = <NUM_LIT:1> + np.random.uniform(-val, val)<EOL>im = im * scale<EOL><DEDENT>else:<EOL><INDENT>im = im * val<EOL><DEDENT>if len(clip) == <NUM_LIT:2>:<EOL><INDENT>im = np.clip(im, clip[<NUM_LIT:0>], clip[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>return im<EOL>

Scales each value in the pixels of the image.

    Parameters
    -----------
    im : numpy.array
        An image.
    val : float
        The scale value for changing pixel value.
            - If is_random=False, multiply this value with all pixels.
            - If is_random=True, multiply a value between [1-val, 1+val] with all pixels.
    clip : tuple of 2 numbers
        The minimum and maximum value.
    is_random : boolean
        If True, see ``val``.

    Returns
    -------
    numpy.array
        A processed image.

    Examples
    ----------
    Random

    >>> im = pixel_value_scale(im, 0.1, [0, 255], is_random=True)

    Non-random

    >>> im = pixel_value_scale(im, 0.9, [0, 255], is_random=False)


def samplewise_norm(<EOL>x, rescale=None, samplewise_center=False, samplewise_std_normalization=False, channel_index=<NUM_LIT:2>, epsilon=<NUM_LIT><EOL>):

if rescale:<EOL><INDENT>x *= rescale<EOL><DEDENT>if x.shape[channel_index] == <NUM_LIT:1>:<EOL><INDENT>if samplewise_center:<EOL><INDENT>x = x - np.mean(x)<EOL><DEDENT>if samplewise_std_normalization:<EOL><INDENT>x = x / np.std(x)<EOL><DEDENT>return x<EOL><DEDENT>elif x.shape[channel_index] == <NUM_LIT:3>:<EOL><INDENT>if samplewise_center:<EOL><INDENT>x = x - np.mean(x, axis=channel_index, keepdims=True)<EOL><DEDENT>if samplewise_std_normalization:<EOL><INDENT>x = x / (np.std(x, axis=channel_index, keepdims=True) + epsilon)<EOL><DEDENT>return x<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>" % x.shape[channel_index])<EOL><DEDENT>

Normalize an image by rescale, samplewise centering and samplewise centering in order.

    Parameters
    -----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    rescale : float
        Rescaling factor. If None or 0, no rescaling is applied, otherwise we multiply the data by the value provided (before applying any other transformation)
    samplewise_center : boolean
        If True, set each sample mean to 0.
    samplewise_std_normalization : boolean
        If True, divide each input by its std.
    epsilon : float
        A small position value for dividing standard deviation.

    Returns
    -------
    numpy.array
        A processed image.

    Examples
    --------
    >>> x = samplewise_norm(x, samplewise_center=True, samplewise_std_normalization=True)
    >>> print(x.shape, np.mean(x), np.std(x))
    (160, 176, 1), 0.0, 1.0

    Notes
    ------
    When samplewise_center and samplewise_std_normalization are True.
    - For greyscale image, every pixels are subtracted and divided by the mean and std of whole image.
    - For RGB image, every pixels are subtracted and divided by the mean and std of this pixel i.e. the mean and std of a pixel is 0 and 1.


def featurewise_norm(x, mean=None, std=None, epsilon=<NUM_LIT>):

if mean:<EOL><INDENT>x = x - mean<EOL><DEDENT>if std:<EOL><INDENT>x = x / (std + epsilon)<EOL><DEDENT>return x<EOL>

Normalize every pixels by the same given mean and std, which are usually
    compute from all examples.

    Parameters
    -----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    mean : float
        Value for subtraction.
    std : float
        Value for division.
    epsilon : float
        A small position value for dividing standard deviation.

    Returns
    -------
    numpy.array
        A processed image.


flatX = np.reshape(X, (X.shape[<NUM_LIT:0>], X.shape[<NUM_LIT:1>] * X.shape[<NUM_LIT:2>] * X.shape[<NUM_LIT:3>]))<EOL>tl.logging.info("<STR_LIT>")<EOL>sigma = np.dot(flatX.T, flatX) / flatX.shape[<NUM_LIT:0>]<EOL>tl.logging.info("<STR_LIT>")<EOL>U, S, _ = linalg.svd(sigma)  <EOL>tl.logging.info("<STR_LIT>")<EOL>principal_components = np.dot(np.dot(U, np.diag(<NUM_LIT:1.> / np.sqrt(S + <NUM_LIT>))), U.T)<EOL>return principal_components<EOL>

Return the ZCA whitening principal components matrix.

    Parameters
    -----------
    x : numpy.array
        Batch of images with dimension of [n_example, row, col, channel] (default).

    Returns
    -------
    numpy.array
        A processed image.


flatx = np.reshape(x, (x.size))<EOL>whitex = np.dot(flatx, principal_components)<EOL>x = np.reshape(whitex, (x.shape[<NUM_LIT:0>], x.shape[<NUM_LIT:1>], x.shape[<NUM_LIT:2>]))<EOL>return x<EOL>

Apply ZCA whitening on an image by given principal components matrix.

    Parameters
    -----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    principal_components : matrix
        Matrix from ``get_zca_whitening_principal_components_img``.

    Returns
    -------
    numpy.array
        A processed image.


def channel_shift(x, intensity, is_random=False, channel_index=<NUM_LIT:2>):

if is_random:<EOL><INDENT>factor = np.random.uniform(-intensity, intensity)<EOL><DEDENT>else:<EOL><INDENT>factor = intensity<EOL><DEDENT>x = np.rollaxis(x, channel_index, <NUM_LIT:0>)<EOL>min_x, max_x = np.min(x), np.max(x)<EOL>channel_images = [np.clip(x_channel + factor, min_x, max_x) for x_channel in x]<EOL>x = np.stack(channel_images, axis=<NUM_LIT:0>)<EOL>x = np.rollaxis(x, <NUM_LIT:0>, channel_index + <NUM_LIT:1>)<EOL>return x<EOL>

Shift the channels of an image, randomly or non-randomly, see `numpy.rollaxis <https://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html>`__.

    Parameters
    -----------
    x : numpy.array
        An image with dimension of [row, col, channel] (default).
    intensity : float
        Intensity of shifting.
    is_random : boolean
        If True, randomly shift. Default is False.
    channel_index : int
        Index of channel. Default is 2.

    Returns
    -------
    numpy.array
        A processed image.


def channel_shift_multi(x, intensity, is_random=False, channel_index=<NUM_LIT:2>):

if is_random:<EOL><INDENT>factor = np.random.uniform(-intensity, intensity)<EOL><DEDENT>else:<EOL><INDENT>factor = intensity<EOL><DEDENT>results = []<EOL>for data in x:<EOL><INDENT>data = np.rollaxis(data, channel_index, <NUM_LIT:0>)<EOL>min_x, max_x = np.min(data), np.max(data)<EOL>channel_images = [np.clip(x_channel + factor, min_x, max_x) for x_channel in x]<EOL>data = np.stack(channel_images, axis=<NUM_LIT:0>)<EOL>data = np.rollaxis(x, <NUM_LIT:0>, channel_index + <NUM_LIT:1>)<EOL>results.append(data)<EOL><DEDENT>return np.asarray(results)<EOL>

Shift the channels of images with the same arguments, randomly or non-randomly, see `numpy.rollaxis <https://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html>`__.
    Usually be used for image segmentation which x=[X, Y], X and Y should be matched.

    Parameters
    -----------
    x : list of numpy.array
        List of images with dimension of [n_images, row, col, channel] (default).
    others : args
        See ``tl.prepro.channel_shift``.

    Returns
    -------
    numpy.array
        A list of processed images.


if len(x.shape) == <NUM_LIT:3>:<EOL><INDENT>if x.shape[-<NUM_LIT:1>] == <NUM_LIT:3>:  <EOL><INDENT>img_size = x.shape<EOL>mask = np.random.binomial(n=<NUM_LIT:1>, p=keep, size=x.shape[:-<NUM_LIT:1>])<EOL>for i in range(<NUM_LIT:3>):<EOL><INDENT>x[:, :, i] = np.multiply(x[:, :, i], mask)<EOL><DEDENT><DEDENT>elif x.shape[-<NUM_LIT:1>] == <NUM_LIT:1>:  <EOL><INDENT>img_size = x.shape<EOL>x = np.multiply(x, np.random.binomial(n=<NUM_LIT:1>, p=keep, size=img_size))<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>".format(x.shape))<EOL><DEDENT><DEDENT>elif len(x.shape) == <NUM_LIT:2> or <NUM_LIT:1>:  <EOL><INDENT>img_size = x.shape<EOL>x = np.multiply(x, np.random.binomial(n=<NUM_LIT:1>, p=keep, size=img_size))<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>".format(x.shape))<EOL><DEDENT>return x<EOL>

Randomly set some pixels to zero by a given keeping probability.

    Parameters
    -----------
    x : numpy.array
        An image with dimension of [row, col, channel] or [row, col].
    keep : float
        The keeping probability (0, 1), the lower more values will be set to zero.

    Returns
    -------
    numpy.array
        A processed image.


def array_to_img(x, dim_ordering=(<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:2>), scale=True):

<EOL>x = x.transpose(dim_ordering)<EOL>if scale:<EOL><INDENT>x += max(-np.min(x), <NUM_LIT:0>)<EOL>x_max = np.max(x)<EOL>if x_max != <NUM_LIT:0>:<EOL><INDENT>x = x / x_max<EOL><DEDENT>x *= <NUM_LIT:255><EOL><DEDENT>if x.shape[<NUM_LIT:2>] == <NUM_LIT:3>:<EOL><INDENT>return PIL.Image.fromarray(x.astype('<STR_LIT>'), '<STR_LIT>')<EOL><DEDENT>elif x.shape[<NUM_LIT:2>] == <NUM_LIT:1>:<EOL><INDENT>return PIL.Image.fromarray(x[:, :, <NUM_LIT:0>].astype('<STR_LIT>'), '<STR_LIT:L>')<EOL><DEDENT>else:<EOL><INDENT>raise Exception('<STR_LIT>', x.shape[<NUM_LIT:2>])<EOL><DEDENT>

Converts a numpy array to PIL image object (uint8 format).

    Parameters
    ----------
    x : numpy.array
        An image with dimension of 3 and channels of 1 or 3.
    dim_ordering : tuple of 3 int
        Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
    scale : boolean
        If True, converts image to [0, 255] from any range of value like [-1, 2]. Default is True.

    Returns
    -------
    PIL.image
        An image.

    References
    -----------
    `PIL Image.fromarray <http://pillow.readthedocs.io/en/3.1.x/reference/Image.html?highlight=fromarray>`__


def find_contours(x, level=<NUM_LIT>, fully_connected='<STR_LIT>', positive_orientation='<STR_LIT>'):

return skimage.measure.find_contours(<EOL>x, level, fully_connected=fully_connected, positive_orientation=positive_orientation<EOL>)<EOL>

Find iso-valued contours in a 2D array for a given level value, returns list of (n, 2)-ndarrays
    see `skimage.measure.find_contours <http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.find_contours>`__.

    Parameters
    ------------
    x : 2D ndarray of double.
        Input data in which to find contours.
    level : float
        Value along which to find contours in the array.
    fully_connected : str
        Either `low` or `high`. Indicates whether array elements below the given level value are to be considered fully-connected (and hence elements above the value will only be face connected), or vice-versa. (See notes below for details.)
    positive_orientation : str
        Either `low` or `high`. Indicates whether the output contours will produce positively-oriented polygons around islands of low- or high-valued elements. If `low` then contours will wind counter-clockwise around elements below the iso-value. Alternately, this means that low-valued elements are always on the left of the contour.

    Returns
    --------
    list of (n,2)-ndarrays
        Each contour is an ndarray of shape (n, 2), consisting of n (row, column) coordinates along the contour.


def pt2map(list_points=None, size=(<NUM_LIT:100>, <NUM_LIT:100>), val=<NUM_LIT:1>):

if list_points is None:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>i_m = np.zeros(size)<EOL>if len(list_points) == <NUM_LIT:0>:<EOL><INDENT>return i_m<EOL><DEDENT>for xx in list_points:<EOL><INDENT>for x in xx:<EOL><INDENT>i_m[int(np.round(x[<NUM_LIT:0>]))][int(np.round(x[<NUM_LIT:1>]))] = val<EOL><DEDENT><DEDENT>return i_m<EOL>

Inputs a list of points, return a 2D image.

    Parameters
    --------------
    list_points : list of 2 int
        [[x, y], [x, y]..] for point coordinates.
    size : tuple of 2 int
        (w, h) for output size.
    val : float or int
        For the contour value.

    Returns
    -------
    numpy.array
        An image.


mask = disk(radius)<EOL>x = _binary_dilation(x, selem=mask)<EOL>return x<EOL>

Return fast binary morphological dilation of an image.
    see `skimage.morphology.binary_dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_dilation>`__.

    Parameters
    -----------
    x : 2D array
        A binary image.
    radius : int
        For the radius of mask.

    Returns
    -------
    numpy.array
        A processed binary image.


mask = disk(radius)<EOL>x = dilation(x, selem=mask)<EOL>return x<EOL>

Return greyscale morphological dilation of an image,
    see `skimage.morphology.dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.dilation>`__.

    Parameters
    -----------
    x : 2D array
        An greyscale image.
    radius : int
        For the radius of mask.

    Returns
    -------
    numpy.array
        A processed greyscale image.


mask = disk(radius)<EOL>x = _binary_erosion(x, selem=mask)<EOL>return x<EOL>

Return binary morphological erosion of an image,
    see `skimage.morphology.binary_erosion <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_erosion>`__.

    Parameters
    -----------
    x : 2D array
        A binary image.
    radius : int
        For the radius of mask.

    Returns
    -------
    numpy.array
        A processed binary image.


mask = disk(radius)<EOL>x = _erosion(x, selem=mask)<EOL>return x<EOL>

Return greyscale morphological erosion of an image,
    see `skimage.morphology.erosion <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.erosion>`__.

    Parameters
    -----------
    x : 2D array
        A greyscale image.
    radius : int
        For the radius of mask.

    Returns
    -------
    numpy.array
        A processed greyscale image.


if coords is None:<EOL><INDENT>coords = []<EOL><DEDENT>if shape is None:<EOL><INDENT>shape = [<NUM_LIT:100>, <NUM_LIT:200>]<EOL><DEDENT>imh, imw = shape[<NUM_LIT:0>], shape[<NUM_LIT:1>]<EOL>imh = imh * <NUM_LIT:1.0>  <EOL>imw = imw * <NUM_LIT:1.0><EOL>coords_new = list()<EOL>for coord in coords:<EOL><INDENT>if len(coord) != <NUM_LIT:4>:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT>x = coord[<NUM_LIT:0>] / imw<EOL>y = coord[<NUM_LIT:1>] / imh<EOL>w = coord[<NUM_LIT:2>] / imw<EOL>h = coord[<NUM_LIT:3>] / imh<EOL>coords_new.append([x, y, w, h])<EOL><DEDENT>return coords_new<EOL>

Scale down a list of coordinates from pixel unit to the ratio of image size i.e. in the range of [0, 1].

    Parameters
    ------------
    coords : list of list of 4 ints or None
        For coordinates of more than one images .e.g.[[x, y, w, h], [x, y, w, h], ...].
    shape : list of 2 int or None
        【height, width].

    Returns
    -------
    list of list of 4 numbers
        A list of new bounding boxes.

    Examples
    ---------
    >>> coords = obj_box_coords_rescale(coords=[[30, 40, 50, 50], [10, 10, 20, 20]], shape=[100, 100])
    >>> print(coords)
      [[0.3, 0.4, 0.5, 0.5], [0.1, 0.1, 0.2, 0.2]]
    >>> coords = obj_box_coords_rescale(coords=[[30, 40, 50, 50]], shape=[50, 100])
    >>> print(coords)
      [[0.3, 0.8, 0.5, 1.0]]
    >>> coords = obj_box_coords_rescale(coords=[[30, 40, 50, 50]], shape=[100, 200])
    >>> print(coords)
      [[0.15, 0.4, 0.25, 0.5]]

    Returns
    -------
    list of 4 numbers
        New coordinates.


if coord is None:<EOL><INDENT>coord = []<EOL><DEDENT>if shape is None:<EOL><INDENT>shape = [<NUM_LIT:100>, <NUM_LIT:200>]<EOL><DEDENT>return obj_box_coords_rescale(coords=[coord], shape=shape)[<NUM_LIT:0>]<EOL>

Scale down one coordinates from pixel unit to the ratio of image size i.e. in the range of [0, 1].
    It is the reverse process of ``obj_box_coord_scale_to_pixelunit``.

    Parameters
    ------------
    coords : list of 4 int or None
        One coordinates of one image e.g. [x, y, w, h].
    shape : list of 2 int or None
        For [height, width].

    Returns
    -------
    list of 4 numbers
        New bounding box.

    Examples
    ---------
    >>> coord = tl.prepro.obj_box_coord_rescale(coord=[30, 40, 50, 50], shape=[100, 100])
      [0.3, 0.4, 0.5, 0.5]


if shape is None:<EOL><INDENT>shape = [<NUM_LIT:100>, <NUM_LIT:100>]<EOL><DEDENT>imh, imw = shape[<NUM_LIT:0>:<NUM_LIT:2>]<EOL>x = int(coord[<NUM_LIT:0>] * imw)<EOL>x2 = int(coord[<NUM_LIT:2>] * imw)<EOL>y = int(coord[<NUM_LIT:1>] * imh)<EOL>y2 = int(coord[<NUM_LIT:3>] * imh)<EOL>return [x, y, x2, y2]<EOL>

Convert one coordinate [x, y, w (or x2), h (or y2)] in ratio format to image coordinate format.
    It is the reverse process of ``obj_box_coord_rescale``.

    Parameters
    -----------
    coord : list of 4 float
        One coordinate of one image [x, y, w (or x2), h (or y2)] in ratio format, i.e value range [0~1].
    shape : tuple of 2 or None
        For [height, width].

    Returns
    -------
    list of 4 numbers
        New bounding box.

    Examples
    ---------
    >>> x, y, x2, y2 = tl.prepro.obj_box_coord_scale_to_pixelunit([0.2, 0.3, 0.5, 0.7], shape=(100, 200, 3))
      [40, 30, 100, 70]


if len(coord) != <NUM_LIT:4>:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT>x_center, y_center, w, h = coord<EOL>x = x_center - w / <NUM_LIT><EOL>y = y_center - h / <NUM_LIT><EOL>x2 = x + w<EOL>y2 = y + h<EOL>if to_int:<EOL><INDENT>return [int(x), int(y), int(x2), int(y2)]<EOL><DEDENT>else:<EOL><INDENT>return [x, y, x2, y2]<EOL><DEDENT>

Convert one coordinate [x_center, y_center, w, h] to [x1, y1, x2, y2] in up-left and botton-right format.

    Parameters
    ------------
    coord : list of 4 int/float
        One coordinate.
    to_int : boolean
        Whether to convert output as integer.

    Returns
    -------
    list of 4 numbers
        New bounding box.

    Examples
    ---------
    >>> coord = obj_box_coord_centroid_to_upleft_butright([30, 40, 20, 20])
      [20, 30, 40, 50]


if len(coord) != <NUM_LIT:4>:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT>x1, y1, x2, y2 = coord<EOL>w = x2 - x1<EOL>h = y2 - y1<EOL>x_c = x1 + w / <NUM_LIT><EOL>y_c = y1 + h / <NUM_LIT><EOL>return [x_c, y_c, w, h]<EOL>

Convert one coordinate [x1, y1, x2, y2] to [x_center, y_center, w, h].
    It is the reverse process of ``obj_box_coord_centroid_to_upleft_butright``.

    Parameters
    ------------
    coord : list of 4 int/float
        One coordinate.

    Returns
    -------
    list of 4 numbers
        New bounding box.


if len(coord) != <NUM_LIT:4>:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT>x_center, y_center, w, h = coord<EOL>x = x_center - w / <NUM_LIT><EOL>y = y_center - h / <NUM_LIT><EOL>return [x, y, w, h]<EOL>

Convert one coordinate [x_center, y_center, w, h] to [x, y, w, h].
    It is the reverse process of ``obj_box_coord_upleft_to_centroid``.

    Parameters
    ------------
    coord : list of 4 int/float
        One coordinate.

    Returns
    -------
    list of 4 numbers
        New bounding box.


if len(coord) != <NUM_LIT:4>:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT>x, y, w, h = coord<EOL>x_center = x + w / <NUM_LIT><EOL>y_center = y + h / <NUM_LIT><EOL>return [x_center, y_center, w, h]<EOL>

Convert one coordinate [x, y, w, h] to [x_center, y_center, w, h].
    It is the reverse process of ``obj_box_coord_centroid_to_upleft``.

    Parameters
    ------------
    coord : list of 4 int/float
        One coordinate.

    Returns
    -------
    list of 4 numbers
        New bounding box.


annotations = annotations.split("<STR_LIT:\n>")<EOL>ann = []<EOL>for a in annotations:<EOL><INDENT>a = a.split()<EOL>if len(a) == <NUM_LIT:5>:<EOL><INDENT>for i, _v in enumerate(a):<EOL><INDENT>if i == <NUM_LIT:0>:<EOL><INDENT>a[i] = int(a[i])<EOL><DEDENT>else:<EOL><INDENT>a[i] = float(a[i])<EOL><DEDENT><DEDENT>ann.append(a)<EOL><DEDENT><DEDENT>return ann<EOL>

r"""Input string format of class, x, y, w, h, return list of list format.

    Parameters
    -----------
    annotations : str
        The annotations in darkent format "class, x, y, w, h ...." seperated by "\\n".

    Returns
    -------
    list of list of 4 numbers
        List of bounding box.


class_list = []<EOL>bbox_list = []<EOL>for ann in annotations:<EOL><INDENT>class_list.append(ann[<NUM_LIT:0>])<EOL>bbox_list.append(ann[<NUM_LIT:1>:])<EOL><DEDENT>return class_list, bbox_list<EOL>

Parse darknet annotation format into two lists for class and bounding box.

    Input list of [[class, x, y, w, h], ...], return two list of [class ...] and [[x, y, w, h], ...].

    Parameters
    ------------
    annotations : list of list
        A list of class and bounding boxes of images e.g. [[class, x, y, w, h], ...]

    Returns
    -------
    list of int
        List of class labels.

    list of list of 4 numbers
        List of bounding box.


def obj_box_horizontal_flip(im, coords=None, is_rescale=False, is_center=False, is_random=False):

if coords is None:<EOL><INDENT>coords = []<EOL><DEDENT>def _flip(im, coords):<EOL><INDENT>im = flip_axis(im, axis=<NUM_LIT:1>, is_random=False)<EOL>coords_new = list()<EOL>for coord in coords:<EOL><INDENT>if len(coord) != <NUM_LIT:4>:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT>if is_rescale:<EOL><INDENT>if is_center:<EOL><INDENT>x = <NUM_LIT:1.> - coord[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>x = <NUM_LIT:1.> - coord[<NUM_LIT:0>] - coord[<NUM_LIT:2>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if is_center:<EOL><INDENT>x = im.shape[<NUM_LIT:1>] - coord[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>x = im.shape[<NUM_LIT:1>] - coord[<NUM_LIT:0>] - coord[<NUM_LIT:2>]<EOL><DEDENT><DEDENT>coords_new.append([x, coord[<NUM_LIT:1>], coord[<NUM_LIT:2>], coord[<NUM_LIT:3>]])<EOL><DEDENT>return im, coords_new<EOL><DEDENT>if is_random:<EOL><INDENT>factor = np.random.uniform(-<NUM_LIT:1>, <NUM_LIT:1>)<EOL>if factor > <NUM_LIT:0>:<EOL><INDENT>return _flip(im, coords)<EOL><DEDENT>else:<EOL><INDENT>return im, coords<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return _flip(im, coords)<EOL><DEDENT>

Left-right flip the image and coordinates for object detection.

    Parameters
    ----------
    im : numpy.array
        An image with dimension of [row, col, channel] (default).
    coords : list of list of 4 int/float or None
        Coordinates [[x, y, w, h], [x, y, w, h], ...].
    is_rescale : boolean
        Set to True, if the input coordinates are rescaled to [0, 1]. Default is False.
    is_center : boolean
        Set to True, if the x and y of coordinates are the centroid (i.e. darknet format). Default is False.
    is_random : boolean
        If True, randomly flip. Default is False.

    Returns
    -------
    numpy.array
        A processed image
    list of list of 4 numbers
        A list of new bounding boxes.

    Examples
    --------
    >>> im = np.zeros([80, 100])    # as an image with shape width=100, height=80
    >>> im, coords = obj_box_left_right_flip(im, coords=[[0.2, 0.4, 0.3, 0.3], [0.1, 0.5, 0.2, 0.3]], is_rescale=True, is_center=True, is_random=False)
    >>> print(coords)
      [[0.8, 0.4, 0.3, 0.3], [0.9, 0.5, 0.2, 0.3]]
    >>> im, coords = obj_box_left_right_flip(im, coords=[[0.2, 0.4, 0.3, 0.3]], is_rescale=True, is_center=False, is_random=False)
    >>> print(coords)
      [[0.5, 0.4, 0.3, 0.3]]
    >>> im, coords = obj_box_left_right_flip(im, coords=[[20, 40, 30, 30]], is_rescale=False, is_center=True, is_random=False)
    >>> print(coords)
      [[80, 40, 30, 30]]
    >>> im, coords = obj_box_left_right_flip(im, coords=[[20, 40, 30, 30]], is_rescale=False, is_center=False, is_random=False)
    >>> print(coords)
      [[50, 40, 30, 30]]


def obj_box_imresize(im, coords=None, size=None, interp='<STR_LIT>', mode=None, is_rescale=False):

if coords is None:<EOL><INDENT>coords = []<EOL><DEDENT>if size is None:<EOL><INDENT>size = [<NUM_LIT:100>, <NUM_LIT:100>]<EOL><DEDENT>imh, imw = im.shape[<NUM_LIT:0>:<NUM_LIT:2>]<EOL>imh = imh * <NUM_LIT:1.0>  <EOL>imw = imw * <NUM_LIT:1.0><EOL>im = imresize(im, size=size, interp=interp, mode=mode)<EOL>if is_rescale is False:<EOL><INDENT>coords_new = list()<EOL>for coord in coords:<EOL><INDENT>if len(coord) != <NUM_LIT:4>:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT>x = int(coord[<NUM_LIT:0>] * (size[<NUM_LIT:1>] / imw))<EOL>y = int(coord[<NUM_LIT:1>] * (size[<NUM_LIT:0>] / imh))<EOL>w = int(coord[<NUM_LIT:2>] * (size[<NUM_LIT:1>] / imw))<EOL>h = int(coord[<NUM_LIT:3>] * (size[<NUM_LIT:0>] / imh))<EOL>coords_new.append([x, y, w, h])<EOL><DEDENT>return im, coords_new<EOL><DEDENT>else:<EOL><INDENT>return im, coords<EOL><DEDENT>

Resize an image, and compute the new bounding box coordinates.

    Parameters
    -------------
    im : numpy.array
        An image with dimension of [row, col, channel] (default).
    coords : list of list of 4 int/float or None
        Coordinates [[x, y, w, h], [x, y, w, h], ...]
    size interp and mode : args
        See ``tl.prepro.imresize``.
    is_rescale : boolean
        Set to True, if the input coordinates are rescaled to [0, 1], then return the original coordinates. Default is False.

    Returns
    -------
    numpy.array
        A processed image
    list of list of 4 numbers
        A list of new bounding boxes.

    Examples
    --------
    >>> im = np.zeros([80, 100, 3])    # as an image with shape width=100, height=80
    >>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30], [10, 20, 20, 20]], size=[160, 200], is_rescale=False)
    >>> print(coords)
      [[40, 80, 60, 60], [20, 40, 40, 40]]
    >>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30]], size=[40, 100], is_rescale=False)
    >>> print(coords)
      [[20, 20, 30, 15]]
    >>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30]], size=[60, 150], is_rescale=False)
    >>> print(coords)
      [[30, 30, 45, 22]]
    >>> im2, coords = obj_box_imresize(im, coords=[[0.2, 0.4, 0.3, 0.3]], size=[160, 200], is_rescale=True)
    >>> print(coords, im2.shape)
      [[0.2, 0.4, 0.3, 0.3]] (160, 200, 3)