-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsparse_deconv.py
245 lines (196 loc) · 7.73 KB
/
sparse_deconv.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
import warnings
import numpy as np
import matplotlib.pyplot as plt
try:
import cupy
except ImportError:
cupy = None
xp = np if cupy is None else cupy
## adapted from https://github.com/tlambert03/pycudasirecon/blob/master/pycudasirecon/_hessian.py
def sparse_hessian_denoise(initial: np.ndarray, iters=50, mu=100, sigma: float = 1, lamda=1,sparsity=5):
"""
sparse hessian deconv
Parameters
----------
initial : np.ndarray
input image
iters : int, optional
number of iterations, by default 50
mu : int, optional
tradeoff between resolution and denoising. Higher values result in increased
resolution but increased noise, by default 150
sigma : float, optional
When structures change slowly along the Z/T axis, use a value between
0 and 1 to obtain trade-off between effective denoising and minimal temporal
blurring. Set to zero to turn off regularization along the Z/T axis.
by default 1
lamda : int, optional
[description], by default 1
Returns
-------
result: np.ndarray
denoised image
"""
## ensure whether the cupy is avaliable
if xp is not cupy:
warnings.warn("could not import cupy... falling back to numpy & cpu.")
## initial data type as cupy array
initial = xp.asarray(initial, dtype="single")
if initial.ndim == 2 or initial.shape[0] < 3:
sigma = 0
warnings.warn(
"Number of Z/T planes is smaller than 3, the t and z-axis of "
"Hessian was turned off(sigma=0)"
)
if initial.ndim == 2:
initial = xp.tile(initial, [3, 1, 1])
elif initial.ndim == 3:
if initial.shape[0] == 1:
initial = xp.tile(initial[-1], [3, 1, 1])
elif initial.shape[0] == 2:
initial = xp.concatenate([initial, xp.expand_dims(initial[-1], 0)], 0)
## mu/lamda
_mu_d_lamda = mu / lamda
ymax = initial.max()
initial /= ymax
sizex = initial.shape
## initialize denominator(include fft_of_diff+ mu/lambda + lambda_l1^2)
## the value just need calculate once
divide = (_fft_of_diff(sizex, sigma) + _mu_d_lamda + sparsity**2).astype(xp.float32)
## initialize b
## 7 channels b
bs = xp.zeros((7,) + sizex, "float32")
## initialize output x
x = xp.zeros(sizex, "float32")
frac = _mu_d_lamda * initial
for ii in range(iters):
frac = xp.fft.fftn(frac)
divisor = divide if ii >= 1 else _mu_d_lamda
x = xp.fft.ifftn(frac / divisor).real
frac = _mu_d_lamda * initial
frac += _bfbf(bs[0], 1, 1, x, lamda)
frac += _bfbf(bs[1], 2, 2, x, lamda)
frac += _bfbf(bs[2], 0, 0, x, lamda)
frac += _ffbb(bs[3], 1, 2, x, lamda)
frac += sigma * _ffbb(bs[4], 1, 0, x, lamda)
frac += sigma * _ffbb(bs[5], 2, 0, x, lamda)
## add sparsity
frac += sparsity * _Lsparse(bs[6],x,lamda)
# plt.figure()
# temp = bs[3]
# plt.imshow(xp.asnumpy(temp[50,:,:].real))
# plt.show
x.clip(0, out=x)
if x.shape != initial.shape:
x = x[: initial.shape[0]]
x *= ymax
return x.get() if hasattr(x, "get") else x
def hessian_denoise(initial: np.ndarray, iters=50, mu=150, sigma: float = 1, lamda=1):
"""Hessian (Split-Bregman) SIM denoise algorithm.
May be applied to images images reconstructed with Wiener method to further
reduce noise.
Adapted from MATLAB code published in Huang et al 2018 [1]_.
See supplementary information (fig 7) for details on the paramaeters.
Parameters
----------
initial : np.ndarray
input image
iters : int, optional
number of iterations, by default 50
mu : int, optional
tradeoff between resolution and denoising. Higher values result in increased
resolution but increased noise, by default 150
sigma : float, optional
When structures change slowly along the Z/T axis, use a value between
0 and 1 to obtain trade-off between effective denoising and minimal temporal
blurring. Set to zero to turn off regularization along the Z/T axis.
by default 1
lamda : int, optional
[description], by default 1
Returns
-------
result: np.ndarray
denoised image
References
----------
.. [1] Huang, X., Fan, J., Li, L. et al. Fast, long-term, super-resolution imaging
with Hessian structured illumination microscopy. Nat Biotechnol 36, 451–459
(2018). https://doi-org.ezp-prod1.hul.harvard.edu/10.1038/nbt.4115
"""
if xp is not cupy:
warnings.warn("could not import cupy... falling back to numpy & cpu.")
initial = xp.asarray(initial, dtype="single")
if initial.ndim == 2 or initial.shape[0] < 3:
sigma = 0
warnings.warn(
"Number of Z/T planes is smaller than 3, the t and z-axis of "
"Hessian was turned off(sigma=0)"
)
if initial.ndim == 2:
initial = xp.tile(initial, [3, 1, 1])
elif initial.ndim == 3:
if initial.shape[0] == 1:
initial = xp.tile(initial[-1], [3, 1, 1])
elif initial.shape[0] == 2:
initial = xp.concatenate([initial, xp.expand_dims(initial[-1], 0)], 0)
_mu_d_lamda = mu / lamda
ymax = initial.max()
initial /= ymax
sizex = initial.shape
divide = (_fft_of_diff(sizex, sigma) + _mu_d_lamda).astype(xp.float32)
bs = xp.zeros((6,) + sizex, "float32")
x = xp.zeros(sizex, "int32")
frac = _mu_d_lamda * initial
for ii in range(iters):
frac = xp.fft.fftn(frac)
divisor = divide if ii >= 1 else _mu_d_lamda
x = xp.fft.ifftn(frac / divisor).real
frac = _mu_d_lamda * initial
frac += _bfbf(bs[0], 1, 1, x, lamda)
frac += _bfbf(bs[1], 2, 2, x, lamda)
frac += _bfbf(bs[2], 0, 0, x, lamda)
frac += _ffbb(bs[3], 1, 2, x, lamda)
frac += sigma * _ffbb(bs[4], 1, 0, x, lamda)
frac += sigma * _ffbb(bs[5], 2, 0, x, lamda)
x.clip(0, out=x)
if x.shape != initial.shape:
x = x[: initial.shape[0]]
x *= ymax
return x.get() if hasattr(x, "get") else x
def _fft_of_diff(shape, sigma):
# FFTs of difference operator
_v0 = xp.array([1, -2, 1])
_v1 = xp.array([[1, -1], [-1, 1]])
divide = (
_fconj(_v0.reshape((1, 1, 3)), shape)
+ _fconj(_v0.reshape((1, 3, 1)), shape)
+ (sigma ** 2) * _fconj(_v0.reshape((3, 1, 1)), shape)
+ 2 * _fconj(_v1.reshape((1, 2, 2)), shape)
+ 2 * sigma * _fconj(_v1.reshape((2, 1, 2)), shape)
+ 2 * sigma * _fconj(_v1.reshape((2, 2, 1)), shape)
)
return divide.real
def _fconj(array, shape):
tmp_fft = xp.fft.fftn(array, shape)
return tmp_fft * xp.conj(tmp_fft)
def _forward_diff(data, axis):
return xp.diff(data, axis=axis, append=0)
def _back_diff(data, axis):
return xp.diff(data, axis=axis, prepend=0)
def _middle(u, b_, lamda):
signd = abs(u + b_) - 1 / lamda
signd.clip(0, out=signd)
signd *= xp.sign(u + b_)
b_ += u - signd
return signd
def _bfbf(b_, c0, c1, x, lamda):
u = _back_diff(_forward_diff(x, c0), c1)
signd = _middle(u, b_, lamda)
return _back_diff(_forward_diff(signd - b_, c1), c0)
def _ffbb(b_, c0, c1, x, lamda):
u = _forward_diff(_forward_diff(x, c0), c1)
signd = _middle(u, b_, lamda)
return 2 * _back_diff(_back_diff(signd - b_, c1), c0)
def _Lsparse(b_,x,lamda):
signd = _middle(x,b_,lamda)
return signd - b_