Skip to content

Instantly share code, notes, and snippets.

@Dref360
Created February 2, 2018 16:46
Show Gist options
  • Select an option

  • Save Dref360/f8dc71d71f00e319b76e67668afeb7ac to your computer and use it in GitHub Desktop.

Select an option

Save Dref360/f8dc71d71f00e319b76e67668afeb7ac to your computer and use it in GitHub Desktop.
Exemple for my class on the importance of clearability
"""Good example"""
def random_shift(x, wrg, hrg, row_axis=1, col_axis=2, channel_axis=0,
fill_mode='nearest', cval=0., tx=None, ty=None):
"""Performs a random spatial shift of a Numpy image tensor.
# Arguments
x: Input tensor. Must be 3D.
wrg: Width shift range, as a float fraction of the width.
hrg: Height shift range, as a float fraction of the height.
row_axis: Index of axis for rows in the input tensor.
col_axis: Index of axis for columns in the input tensor.
channel_axis: Index of axis for channels in the input tensor.
fill_mode: Points outside the boundaries of the input
are filled according to the given mode
(one of `{'constant', 'nearest', 'reflect', 'wrap'}`).
cval: Value used for points outside the boundaries
of the input if `mode='constant'`.
tx : Value to disable randomness in X or None.
ty : Value to disable randomness in Y or None.
# Returns
Shifted Numpy image tensor.
"""
h, w = x.shape[row_axis], x.shape[col_axis]
tx = np.random.uniform(-hrg, hrg) * h if tx is None else tx
ty = np.random.uniform(-wrg, wrg) * w if ty is None else ty
tx *= h
ty *= w
translation_matrix = np.array([[1, 0, tx],
[0, 1, ty],
[0, 0, 1]])
transform_matrix = translation_matrix # no need to do offset
x = apply_transform(x, transform_matrix, channel_axis, fill_mode, cval)
return x
"""BAD FORMAT, hard to read"""
def random_shift(x,wrg,hrg,row_axis=1,col_axis=2,channel_axis=0,fill_mode='nearest',cval=0.,tx=None,ty=None):
h, w = x.shape[row_axis],x.shape[col_axis]
tx=np.random.uniform(-hrg,hrg)*h if tx is None else tx
ty=np.random.uniform(-wrg,wrg)*w if ty is None else ty
tx*=h
ty*=w
translation_matrix=np.array([[1,0,tx],[0,1,ty],[0,0,1]])
transform_matrix=translation_matrix
x=apply_transform(x,transform_matrix,channel_axis,fill_mode,cval)
return x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment