/
lpi_filter.py
251 lines (191 loc) · 7.18 KB
/
lpi_filter.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
"""
:author: Stefan van der Walt, 2008
:license: modified BSD
"""
import numpy as np
from scipy.fftpack import ifftshift
from .._shared.utils import assert_nD
eps = np.finfo(float).eps
def _min_limit(x, val=eps):
mask = np.abs(x) < eps
x[mask] = np.sign(x[mask]) * eps
def _centre(x, oshape):
"""Return an array of oshape from the centre of x.
"""
start = (np.array(x.shape) - np.array(oshape)) // 2 + 1
out = x[[slice(s, s + n) for s, n in zip(start, oshape)]]
return out
def _pad(data, shape):
"""Pad the data to the given shape with zeros.
Parameters
----------
data : 2-d ndarray
Input data
shape : (2,) tuple
"""
out = np.zeros(shape)
out[[slice(0, n) for n in data.shape]] = data
return out
class LPIFilter2D(object):
"""Linear Position-Invariant Filter (2-dimensional)
"""
def __init__(self, impulse_response, **filter_params):
"""
Parameters
----------
impulse_response : callable `f(r, c, **filter_params)`
Function that yields the impulse response. `r` and `c` are
1-dimensional vectors that represent row and column positions, in
other words coordinates are (r[0],c[0]),(r[0],c[1]) etc.
`**filter_params` are passed through.
In other words, `impulse_response` would be called like this:
>>> def impulse_response(r, c, **filter_params):
... pass
>>>
>>> r = [0,0,0,1,1,1,2,2,2]
>>> c = [0,1,2,0,1,2,0,1,2]
>>> filter_params = {'kw1': 1, 'kw2': 2, 'kw3': 3}
>>> impulse_response(r, c, **filter_params)
Examples
--------
Gaussian filter: Use a 1-D gaussian in each direction without
normalization coefficients.
>>> def filt_func(r, c, sigma = 1):
... return np.exp(-np.hypot(r, c)/sigma)
>>> filter = LPIFilter2D(filt_func)
"""
if not callable(impulse_response):
raise ValueError("Impulse response must be a callable.")
self.impulse_response = impulse_response
self.filter_params = filter_params
self._cache = None
def _prepare(self, data):
"""Calculate filter and data FFT in preparation for filtering.
"""
dshape = np.array(data.shape)
dshape += (dshape % 2 == 0) # all filter dimensions must be uneven
oshape = np.array(data.shape) * 2 - 1
if self._cache is None or np.any(self._cache.shape != oshape):
coords = np.mgrid[[slice(0, float(n)) for n in dshape]]
# this steps over two sets of coordinates,
# not over the coordinates individually
for k, coord in enumerate(coords):
coord -= (dshape[k] - 1) / 2.
coords = coords.reshape(2, -1).T # coordinate pairs (r,c)
f = self.impulse_response(coords[:, 0], coords[:, 1],
**self.filter_params).reshape(dshape)
f = _pad(f, oshape)
F = np.dual.fftn(f)
self._cache = F
else:
F = self._cache
data = _pad(data, oshape)
G = np.dual.fftn(data)
return F, G
def __call__(self, data):
"""Apply the filter to the given data.
Parameters
----------
data : (M,N) ndarray
"""
assert_nD(data, 2, 'data')
F, G = self._prepare(data)
out = np.dual.ifftn(F * G)
out = np.abs(_centre(out, data.shape))
return out
def forward(data, impulse_response=None, filter_params={},
predefined_filter=None):
"""Apply the given filter to data.
Parameters
----------
data : (M,N) ndarray
Input data.
impulse_response : callable `f(r, c, **filter_params)`
Impulse response of the filter. See LPIFilter2D.__init__.
filter_params : dict
Additional keyword parameters to the impulse_response function.
Other Parameters
----------------
predefined_filter : LPIFilter2D
If you need to apply the same filter multiple times over different
images, construct the LPIFilter2D and specify it here.
Examples
--------
Gaussian filter:
>>> def filt_func(r, c):
... return np.exp(-np.hypot(r, c)/1)
>>>
>>> from skimage import data
>>> filtered = forward(data.coins(), filt_func)
"""
assert_nD(data, 2, 'data')
if predefined_filter is None:
predefined_filter = LPIFilter2D(impulse_response, **filter_params)
return predefined_filter(data)
def inverse(data, impulse_response=None, filter_params={}, max_gain=2,
predefined_filter=None):
"""Apply the filter in reverse to the given data.
Parameters
----------
data : (M,N) ndarray
Input data.
impulse_response : callable `f(r, c, **filter_params)`
Impulse response of the filter. See LPIFilter2D.__init__.
filter_params : dict
Additional keyword parameters to the impulse_response function.
max_gain : float
Limit the filter gain. Often, the filter contains zeros, which would
cause the inverse filter to have infinite gain. High gain causes
amplification of artefacts, so a conservative limit is recommended.
Other Parameters
----------------
predefined_filter : LPIFilter2D
If you need to apply the same filter multiple times over different
images, construct the LPIFilter2D and specify it here.
"""
assert_nD(data, 2, 'data')
if predefined_filter is None:
filt = LPIFilter2D(impulse_response, **filter_params)
else:
filt = predefined_filter
F, G = filt._prepare(data)
_min_limit(F)
F = 1 / F
mask = np.abs(F) > max_gain
F[mask] = np.sign(F[mask]) * max_gain
return _centre(np.abs(ifftshift(np.dual.ifftn(G * F))), data.shape)
def wiener(data, impulse_response=None, filter_params={}, K=0.25,
predefined_filter=None):
"""Minimum Mean Square Error (Wiener) inverse filter.
Parameters
----------
data : (M,N) ndarray
Input data.
K : float or (M,N) ndarray
Ratio between power spectrum of noise and undegraded
image.
impulse_response : callable `f(r, c, **filter_params)`
Impulse response of the filter. See LPIFilter2D.__init__.
filter_params : dict
Additional keyword parameters to the impulse_response function.
Other Parameters
----------------
predefined_filter : LPIFilter2D
If you need to apply the same filter multiple times over different
images, construct the LPIFilter2D and specify it here.
"""
assert_nD(data, 2, 'data')
if not isinstance(K, float):
assert_nD(K, 2, 'K')
if predefined_filter is None:
filt = LPIFilter2D(impulse_response, **filter_params)
else:
filt = predefined_filter
F, G = filt._prepare(data)
_min_limit(F)
H_mag_sqr = np.abs(F) ** 2
F = 1 / F * H_mag_sqr / (H_mag_sqr + K)
return _centre(np.abs(ifftshift(np.dual.ifftn(G * F))), data.shape)
def constrained_least_squares(data, lam, impulse_response=None,
filter_params={}):
raise NotImplementedError