/
utility.py
1428 lines (1294 loc) · 48.4 KB
/
utility.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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ============================================================================
# ============================================================================
# Copyright (c) 2021 Nghia T. Vo. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
# Author: Nghia T. Vo
# E-mail:
# Description: Utility methods
# Contributors:
# ============================================================================
"""
Module of utility methods:
- Methods for parallel computing, geometric transformation, masking.
- Methods for customizing stripe/ring removal methods
+ sort_forward
+ sort_backward
+ separate_frequency_component
+ generate_fitted_image
+ detect_stripe
+ calculate_regularization_coefficient
+ make_2d_butterworth_window
+ make_2d_damping_window
+ apply_wavelet_decomposition
+ apply_wavelet_reconstruction
+ apply_filter_to_wavelet_component
+ interpolate_inside_stripe
+ transform_slice_forward
+ transform_slice_backward
- Customized smoothing filters:
+ apply_gaussian_filter (in the Fourier space)
+ apply_regularization_filter
- Methods for grid scans:
+ detect_sample
+ fix_non_sample_areas
+ locate_slice
+ locate_slice_chunk
- Methods for speckle-based tomography
+ generate_spiral_positions
- Method for finding the center of rotation by visual inspection.
+ find_center_visual_sinograms
"""
import sys
import multiprocessing as mp
import pywt
import numpy as np
import numpy.fft as fft
from numba import cuda
import scipy.ndimage as ndi
from scipy import interpolate
import scipy.signal.windows as win
from scipy.signal import savgol_filter
from joblib import Parallel, delayed
import algotom.io.loadersaver as losa
def parallel_process_slices(data, method, parameters, axis=1, ncore=None,
prefer="threads", **kwargs):
"""
Apply a processing method to slices of a 3D array in parallel.
Parameters
----------
data : array_like or hdf object
3D data array or HDF dataset.
method : callable
Function to apply to each slice.
parameters : list
List of positional parameters for the method.
axis : int
Axis along which the method is applied.
ncore : int, optional
Number of cpu-cores used for computing. Automatically selected if None.
prefer : {"threads", "processes"}
Preferred parallel backend ("threads" for I/O bound tasks or
"processes" for CPU-bound tasks).
**kwargs : dict
Additional keyword parameters to pass to the method.
Returns
-------
array_like
Same axis-definition as the input.
"""
(depth, height, width) = data.shape
if ncore is None:
ncore = np.clip(mp.cpu_count() - 1, 1, None)
else:
ncore = np.clip(ncore, 1, None)
if not isinstance(parameters, list):
parameters = list([parameters])
if axis == 2:
data_out = Parallel(n_jobs=ncore, prefer=prefer)(
delayed(method)(data[:, :, i], *parameters, **kwargs) for i in
range(width))
data_out = np.copy(np.moveaxis(np.float32(data_out), 0, 2))
elif axis == 1:
data_out = Parallel(n_jobs=ncore, prefer=prefer)(
delayed(method)(data[:, i, :], *parameters, **kwargs) for i in
range(height))
data_out = np.copy(np.moveaxis(np.float32(data_out), 0, 1))
else:
data_out = Parallel(n_jobs=ncore, prefer=prefer)(
delayed(method)(data[i, :, :], *parameters, **kwargs) for i in
range(depth))
data_out = np.float32(data_out)
return data_out
def apply_method_to_multiple_sinograms(*args, **kwargs):
msg = "!!! 'apply_method_to_multiple_sinograms' has been removed after " \
"version 1.5.0. Please use 'parallel_process_slices' instead. " \
"Refer to the documentation for details on parameters and usage " \
"adjustments needed!!!"
raise NotImplementedError(msg)
def mapping(mat, x_mat, y_mat, order=1, mode="reflect"):
"""
Apply a geometric transformation to a 2D array
Parameters
----------
mat : array_like
2D array.
x_mat : array_like
2D array of the x-coordinates.
y_mat : array_like
2D array of the y-coordinates.
order : int, optional
The order of the spline interpolation, default is 1.
The order has to be in the range 0-5.
mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
The mode parameter determines how the input array is extended beyond
its boundaries. Default is 'reflect'.
Returns
-------
array_like
2D array.
"""
coords = np.vstack((np.ndarray.flatten(y_mat), np.ndarray.flatten(x_mat)))
mat = ndi.map_coordinates(mat, coords, order=order, mode=mode)
return mat.reshape(x_mat.shape)
def make_circle_mask(width, ratio):
"""
Create a circle mask.
Parameters
-----------
width : int
Width of a square array.
ratio : float
Ratio between the diameter of the mask and the width of the array.
Returns
------
array_like
Square array.
"""
mask = np.zeros((width, width), dtype=np.float32)
center = width // 2
radius = ratio * center
y, x = np.ogrid[-center:width - center, -center:width - center]
mask_check = x * x + y * y <= radius * radius
mask[mask_check] = 1.0
return mask
def sort_forward(mat, axis=0):
"""
Sort gray-scales of an image along an axis.
e.g. axis=0 is to sort along each column.
Parameters
----------
mat : array_like
2D array.
axis : int
Axis along which to sort.
Returns
--------
mat_sort : array_like
2D array. Sorted image.
mat_index : array_like
2D array. Index array used for sorting backward.
"""
if axis == 0:
mat = np.transpose(mat)
(nrow, ncol) = mat.shape
list_index = np.arange(0.0, ncol, 1.0)
mat_index = np.tile(list_index, (nrow, 1))
mat_comb = np.asarray(np.dstack((mat_index, mat)))
mat_comb_sort = np.asarray(
[row[row[:, 1].argsort()] for row in mat_comb])
mat_sort = mat_comb_sort[:, :, 1]
mat_index = mat_comb_sort[:, :, 0]
if axis == 0:
mat_sort = np.transpose(mat_sort)
mat_index = np.transpose(mat_index)
return mat_sort, mat_index
def sort_backward(mat, mat_index, axis=0):
"""
Sort gray-scales of an image using an index array provided.
e.g. axis=0 is to sort each column.
Parameters
----------
mat : array_like
2D array.
mat_index : array_like
2D array. Index array used for sorting.
axis : int
Axis along which to sort.
Returns
--------
mat_sort : array_like
2D array. Sorted image.
"""
if axis == 0:
mat = np.transpose(mat)
mat_index = np.transpose(mat_index)
mat_comb = np.asarray(np.dstack((mat_index, mat)))
mat_comb_sort = np.asarray(
[row[row[:, 0].argsort()] for row in mat_comb])
mat_sort = mat_comb_sort[:, :, 1]
if axis == 0:
mat_sort = np.transpose(mat_sort)
return mat_sort
def separate_frequency_component(mat, axis=0, window=None):
"""
Separate low and high frequency components of an image along an axis.
e.g. axis=0 is to apply the separation to each column.
Parameters
----------
mat : array_like
2D array.
axis : int
Axis along which to apply the filter.
window : array_like or dict
1D array or a dictionary which given the name of a window in
the scipy_window list and its parameters (without window-length).
E.g window={"name": "gaussian", "sigma": 5}
Returns
-------
mat_low : array_like
2D array. Low-frequency image.
mat_high : array_like
2D array. High-frequency image.
"""
if axis == 0:
mat = np.transpose(mat)
(nrow, ncol) = mat.shape
pad = min(150, int(0.1 * ncol))
if window is None:
window = {"name": "gaussian", "sigma": 5}
if not isinstance(window, dict):
if len(window) != ncol:
raise ValueError("Window-length is not the same as the"
" axis-length!")
else:
window = np.pad(window, (pad, pad), mode='constant',
constant_values=1.0)
else:
win_name = tuple(window.values())[0]
para = tuple(window.values())[1:]
window = getattr(win, win_name)(ncol + 2 * pad, *para)
list_sign = np.power(-1.0, np.arange(ncol + 2 * pad))
mat_pad = np.pad(mat, ((0, 0), (pad, pad)), mode='reflect')
mat_smooth = np.copy(mat)
for i, line in enumerate(mat_pad):
mat_smooth[i] = np.real(
fft.ifft(fft.fft(line * list_sign) * window) *
list_sign)[pad:ncol + pad]
mat_sharp = mat - mat_smooth
if axis == 0:
mat_smooth = np.transpose(mat_smooth)
mat_sharp = np.transpose(mat_sharp)
return mat_smooth, mat_sharp
def generate_fitted_image(mat, order, axis=0, num_chunk=1):
"""
Apply a polynomial fitting along an axis of an image.
e.g. axis=0 is to apply the fitting to each column.
Parameters
----------
mat : array_like
2D array.
order : int
Order of the polynomial used to fit.
axis : int
Axis along which to apply the filter.
num_chunk : int
Number of chunks of rows or columns to apply the fitting.
Returns
-------
mat_fit : array_like
"""
(nrow, ncol) = mat.shape
if axis == 0:
size = nrow // num_chunk
length = size if (size % 2 == 1) else size - 1
mat_fit = savgol_filter(mat, length, order, axis=axis, mode='mirror')
else:
size = ncol // num_chunk
length = size if (size % 2 == 1) else size - 1
mat_fit = savgol_filter(mat, length, order, axis=axis, mode='mirror')
return mat_fit
def detect_stripe(list_data, snr):
"""
Locate stripe positions using Algorithm 4 in Ref. [1]
Parameters
----------
list_data : array_like
1D array. Normalized data.
snr : float
Ratio (>1.0) for stripe detection. Greater is less sensitive.
Returns
-------
array_like
1D binary mask.
References
----------
[1] : https://doi.org/10.1364/OE.26.028396
"""
npoint = len(list_data)
list_sort = np.sort(list_data)
xlist = np.arange(0, npoint, 1.0)
ndrop = np.int16(0.25 * npoint)
(slope, intercept) = np.polyfit(xlist[ndrop:-ndrop - 1],
list_sort[ndrop:-ndrop - 1], 1)[:2]
y_end = intercept + slope * xlist[-1]
noise_level = np.abs(y_end - intercept)
if noise_level < 1.0e-5:
raise ValueError("The method doesn't work on noise-free data. If you "
"apply the method on simulated data, please add"
" noise!")
val1 = np.abs(list_sort[-1] - y_end) / noise_level
val2 = np.abs(intercept - list_sort[0]) / noise_level
list_mask = np.zeros(npoint, dtype=np.float32)
if val1 >= snr:
upper_thresh = y_end + noise_level * snr * 0.5
list_mask[list_data > upper_thresh] = 1.0
if val2 >= snr:
lower_thresh = intercept - noise_level * snr * 0.5
list_mask[list_data <= lower_thresh] = 1.0
return list_mask
def calculate_regularization_coefficient(width, alpha):
"""
Calculate coefficients used for the regularization-based method.
Eq. (7) in Ref. [1].
Parameters
----------
width : int
Width of a square array.
alpha : float
Regularization parameter.
Returns
-------
float
Square array.
References
----------
[1] : https://doi.org/10.1016/j.aml.2010.08.022
"""
tau = 2.0 * np.arcsinh(np.sqrt(alpha) * 0.5)
ilist = np.arange(0, width)
jlist = np.arange(0, width)
matjj, matii = np.meshgrid(jlist, ilist)
mat1 = np.abs(matii - matjj)
mat2 = matii + matjj
mat1a = np.cosh((width - 1 - mat1) * tau)
mat2a = np.cosh((width - mat2) * tau)
matcoe = - (np.tanh(
0.5 * tau) / (alpha * np.sinh(width * tau))) * (mat1a + mat2a)
return matcoe
def make_2d_butterworth_window(width, height, u, v, n):
"""
Create a 2d window from the 1D Butterworth window.
Parameters
----------
height : int
Height of the window.
width : int
Width of the window.
u : int
Cutoff frequency.
n : int
Filter order.
v : int
Number of rows (= 2*v) around the height middle are the
1D Butterworth windows.
Returns
-------
array_like
2D array.
"""
xcenter = np.ceil(width / 2.0) - 1.0
ycenter = np.int16(np.ceil(height / 2.0) - 1)
xlist = np.arange(width) - xcenter
window = 1.0 / (1.0 + np.power(xlist / u, 2 * n))
row1 = ycenter - np.int16(v)
row2 = ycenter + np.int16(v) + 1
window_2d = np.ones((height, width), dtype=np.float32)
window_2d[row1:row2] = window
return window_2d
def make_2d_damping_window(width, height, size, window_name="gaussian"):
"""
Make 2D damping window from a list of 1D window for a Fourier-space filter,
i.e. a high-pass filter.
Parameters
----------
height : int
Height of the window.
width : int
Width of the window.
size : int
Sigma of a Gaussian window or cutoff frequency of a Butterworth window.
window_name : str, optional
Two options: "gaussian" or "butter".
Returns
-------
array_like
2D array of the window.
"""
xcenter = np.ceil(width / 2.0) - 1.0
xlist = np.arange(width) - xcenter
if window_name == "butter":
window = 1.0 - 1.0 / (1.0 + np.power(xlist / size, 2))
else:
window = 1.0 - np.exp(-xlist ** 2 / (2 * (size ** 2)))
return np.tile(window, (height, 1))
def apply_wavelet_decomposition(mat, wavelet_name, level=None):
"""
Apply 2D wavelet decomposition.
Parameters
----------
mat : array_like
2D array.
wavelet_name : str
Name of a wavelet. E.g. "db5"
level : int, optional
Decomposition level. It is constrained to return an array with
a minimum size of larger than 16 pixels.
Returns
-------
list
The first element is an 2D-array, next elements are tuples of three
2D-arrays. i.e [mat_n, (cH_level_n, cV_level_n, cD_level_n), ...,
(cH_level_1, cV_level_1, cD_level_1)]
"""
(nrow, ncol) = mat.shape
max_level = int(
min(np.floor(np.log2(nrow / 16.0)), np.floor(np.log2(ncol / 16.0))))
if (level is None) or (level > max_level) or (level < 1):
level = max_level
return pywt.wavedec2(mat, wavelet_name, level=level)
def apply_wavelet_reconstruction(data, wavelet_name, ignore_level=None):
"""
Apply 2D wavelet reconstruction.
Parameters
----------
data : list or tuple
The first element is an 2D-array, next elements are tuples of three
2D-arrays. i.e [mat_n, (cH_level_n, cV_level_n, cD_level_n), ...,
(cH_level_1, cV_level_1, cD_level_1)].
wavelet_name : str
Name of a wavelet. E.g. "db5"
ignore_level : int, optional
Decomposition level to be ignored for reconstruction.
Returns
-------
array_like
2D array. Note that the sizes of the array are always even numbers.
"""
if ignore_level is not None:
level = len(data[1:])
if level >= ignore_level > 0:
data[-ignore_level] = tuple(
[np.zeros_like(v) for v in data[-ignore_level]])
return pywt.waverec2(data, wavelet_name)
def check_level(level, n_level):
"""
Supplementary method for the method of "apply_filter_to_wavelet_component".
To check if the provided level is in the right format.
"""
if level is None:
level = list(range(1, n_level + 1))
else:
if isinstance(level, int):
if 0 < level <= n_level:
level = [level]
else:
raise ValueError(
"Level is out of range: [1:{}]!".format(n_level))
elif isinstance(level, list) or isinstance(level, tuple):
level = [(i if (0 < i <= n_level) else 0) for i in level]
if 0 in level:
raise ValueError(
"Level is out of range: [1:{}]!".format(n_level))
else:
raise ValueError("Level-input format is incorrect!")
return level
def apply_filter_to_wavelet_component(data, level=None, order=1, method=None,
para=None):
"""
Apply a filter to a component of the wavelet decomposition of an image.
Parameters
----------
data : list or tuple
The first element is an 2D-array, next elements are tuples of three
2D-arrays. i.e [mat_n, (cH_level_n, cV_level_n, cD_level_n), ...,
(cH_level_1, cV_level_1, cD_level_1)].
level : int, list of int, or None
Decomposition level to be applied the filter.
order : {0, 1, 2}
Specify which component in a tuple,
(cH_level_n, cV_level_n, cD_level_n), to be filtered.
method : str
Name of the filter in the namespace. E.g. method="gaussian_filter"
para : list or tuple
Parameters of the filter. E.g para=[(1,11)]
Returns
-------
list or tuple
The first element is an 2D-array, next elements are tuples of three
2D-arrays. i.e [mat_n, (cH_level_n, cV_level_n, cD_level_n), ...,
(cH_level_1, cV_level_1, cD_level_1)].
"""
n_level = len(data[1:])
level = check_level(level, n_level)
order = np.clip(order, 0, 2)
data = [list(i_data) for i_data in data]
if method is None:
method = "gaussian_filter"
if para is None:
para = [(1, 11)]
if not isinstance(para, list):
para = tuple(list([para]))
else:
para = tuple(para)
funcs = [f_name for (f_name, item) in globals().items() if callable(item)]
for i in level:
if method in dir(ndi):
data[i][order] = getattr(ndi, method)(data[i][order], *para)
else:
if method in funcs:
obj = sys.modules[__name__]
data[i][order] = getattr(obj, method)(data[i][order], *para)
else:
raise ValueError("Can't find the method: '{}' in the"
" namespace!".format(method))
data = [tuple(i_data) for i_data in data]
data[0] = np.asarray(data[0])
return data
def interpolate_inside_stripe(mat, list_mask, kind="linear"):
"""
Interpolate gray-scales inside vertical stripes of an image. Stripe
locations given by a binary 1D-mask.
Parameters
----------
mat : array_like
2D array.
list_mask : array_like
1D array. Must equal the width of an image.
kind : {'linear', 'cubic', 'quintic'}, optional
The kind of spline interpolation to use. Default is 'linear'.
Returns
-------
array_like
"""
(nrow, ncol) = mat.shape
if len(list_mask) != ncol:
raise ValueError("Length of a binary 1D-mask is not the same as the "
"width of an image!")
mat = np.copy(mat)
list_mask = np.copy(list_mask)
list_mask[0:2] = 0.0
list_mask[-2:] = 0.0
xlist = np.where(list_mask < 1.0)[0]
ylist = np.arange(nrow)
if kind == "cubic":
finter = interpolate.RectBivariateSpline(ylist, xlist, mat[:, xlist],
kx=2, ky=2)
elif kind == "quintic":
finter = interpolate.RectBivariateSpline(ylist, xlist, mat[:, xlist],
kx=3, ky=3)
else:
finter = interpolate.RectBivariateSpline(ylist, xlist, mat[:, xlist],
kx=1, ky=1)
xlist_miss = np.where(list_mask > 0.0)[0]
if len(xlist_miss) > 0:
x_mat_miss, y_mat = np.meshgrid(xlist_miss, ylist)
output = finter.ev(np.ndarray.flatten(y_mat),
np.ndarray.flatten(x_mat_miss))
mat[:, xlist_miss] = output.reshape(x_mat_miss.shape)
return mat
def rectangular_from_polar(width_reg, height_reg, width_pol, height_pol):
"""
Generate coordinates of a rectangular grid from polar coordinates.
Parameters
-----------
width_reg : int
Width of an image in the Cartesian coordinate system.
height_reg : int
Height of an image in the Cartesian coordinate system.
width_pol : int
Width of an image in the polar coordinate system.
height_pol : int
Height of an image in the polar coordinate system.
Returns
------
x_mat : array_like
2D array. Broadcast of the x-coordinates.
y_mat : array_like
2D array. Broadcast of the y-coordinates.
"""
xcenter = (width_reg - 1.0) * 0.5
ycenter = (height_reg - 1.0) * 0.5
r_max = np.floor(max(xcenter, ycenter))
r_list = np.linspace(0.0, r_max, width_pol)
theta_list = np.arange(0.0, height_pol, 1.0) * 2 * np.pi / (height_pol - 1)
r_mat, theta_mat = np.meshgrid(r_list, theta_list)
x_mat = np.float32(
np.clip(xcenter + r_mat * np.cos(theta_mat), 0, width_reg - 1))
y_mat = np.float32(
np.clip(ycenter + r_mat * np.sin(theta_mat), 0, height_reg - 1))
return x_mat, y_mat
def polar_from_rectangular(width_pol, height_pol, width_reg, height_reg):
"""
Generate polar coordinates from grid coordinates.
Parameters
-----------
width_pol : int
Width of an image in the polar coordinate system.
height_pol : int
Height of an image in the polar coordinate system.
width_reg : int
Width of an image in the Cartesian coordinate system.
height_reg : int
Height of an image in the Cartesian coordinate system.
Returns
------
r_mat : array_like
2D array. Broadcast of the r-coordinates.
theta_mat : array_like
2D array. Broadcast of the theta-coordinates.
"""
xcenter = (width_reg - 1.0) * 0.5
ycenter = (height_reg - 1.0) * 0.5
r_max = np.floor(max(xcenter, ycenter))
xlist = (np.flipud(np.arange(width_reg)) - xcenter) * width_pol / r_max
ylist = (np.flipud(np.arange(height_reg)) - ycenter) * width_pol / r_max
x_mat, y_mat = np.meshgrid(xlist, ylist)
r_mat = np.float32(
np.clip(np.sqrt(x_mat ** 2 + y_mat ** 2), 0, width_pol - 1))
theta_mat = np.float32(np.clip(
(np.pi + np.arctan2(y_mat, x_mat)) * (height_pol - 1) / (2 * np.pi), 0,
height_pol - 1))
return r_mat, theta_mat
def transform_slice_forward(mat, coord_mat=None):
"""
Transform a reconstructed image into polar coordinates.
Parameters
----------
mat : array_like
Square array. Reconstructed image.
coord_mat : tuple of array_like, optional
(Square array of x-coordinates , square array of y-coordinates) or
generated if None.
Returns
-------
array_like
Transformed image.
"""
(nrow, ncol) = mat.shape
if nrow != ncol:
raise ValueError("Height and width of the image is not the same!")
if coord_mat is None:
(x_mat, y_mat) = rectangular_from_polar(ncol, ncol, ncol, ncol)
else:
(x_mat, y_mat) = coord_mat
if (x_mat.shape != mat.shape) or (y_mat.shape != mat.shape):
raise ValueError("Shape of the coordinate array is not the same as"
" the shape of the image!")
return mapping(mat, x_mat, y_mat)
def transform_slice_backward(mat, coord_mat=None):
"""
Transform a reconstructed image in polar coordinates back to rectangular
coordinates.
Parameters
----------
mat : array_like
Square array. Reconstructed image in polar coordinates.
coord_mat : tuple of array_like, optional
(Square array of r-coordinates , square array of theta-coordinates) or
generated if None.
Returns
-------
array_like
Transformed image.
"""
(nrow, ncol) = mat.shape
if nrow != ncol:
raise ValueError("Height and width of the image is not the same!")
if coord_mat is None:
(r_mat, theta_mat) = polar_from_rectangular(ncol, ncol, ncol, ncol)
else:
(r_mat, theta_mat) = coord_mat
if (r_mat.shape != mat.shape) or (theta_mat.shape != mat.shape):
raise ValueError("Shape of the coordinate array is not the same as"
" the shape of the image!")
return mapping(mat, r_mat, theta_mat)
def make_2d_gaussian_window(height, width, sigma_x, sigma_y):
"""
Create a 2D Gaussian window.
Parameters
----------
height : int
Height of the image.
width : int
Width of the image.
sigma_x : int
Sigma in the x-direction.
sigma_y : int
Sigma in the y-direction.
Returns
-------
array_like
2D array.
"""
xcenter = (width - 1.0) / 2.0
ycenter = (height - 1.0) / 2.0
y, x = np.ogrid[-ycenter:height - ycenter, -xcenter:width - xcenter]
window = np.exp(
-(x ** 2 / (2 * sigma_x ** 2) + y ** 2 / (2 * sigma_y ** 2)))
return window
def apply_gaussian_filter(mat, sigma_x, sigma_y, pad=None, mode=None):
"""
Filtering an image in the Fourier domain using a 2D Gaussian window.
Smaller is stronger.
Parameters
----------
mat : array_like
2D array.
sigma_x : int
Sigma in the x-direction.
sigma_y : int
Sigma in the y-direction.
pad : int or None
Padding for the Fourier transform.
mode : str, list of str, or tuple of str
Padding method. One of options : 'reflect', 'edge', 'constant'. Full
list is at:
https://numpy.org/doc/stable/reference/generated/numpy.pad.html
Returns
-------
array_like
2D array. Filtered image.
"""
if mode is None:
# Default for a sinogram image.
mode1 = "edge"
mode2 = "mean"
else:
if isinstance(mode, list) or isinstance(mode, tuple):
mode1 = mode[0]
mode2 = mode[1]
else:
mode1 = mode2 = mode
if pad is None:
pad = min(150, int(0.1 * min(mat.shape)))
mat_pad = np.pad(mat, ((0, 0), (pad, pad)), mode=mode1)
mat_pad = np.pad(mat_pad, ((pad, pad), (0, 0)), mode=mode2)
(nrow, ncol) = mat_pad.shape
window = make_2d_gaussian_window(nrow, ncol, sigma_x, sigma_y)
xlist = np.arange(0, ncol)
ylist = np.arange(0, nrow)
x, y = np.meshgrid(xlist, ylist)
mat_sign = np.power(-1.0, x + y)
mat_filt = np.real(
fft.ifft2(fft.fft2(mat_pad * mat_sign) * window) * mat_sign)
return mat_filt[pad:nrow - pad, pad:ncol - pad]
def apply_1d_regularizer(list_data, sijmat):
"""
Supplementary method for the method of "apply_regularization_filter".
To apply a regularizer to an 1D-array.
"""
ncol = len(list_data)
list_grad = np.zeros(ncol, dtype=np.float32)
list_grad[1:-1] = (-1) * np.diff(list_data, 2)
list_grad[0] = list_data[0] - list_data[1]
list_grad[-1] = list_data[-1] - list_data[-2]
list_coe = np.sum(np.tile(list_grad, (ncol, 1)) * sijmat, axis=1)
return list_data + list_coe
def apply_regularization_filter(mat, alpha, axis=1, ncore=None):
"""
Apply a regularization filter using the method in Ref. [1].
Note that it's computationally costly.
Parameters
----------
mat : array_like
2D array
alpha : float
Regularization parameter, e.g. 0.001. Smaller is stronger.
axis : int
Axis along which to apply the filter.
ncore: int or None
Number of cpu-cores used for computing. Automatically selected if None.
Returns
-------
array_like
2D array. Smoothed image.
References
----------
[1] : https://doi.org/10.1016/j.aml.2010.08.022
"""
if ncore is None:
ncore = np.clip(mp.cpu_count() - 1, 1, None)
if axis == 0:
mat = np.transpose(mat)
(nrow, ncol) = mat.shape
sijmat = calculate_regularization_coefficient(ncol, alpha)
mat = np.asarray(Parallel(n_jobs=ncore, prefer="threads")(
delayed(apply_1d_regularizer)(mat[i], sijmat) for i in range(nrow)))
if axis == 0:
mat = np.transpose(mat)
return mat
def transform_1d_window_to_2d(win_1d, order=1, mode="reflect"):
"""
Transform a 1d-window to 2d-window.
Useful for designing a Fourier filter.
Parameters
----------
win_1d : array_like
1D array.
order : int, optional
The order of the spline interpolation, default is 1.
The order has to be in the range 0-5.
mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
The mode parameter determines how the input array is extended beyond
its boundaries. Default is 'reflect'.
Returns
--------
win_2d : array_like
Square array, a 2D version of the 1d-window.
"""
width0 = len(win_1d)
if width0 % 2 == 0:
width = width0 + 1
else:
width = width0
center = width // 2
xlist = (1.0 * np.flipud(np.arange(width)) - center)
ylist = (1.0 * np.arange(width) - center)
x_mat, y_mat = np.meshgrid(xlist, ylist)
r_mat = np.float32(np.clip(np.sqrt(x_mat ** 2 + y_mat ** 2), 0, center))
theta_mat = np.arctan2(y_mat, x_mat)
r_mat[theta_mat < 0] *= -1
r_mat = np.float32(np.clip(r_mat + center, 0, width - 1))
theta_mat = np.clip(np.float32(theta_mat * (width - 1.0) / np.pi), 0,
width - 1)
mat = np.tile(win_1d, (width, 1))
win_2d = mapping(mat, r_mat, theta_mat, order=order, mode=mode)
return win_2d[0:width0, 0:width0]
def detect_sample(sinogram, sino_type="180"):
"""
To check if there is a sample in a sinogram using the "double-wedge"
property of the Fourier transform of the sinogram (Ref. [1]).
Parameters
----------
sinogram : array_like
2D array. Sinogram image
sino_type : {"180", "360"}
Sinogram type : 180-degree or 360-degree.
Returns
-------
bool
True if there is a sample.
References
----------
[1] : https://doi.org/10.1364/OE.418448
"""
check = True
if not (sino_type == "180" or sino_type == "360"):
raise ValueError("!!! Use only one of two options: '180' or '360'!!!")
if sino_type == "180":
sinogram = 1.0 * np.vstack((sinogram, np.fliplr(sinogram)))
sino_fft = np.abs(fft.fftshift(fft.fft2(sinogram)))
(nrow, ncol) = sino_fft.shape
ycenter = nrow // 2
xcenter = ncol // 2
radi = min(20, int(np.ceil(0.05 * min(ycenter, xcenter))))
sino_fft = sino_fft[:ycenter - radi, :xcenter - radi]
size = min(30, int(np.ceil(0.02 * min(nrow, ncol))))
sino_smooth = ndi.gaussian_filter(sino_fft, size)
(nrow1, _) = sino_smooth.shape