/
general.py
76 lines (61 loc) · 1.62 KB
/
general.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import numpy as np
import pylab
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
from scipy import ndimage
# TODO: try to not make use of transform.resize
from skimage import transform
def crop(M, n=None):
""" crop - crop an image to reduce its size
Only crops square black and white images for now.
"""
# Check that image is square and black and white (no channels)
assert M.shape[0] == M.shape[1]
assert len(M.shape) == 2
n0 = M.shape[0]
if n is None:
n = (n0/2)
# Start and end of selection
start_ind = int(np.floor((n0 - n) / 2))
end_ind = int(-np.ceil((n0 - n) / 2))
return M[start_ind:end_ind, start_ind:end_ind]
def circshift(x, p):
"""
Circular shift of an array.
"""
y = x.copy()
y = np.concatenate((y[p[0]::, :], y[:p[0]:, :]), axis=0)
if x.shape[1] > 0 and len(p) > 1:
y = np.concatenate((y[:, p[0]::], y[:, :p[0]:]), axis=1)
return y
def circshift1d(x, k):
"""
Circularly shift a 1D vector
"""
return np.roll(x, -k, axis=0)
def clamp(x, a=[], b=[]):
"""
clamp - clamp a value
y = clamp(x,a,b);
Default is [a,b]=[0,1].
Copyright (c) 2004 Gabriel Peyre
"""
if a == []:
a = 0.0
if b == []:
b = 1.0
return np.minimum(np.maximum(x, a), b)
def rescale(f,a=0,b=1):
"""
Rescale linearly the dynamic of a vector to fit within a range [a,b]
"""
v = f.max() - f.min()
g = (f - f.min()).copy()
if v > 0:
g = g / v
return a + g*(b-a)
def reverse(x):
"""
Reverse a vector.
"""
return x[::-1]