/
reconstruction.py
1211 lines (1138 loc) · 47.1 KB
/
reconstruction.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: Python module of reconstruction methods
# Contributors:
# ============================================================================
"""
Module of FFT-based reconstruction methods in the reconstruction stage:
- Filtered back-projection (FBP) method for GPU (using numba and cuda)
and CPU.
- Direct Fourier inversion (DFI) method.
- Wrapper for Astra-Toolbox reconstruction methods (optional)
- Wrapper for Tomopy-gridrec reconstruction method (optional)
- Center-of-rotation determination using slice metrics.
"""
import math
import warnings
import multiprocessing as mp
import numpy as np
import numpy.fft as fft
import scipy
from scipy import signal
from numba import jit, cuda, prange
from joblib import Parallel, delayed
import algotom.util.utility as util
def make_smoothing_window(filter_name, width):
"""
Make a 1d smoothing window.
Parameters
----------
filter_name : {"hann", "bartlett", "blackman", "hamming", "nuttall",\
"parzen", "triang"}
Window function used for filtering.
width : int
Width of the window.
Returns
-------
array_like
1D array.
"""
if filter_name == 'hann':
window = signal.windows.hann(width)
elif filter_name == 'bartlett':
window = signal.windows.bartlett(width)
elif filter_name == 'blackman':
window = signal.windows.blackman(width)
elif filter_name == 'hamming':
window = signal.windows.hamming(width)
elif filter_name == 'nuttall':
window = signal.windows.nuttall(width)
elif filter_name == 'parzen':
window = signal.windows.parzen(width)
elif filter_name == 'triang':
window = signal.windows.triang(width)
else:
window = np.ones(width)
return window
def make_2d_ramp_window(height, width, filter_name=None):
"""
Make the 2d ramp window (in the Fourier space) by repeating the 1d ramp
window with the option of adding a smoothing window.
Parameters
----------
height : int
Height of the window.
width : int
Width of the window.
filter_name : {None, "hann", "bartlett", "blackman", "hamming",\
"nuttall", "parzen", "triang"}
Name of a smoothing window used.
Returns
-------
complex ndarray
2D array.
"""
ramp_win = np.arange(0.0, width) - np.ceil((width - 1.0) / 2)
ramp_win[ramp_win == 0.0] = 0.25
ramp_win[ramp_win % 2 == 0.0] = 0.0
for i in range(width):
if ramp_win[i] % 2 == 1.0:
ramp_win[i] = - 1.0 / (ramp_win[i] * np.pi) ** 2
window = make_smoothing_window(filter_name, width)
ramp_fourier = fft.fftshift(fft.fft(ramp_win)) * window
ramp_fourier_2d = np.tile(ramp_fourier, (height, 1))
return ramp_fourier_2d
def apply_ramp_filter(sinogram, ramp_win=None, filter_name=None, pad=None,
pad_mode="edge"):
"""
Apply the ramp filter to a sinogram with the option of adding a smoothing
filter.
Parameters
----------
sinogram : array_like
2D array. Sinogram image.
ramp_win : complex ndarray or None
Ramp window in the Fourier space.
filter_name : {None, "hann", "bartlett", "blackman", "hamming",\
"nuttall", "parzen", "triang"}
Name of a smoothing window used.
pad : int or None
To apply padding before the FFT. The value is set to 10% of the image
width if None is given.
pad_mode : str
Padding method. Full list can be found at numpy_pad documentation.
Returns
-------
array_like
Filtered sinogram.
"""
(nrow, ncol) = sinogram.shape
if pad is None:
pad = min(int(0.15 * ncol), 150)
sino_pad = np.pad(sinogram, ((0, 0), (pad, pad)), mode=pad_mode)
if (ramp_win is None) or (ramp_win.shape != sino_pad.shape):
ramp_win = make_2d_ramp_window(nrow, ncol + 2 * pad, filter_name)
sino_fft = fft.fftshift(fft.fft(sino_pad), axes=1) * ramp_win
sino_filtered = np.real(
fft.ifftshift(fft.ifft(fft.ifftshift(sino_fft, axes=1)), axes=1))
return np.ascontiguousarray(sino_filtered[:, pad:ncol + pad])
@cuda.jit
def back_projection_gpu(recon, sinogram, angles, xlist, center, sino_height,
sino_width): # pragma: no cover
"""
Implement the back-projection algorithm using GPU.
Parameters
----------
recon : array_like
Square array of zeros. Initialized reconstruction-image.
sinogram : array_like
2D array. (Filtered) sinogram image.
angles : array_like
1D array. Angles (radian) corresponding to the sinogram.
xlist : array_like
1D array. Distances of the integration lines to the image center.
center : float
Center of rotation.
sino_height : int
Height of the sinogram image.
sino_width : int
Width of the sinogram image.
Returns
-------
recon : array_like
Note that this is the GPU kernel function, i.e. no need of "return".
"""
(x_index, y_index) = cuda.grid(2)
icenter = math.ceil((sino_width - 1.0) / 2.0)
x_cor = (x_index - icenter)
y_cor = (y_index - icenter)
x_min = max(-icenter, -center)
x_max = min(sino_width - icenter - 1, sino_width - center - 1)
if (x_index < sino_width) and (y_index < sino_width):
num = 0.0
for i in range(sino_height):
theta = - angles[i]
x_pos = x_cor * math.cos(theta) + y_cor * math.sin(theta)
if (x_pos > x_min) and (x_pos < x_max):
fpos = x_pos + center
dpos = int(math.floor(fpos))
upos = int(math.ceil(fpos))
if upos != dpos:
xd = xlist[dpos]
xu = xlist[upos]
yd = sinogram[i, dpos]
yu = sinogram[i, upos]
val = yd + (yu - yd) * ((x_pos - xd) / (xu - xd))
else:
val = sinogram[i, dpos]
num += val
recon[y_index, x_index] = num
@cuda.jit
def back_projection_gpu_chunk(recons, sinograms, angles, xlist, center,
sino_height, sino_width,
num_sino): # pragma: no cover
"""
Implement the back-projection algorithm for a chunk of sinograms using GPU.
Axis of a sinogram/slice in the 3D array is 1.
Parameters
----------
recons : array_like
3D array of zeros. Initialized reconstruction-images.
sinograms : array_like
3D array. (Filtered) sinogram images.
angles : array_like
1D array. Angles (radian) corresponding to a sinogram.
xlist : array_like
1D array. Distances of the integration lines to the image center.
center : float
Center of rotation.
sino_height : int
Height of the sinogram image.
sino_width : int
Width of the sinogram image.
num_sino : int
Number of sinograms.
Returns
-------
recons : array_like
Reconstructed images.
"""
(x_index, y_index) = cuda.grid(2)
icenter = math.ceil((sino_width - 1.0) / 2.0)
x_cor = (x_index - icenter)
y_cor = (y_index - icenter)
x_min = max(-icenter, -center)
x_max = min(sino_width - icenter - 1, sino_width - center - 1)
if (x_index < sino_width) and (y_index < sino_width):
for i in range(sino_height):
theta = - angles[i]
x_pos = x_cor * math.cos(theta) + y_cor * math.sin(theta)
if (x_pos > x_min) and (x_pos < x_max):
fpos = x_pos + center
dpos = int(math.floor(fpos))
upos = int(math.ceil(fpos))
xd = xlist[dpos]
xu = xlist[upos]
for j in range(num_sino):
if upos != dpos:
yd = sinograms[i, j, dpos]
yu = sinograms[i, j, upos]
val = yd + (yu - yd) * ((x_pos - xd) / (xu - xd))
else:
val = sinograms[i, j, dpos]
recons[y_index, j, x_index] += val
@jit(nopython=True, parallel=True, cache=True)
def back_projection_cpu(sinogram, angles, xlist, center): # pragma: no cover
"""
Implement the back-projection algorithm using CPU.
Parameters
----------
sinogram : array_like
2D array. (Filtered) sinogram image.
angles : array_like
1D array. Angles (radian) corresponding to the sinogram.
xlist : array_like
1D array. Distances of the integration lines to the image center.
center : float
Center of rotation.
Returns
-------
recon : array_like
Square array. Reconstructed image.
"""
(sino_height, sino_width) = sinogram.shape
icenter = np.ceil((sino_width - 1.0) / 2.0)
x_min = max(-icenter, -center)
x_max = min(sino_width - icenter - 1, sino_width - center - 1)
recon = np.zeros((sino_width, sino_width), dtype=np.float32)
for i in prange(sino_height):
theta = - angles[i]
cos_theta = math.cos(theta)
sin_theta = math.sin(theta)
for y_index in range(sino_width):
y_cor = y_index - icenter
for x_index in range(sino_width):
x_pos = (x_index - icenter) * cos_theta + y_cor * sin_theta
if (x_pos > x_min) and (x_pos < x_max):
fpos = x_pos + center
dpos = np.int32(np.floor(fpos))
upos = np.int32(np.ceil(fpos))
if upos != dpos:
xd = xlist[dpos]
xu = xlist[upos]
yd = sinogram[i, dpos]
yu = sinogram[i, upos]
val = yd + (yu - yd) * ((x_pos - xd) / (xu - xd))
else:
val = sinogram[i, dpos]
recon[y_index, x_index] += val
return recon
def fbp_reconstruction(sinogram, center, angles=None, ratio=1.0, ramp_win=None,
filter_name="hann", pad=None, pad_mode="edge",
apply_log=True, gpu=True, block=(16, 16), ncore=None):
"""
Apply the FBP (filtered back-projection) reconstruction method to a
sinogram-image or a chunk of sinogram-images. Angular axis is 0.
If input is 3D array, the slicing axis of sinograms must be 1,
e.g. data[:, index, :].
Parameters
----------
sinogram : array_like
2D/3D array. Sinogram image.
center : float
Center of rotation.
angles : array_like, optional
1D array. List of angles (in radian) corresponding to the sinogram.
ratio : float, optional
To apply a circle mask to the reconstructed image.
ramp_win : complex ndarray, optional
Ramp window in the Fourier space. Generated if None.
filter_name : {None, "hann", "bartlett", "blackman", "hamming",\
"nuttall", "parzen", "triang"}
Apply a smoothing filter.
pad : int, optional
To apply padding before the FFT. The value is set to 10% of the image
width if None is given.
pad_mode : str, optional
Padding method. Full list can be found at numpy_pad documentation.
apply_log : bool, optional
Apply the logarithm function to the sinogram before reconstruction.
gpu : bool, optional
Use GPU for computing if True.
block : tuple of two integer-values, optional
Size of a GPU block. E.g. (8, 8), (16, 16), (32, 32), ...
ncore : int or None
Number of cpu-cores used for computing. Automatically selected if None.
Returns
-------
array_like
Square array. Reconstructed image.
"""
input_3d = False
if len(sinogram.shape) == 3:
(nrow, num_sino, ncol) = sinogram.shape
input_3d = True
else:
num_sino = 1
(nrow, ncol) = sinogram.shape
if center < 0 or center >= ncol:
raise ValueError("Center is out of the range [0, {}]".format(ncol - 1))
if angles is None:
angles = np.deg2rad(np.linspace(0.0, 180.0, nrow))
else:
if len(angles) != nrow:
raise ValueError("!!! Number of angles is not the same as the row "
"number of the sinogram !!!")
if gpu is True:
if cuda.is_available() is False:
warnings.warn("!!!No Nvidia GPU found!!!Run with CPU instead!!!")
gpu = False
if ncore is None:
ncore = np.clip(mp.cpu_count() - 1, 1, None)
else:
ncore = np.clip(ncore, 1, None)
if apply_log is True:
if np.any(sinogram <= 0.0):
warnings.warn("!!! Applying logarithm to sinogram is enabled but "
"there are values <= 0.0 in the sinogram !!!")
nmean = np.mean(sinogram)
sino_tmp = np.copy(sinogram)
if nmean != 0.0:
sino_tmp[sinogram <= 0.0] = nmean
else:
sino_tmp[sinogram <= 0.0] = 1
sinogram = sino_tmp
sinogram = -np.log(sinogram)
xlist = np.float32(np.arange(0.0, ncol) - center)
grid = (int(np.ceil(1.0 * ncol / block[0])),
int(np.ceil(1.0 * ncol / block[1])))
if ratio is None:
mask = np.ones((ncol, ncol), dtype=np.float32)
else:
if ratio == 0.0:
ratio = min(center, ncol - center) / (0.5 * ncol)
mask = util.make_circle_mask(ncol, ratio)
if pad is None:
pad = min(int(0.15 * ncol), 150)
if ramp_win is None:
ramp_win = make_2d_ramp_window(nrow, ncol + 2 * pad, filter_name)
if num_sino == 1:
sinogram = np.squeeze(sinogram)
sino_filtered = apply_ramp_filter(sinogram, ramp_win, filter_name, pad,
pad_mode)
if gpu is True:
sino_filtered = np.ascontiguousarray(sino_filtered)
recon = np.zeros((ncol, ncol), dtype=np.float32)
back_projection_gpu[grid, block](recon, np.float32(sino_filtered),
np.float32(angles), xlist,
np.float32(center),
np.int32(nrow), np.int32(ncol))
else:
recon = back_projection_cpu(np.float32(sino_filtered),
np.float32(angles), np.float32(xlist),
np.float32(center))
recon = recon * mask
else:
if ncore == 1:
sino_filtered = np.zeros_like(sinogram)
for i in range(num_sino):
sino_filtered[:, i, :] = apply_ramp_filter(sinogram[:, i, :],
ramp_win,
filter_name, pad,
pad_mode)
else:
ncore = np.clip(ncore, 1, num_sino)
sino_filtered = Parallel(n_jobs=ncore, prefer="threads")(
delayed(apply_ramp_filter)(
sinogram[:, i, :], ramp_win, filter_name, pad,
pad_mode) for i in range(num_sino))
sino_filtered = np.moveaxis(np.asarray(sino_filtered), 0, 1)
if gpu is True:
sino_filtered = np.ascontiguousarray(sino_filtered)
recon = np.zeros((ncol, num_sino, ncol), dtype=np.float32)
back_projection_gpu_chunk[grid, block](recon,
np.float32(sino_filtered),
np.float32(angles), xlist,
np.float32(center),
np.int32(nrow),
np.int32(ncol),
np.int32(num_sino))
else:
recon = np.zeros((ncol, num_sino, ncol), dtype=np.float32)
for i in range(num_sino):
recon[:, i, :] = back_projection_cpu(
np.float32(sino_filtered[:, i, :]), np.float32(angles),
np.float32(xlist), np.float32(center))
if ratio is not None:
for i in range(num_sino):
recon[:, i, :] = recon[:, i, :] * mask
if input_3d is True and num_sino == 1:
recon = np.expand_dims(recon, 1)
return recon * np.pi / (nrow - 1)
def generate_mapping_coordinate(width_sino, height_sino, width_rec,
height_rec):
"""
Calculate coordinates in the sinogram space from coordinates in the
reconstruction space (in the Fourier domain). They are used for the
DFI (direct Fourier inversion) reconstruction method.
Parameters
-----------
width_sino : int
Width of a sinogram image.
height_sino : int
Height of a sinogram image.
width_rec : int
Width of a reconstruction image.
height_rec : int
Height of a reconstruction image.
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_rec - 1.0) * 0.5
ycenter = (height_rec - 1.0) * 0.5
r_max = np.floor(min(xcenter, ycenter))
xlist = (np.flipud(np.arange(width_rec)) - xcenter)
ylist = (np.arange(height_rec) - ycenter)
x_mat, y_mat = np.meshgrid(xlist, ylist)
r_mat = np.float32(np.clip(np.sqrt(x_mat ** 2 + y_mat ** 2), 0, r_max))
theta_mat = np.pi + np.arctan2(y_mat, x_mat)
r_mat[theta_mat > np.pi] *= -1
r_mat = np.float32(np.clip(r_mat + r_max, 0, width_sino - 1))
theta_mat[theta_mat > np.pi] -= np.pi
theta_mat = np.float32(theta_mat * (height_sino - 1.0) / np.pi)
return r_mat, theta_mat
def __dfi_handle_angles(sinogram, angles):
"""
Supplementary method for the DFI reconstruction method.
Allow to use real angles for reconstruction.
"""
nrow = sinogram.shape[0]
if len(angles) != nrow:
raise ValueError("!!! Number of angles is not the same as the row "
"number of the sinogram !!!")
t_ang = np.sum(np.abs(np.diff(angles * 180.0 / np.pi)))
if abs(t_ang - 360) < 10:
nrow = nrow // 2 + 1
sinogram = (sinogram[:nrow] + np.fliplr(sinogram[-nrow:])) / 2
step = np.mean(np.abs(np.diff(angles)))
b_ang = angles[0] - (angles[0] // (2 * np.pi)) * (2 * np.pi)
sino_360 = np.vstack((sinogram[: nrow - 1], np.fliplr(sinogram)))
sinogram = scipy.ndimage.shift(sino_360, (b_ang / step, 0), mode='wrap')[
:nrow]
if angles[-1] < angles[0]:
sinogram = np.flipud(np.fliplr(sinogram))
return sinogram
def __dfi_handle_sinogram(sinogram0, angles, center, pad_rate, pad_mode):
"""
Supplementary method for the DFI reconstruction method.
Shift and pad sinogram.
"""
sinogram = np.squeeze(sinogram0)
if len(sinogram.shape) == 3:
(nrow, num_sino, ncol) = sinogram.shape
if ncol % 2 == 0:
sinogram = np.pad(sinogram, ((0, 0), (0, 0), (0, 1)), mode="edge")
else:
num_sino = 1
(nrow, ncol) = sinogram.shape
if ncol % 2 == 0:
sinogram = np.pad(sinogram, ((0, 0), (0, 1)), mode="edge")
ncol1 = sinogram.shape[-1]
xshift = (ncol1 - 1) / 2.0 - center
pad = int(pad_rate * ncol1)
if num_sino > 1:
sinogram = scipy.ndimage.shift(sinogram, (0, 0, xshift),
mode='nearest')
if angles is not None:
sino_tmp = []
for i in range(num_sino):
sino_tmp.append(__dfi_handle_angles(sinogram[:, i, :], angles))
sinogram = np.moveaxis(np.asarray(sino_tmp), 0, 1)
sinogram = np.pad(sinogram, ((0, 0), (0, 0), (pad, pad)),
mode=pad_mode)
else:
sinogram = scipy.ndimage.shift(sinogram, (0, xshift), mode='nearest')
if angles is not None:
sinogram = __dfi_handle_angles(sinogram, angles)
sinogram = np.pad(sinogram, ((0, 0), (pad, pad)), mode=pad_mode)
return sinogram, num_sino, pad
def __dfi_single_slice(sinogram, window, mask, r_mat, theta_mat):
"""
Supplementary method for the DFI reconstruction method.
Reconstruct a single slice.
"""
sino_fft = fft.fftshift(fft.fft(fft.ifftshift(sinogram, axes=1)), axes=1)
if window is not None:
sino_fft = sino_fft * window
scipy_ver = scipy.__version__
scipy_ver = tuple(map(int, scipy_ver.split(".")[:2]))
if scipy_ver < (1, 6):
mat_real = np.real(sino_fft)
mat_imag = np.imag(sino_fft)
reg_real = util.mapping(mat_real, r_mat, theta_mat, order=5,
mode="reflect") * mask
reg_imag = util.mapping(mat_imag, r_mat, theta_mat, order=5,
mode="reflect") * mask
reg_comp = reg_real + 1j * reg_imag
else:
reg_comp = util.mapping(sino_fft, r_mat, theta_mat, order=5,
mode="reflect") * mask
recon = np.real(fft.fftshift(fft.ifft2(fft.ifftshift(reg_comp))))
return recon
def dfi_reconstruction(sinogram, center, angles=None, ratio=1.0,
filter_name="hann", pad_rate=0.25, pad_mode="edge",
apply_log=True, ncore=None):
"""
Apply the DFI (direct Fourier inversion) reconstruction method (Ref. [1])
to a sinogram-image or a chunk of sinogram-images. Angular axis is 0.
If input is 3D array, the slicing axis of sinograms must be 1,
e.g. data[:, index, :].
Parameters
----------
sinogram : array_like
2D/3D array. Sinogram image.
center : float
Center of rotation.
angles : array_like
1D array. List of angles (in radian) corresponding to the sinogram.
ratio : float
To apply a circle mask to the reconstructed image.
filter_name : {None, "hann", "bartlett", "blackman", "hamming",\
"nuttall", "parzen", "triang"}
Apply a smoothing filter.
pad_rate : float
To apply padding before the FFT. The padding width equals to
(pad_rate * image_width).
pad_mode : str
Padding method. Full list can be found at numpy_pad documentation.
apply_log : bool
Apply the logarithm function to the sinogram before reconstruction.
ncore : int or None
Number of cpu-cores used for computing. Automatically selected if None.
Returns
-------
array_like
Square array. Reconstructed image.
References
----------
[1] : https://doi.org/10.1071/PH560198
"""
input_3d = False
if len(sinogram.shape) == 3:
input_3d = True
nrow, ncol = sinogram.shape[0], sinogram.shape[-1]
if center < 0 or center >= ncol:
raise ValueError("Center is out of the range [0, {}]".format(ncol - 1))
if ncol / nrow > 5.0:
warnings.warn("!!!Sinogram is significantly undersampled!!! "
"Considering to use the 'upsample_sinogram' method "
"before reconstruction!")
sinogram, num_sino, pad = __dfi_handle_sinogram(sinogram, angles, center,
pad_rate, pad_mode)
if apply_log is True:
if np.any(sinogram <= 0.0):
warnings.warn("!!! Applying logarithm to sinogram is enabled but "
"there are values <= 0.0 in the sinogram !!!")
nmean = np.mean(sinogram)
sino_tmp = np.copy(sinogram)
if nmean != 0.0:
sino_tmp[sinogram <= 0.0] = nmean
else:
sino_tmp[sinogram <= 0.0] = 1
sinogram = sino_tmp
sinogram = -np.log(sinogram)
if ncore is None:
ncore = np.clip(mp.cpu_count() - 1, 1, None)
else:
ncore = np.clip(ncore, 1, None)
nrow, ncol2 = sinogram.shape[0], sinogram.shape[-1]
mask = util.make_circle_mask(ncol2, 1.0)
(r_mat, theta_mat) = generate_mapping_coordinate(ncol2, nrow, ncol2, ncol2)
window = None
if filter_name is not None:
win1d = make_smoothing_window(filter_name, ncol2)
window = np.tile(win1d, (nrow, 1))
if num_sino > 1:
if ncore > 1:
ncore = np.clip(ncore, 1, num_sino)
recon = Parallel(n_jobs=ncore, prefer="threads")(
delayed(__dfi_single_slice)(
sinogram[:, i, :], window, mask, r_mat,
theta_mat) for i in range(num_sino))
else:
recon = []
for i in range(num_sino):
recon.append(__dfi_single_slice(sinogram[:, i, :], window,
mask, r_mat, theta_mat))
recon = np.moveaxis(np.asarray(recon), 0, 1)
recon = recon[pad:ncol + pad, :, pad:ncol + pad]
else:
recon = __dfi_single_slice(sinogram, window, mask, r_mat, theta_mat)
recon = recon[pad:ncol + pad, pad:ncol + pad]
if ratio is not None:
if ratio == 0.0:
ratio = min(center, ncol - center) / (0.5 * ncol)
mask = util.make_circle_mask(ncol, ratio)
if num_sino > 1:
for i in range(num_sino):
recon[:, i, :] = recon[:, i, :] * mask
else:
recon = recon * mask
if input_3d is True and num_sino == 1:
recon = np.expand_dims(recon, 1)
return recon
def gridrec_reconstruction(sinogram, center, angles=None, ratio=1.0,
filter_name="shepp", apply_log=True, pad=100,
ncore=1): # pragma: no cover
"""
Apply the gridrec method to a sinogram-image or a chunk of sinogram-images.
Angular axis is 0. If input is 3D array, the slicing axis of sinograms
must be 1, e.g. data[:, index, :]. This is the wrapper of the gridrec
method implemented in the Tomopy package:
https://tomopy.readthedocs.io/en/latest/api/tomopy.recon.algorithm.html.
Users must install Tomopy before using this function.
Parameters
----------
sinogram : array_like
2D/3D array. Sinogram image.
center : float
Center of rotation.
angles : array_like
1D array. List of angles (radian) corresponding to the sinogram.
ratio : float
To apply a circle mask to the reconstructed image.
filter_name : str or None
Apply a smoothing filter. Full list is at:
https://github.com/tomopy/tomopy/blob/master/source/tomopy/recon/algorithm.py
apply_log : bool
Apply the logarithm function to the sinogram before reconstruction.
pad : bool or int
Apply edge padding to the nearest power of 2.
ncore : int or None
Number of cpu-cores used for computing. Automatically selected if None.
Returns
-------
array_like
Square array.
"""
try:
import tomopy
except ImportError:
raise ValueError("You must install Tomopy before using this function!")
input_3d = False
if len(sinogram.shape) == 3:
input_3d = True
if angles is None:
angles = np.deg2rad(np.linspace(0.0, 180.0, sinogram.shape[0]))
else:
if len(angles) != sinogram.shape[0]:
raise ValueError("!!! Number of angles is not the same as the row "
"number of the sinogram !!!")
if apply_log is True:
if np.any(sinogram <= 0.0):
warnings.warn("!!! Applying logarithm to sinogram is enabled but "
"there are values <= 0.0 in the sinogram !!!")
nmean = np.mean(sinogram)
sino_tmp = np.copy(sinogram)
if nmean != 0.0:
sino_tmp[sinogram <= 0.0] = nmean
else:
sino_tmp[sinogram <= 0.0] = 1
sinogram = sino_tmp
sinogram = -np.log(sinogram)
if ncore is None:
ncore = np.clip(mp.cpu_count() - 1, 1, None)
else:
ncore = np.clip(ncore, 1, None)
if filter_name is None:
filter_name = "shepp"
pad_left = 0
ncol = sinogram.shape[-1]
if center < 0 or center >= ncol:
raise ValueError("Center is out of the range [0, {}]".format(ncol - 1))
if isinstance(pad, bool):
if pad is True:
ncol_pad = int(2 ** np.ceil(np.log2(1.0 * ncol)))
pad_left = (ncol_pad - ncol) // 2
pad_right = ncol_pad - ncol - pad_left
else:
pad_right = 0
else:
ncol_pad = int(2 ** np.ceil(np.log2(1.0 * ncol + 2 * pad)))
pad_left = (ncol_pad - ncol) // 2
pad_right = ncol_pad - ncol - pad_left
if len(sinogram.shape) == 2:
sinogram = np.expand_dims(sinogram, 1)
sinogram = np.pad(sinogram, ((0, 0), (0, 0), (pad_left, pad_right)),
mode='edge')
recon = tomopy.recon(sinogram, angles, center=center + pad_left,
algorithm='gridrec', filter_name=filter_name,
ncore=ncore)
num_slice = len(recon)
recon = recon[:, pad_left: pad_left + ncol, pad_left: pad_left + ncol]
if ratio is not None:
if ratio == 0.0:
ratio = min(center, ncol - center) / (0.5 * ncol)
mask = util.make_circle_mask(ncol, ratio)
for i in range(num_slice):
recon[i] = recon[i] * mask
recon = np.moveaxis(np.asarray(recon), 0, 1)
if input_3d is False:
recon = np.squeeze(recon)
return recon
def __astra_recon_single(sinogram, center, angles, pad, method, filter_name,
num_iter): # pragma: no cover
try:
import astra
except ImportError:
raise ValueError("You must install Astra-Toolbox before using this "
"function!")
sinogram = np.pad(sinogram, ((0, 0), (pad, pad)), mode='edge')
ncol = sinogram.shape[-1]
proj_geom = astra.create_proj_geom('parallel', 1, ncol, angles)
vol_geom = astra.create_vol_geom(ncol, ncol)
cen_col = (ncol - 1.0) / 2.0
sinogram = scipy.ndimage.shift(sinogram, (0, cen_col - (center + pad)),
mode='nearest')
sino_id = astra.data2d.create('-sino', proj_geom, sinogram)
rec_id = astra.data2d.create('-vol', vol_geom)
proj_id = None
if "CUDA" not in method:
proj_id = astra.create_projector('line', proj_geom, vol_geom)
cfg = astra.astra_dict(method)
cfg['ProjectionDataId'] = sino_id
cfg['ReconstructionDataId'] = rec_id
if "CUDA" not in method:
cfg['ProjectorId'] = proj_id
if (method == "FBP_CUDA") or (method == "FBP"):
cfg["FilterType"] = filter_name
try:
alg_id = astra.algorithm.create(cfg)
except Exception:
raise ValueError("Invalid selection of method!!!")
astra.algorithm.run(alg_id, num_iter)
recon = astra.data2d.get(rec_id)
astra.algorithm.delete(alg_id)
astra.data2d.delete(sino_id)
astra.data2d.delete(rec_id)
return recon[pad:ncol - pad, pad:ncol - pad]
def astra_reconstruction(sinogram, center, angles=None, ratio=1.0,
method="FBP_CUDA", num_iter=1, filter_name="hann",
pad=None, apply_log=True,
ncore=1): # pragma: no cover
"""
Wrapper of reconstruction methods implemented in the astra toolbox package.
https://www.astra-toolbox.com/docs/algs/index.html
Users must install Astra Toolbox before using this function.
Apply the method to a sinogram-image or a chunk of sinogram-images.
Angular axis is 0. If input is 3D array, the slicing axis of sinograms
must be 1, e.g. data[:, index, :]
Parameters
----------
sinogram : array_like
2D/3D array. Sinogram image.
center : float
Center of rotation.
angles : array_like
1D array. List of angles (radian) corresponding to the sinogram.
ratio : float
To apply a circle mask to the reconstructed image.
method : str
Reconstruction algorithms. For CPU: 'FBP', 'SIRT', 'SART', 'ART', and
'CGLS'. For GPU: 'FBP_CUDA', 'SIRT_CUDA', 'SART_CUDA', and 'CGLS_CUDA'.
num_iter : int
Number of iterations if using iteration methods.
filter_name : str or None
Apply filter if using FBP method. Options: 'ram-lak', 'hamming',
'hann', 'lanczos', 'kaiser', 'parzen',...
pad : int
Padding to reduce the side effect of FFT.
apply_log : bool
Apply the logarithm function to the sinogram before reconstruction.
Returns
-------
array_like
Square array.
"""
try:
import astra
except ImportError:
raise ValueError("You must install Astra-Toolbox before using this "
"function!")
input_3d = False
if len(sinogram.shape) == 3:
(nrow, num_sino, ncol) = sinogram.shape
input_3d = True
else:
num_sino = 1
(nrow, ncol) = sinogram.shape
if angles is None:
angles = np.deg2rad(np.linspace(0.0, 180.0, nrow))
else:
if len(angles) != nrow:
raise ValueError("!!! Number of angles is not the same as the row "
"number of the sinogram !!!")
cpu_method = ["FBP", "SIRT", "SART", "ART", "CGLS"]
gpu_method = ["FBP_CUDA", "SIRT_CUDA", "SART_CUDA", "CGLS_CUDA", "EM_CUDA"]
gpu = True
if "CUDA" in method:
if cuda.is_available() is False:
warnings.warn("!!!No Nvidia GPU found!!!Run with CPU instead!!!")
method = method.replace("_CUDA", "")
if "EM" in method:
raise ValueError("No EM method for CPU-based algorithm!!!")
gpu = False
else:
gpu = False
if gpu is True:
if method not in gpu_method:
raise ValueError("No such option, {0}, in the available list "
"{1}".format(method, gpu_method))
else:
if method not in cpu_method:
raise ValueError("No such option, {0}, in the available list "
"{1}".format(method, cpu_method))
if ncore is None:
ncore = np.clip(mp.cpu_count() - 1, 1, None)
else:
ncore = np.clip(ncore, 1, None)
if center < 0 or center >= ncol:
raise ValueError("Center is out of the range [0, {}]".format(ncol - 1))
if apply_log is True:
if np.any(sinogram <= 0.0):
warnings.warn("!!! Applying logarithm to sinogram is enabled but "
"there are values <= 0.0 in the sinogram !!!")
nmean = np.mean(sinogram)
sino_tmp = np.copy(sinogram)
if nmean != 0.0:
sino_tmp[sinogram <= 0.0] = nmean
else:
sino_tmp[sinogram <= 0.0] = 1
sinogram = sino_tmp
sinogram = -np.log(sinogram)
if filter_name is None:
filter_name = "ram-lak"
if pad is None:
pad = min(int(0.15 * sinogram.shape[-1]), 150)
else:
pad = np.clip(int(pad), 0, None)
if input_3d is False:
recon = __astra_recon_single(sinogram, center, angles, pad, method,
filter_name, num_iter)
else:
if gpu is True:
recon = []
for i in range(num_sino):
recon.append(__astra_recon_single(sinogram[:, i, :], center,
angles, pad, method,
filter_name, num_iter))
else:
ncore = np.clip(ncore, 1, num_sino)
recon = Parallel(n_jobs=ncore, prefer="threads")(delayed(
__astra_recon_single)(sinogram[:, i, :], center, angles, pad,
method, filter_name,
num_iter) for i in range(num_sino))
recon = np.moveaxis(np.asarray(recon), 0, 1)
if ratio is not None:
if ratio == 0.0:
ratio = min(center, ncol - center) / (0.5 * ncol)
mask = util.make_circle_mask(ncol, ratio)
if input_3d is False:
recon = recon * mask
else:
for i in range(num_sino):
recon[:, i, :] = recon[:, i, :] * mask
return recon
def _reconstruct_slice(sinogram, center, method, angles, ratio, filter_name,
apply_log, gpu, ncore):
"""
Supplementary method for '_find_center_based_slice_metric'. Used to
reconstruct a slice.
"""
if method == "fbp":
recon = fbp_reconstruction(sinogram, center, angles=angles,
ratio=ratio, filter_name=filter_name,
apply_log=apply_log, gpu=gpu, ncore=ncore)
elif method == "astra": # pragma: no cover
if gpu is True:
rec_method = "FBP_CUDA"
else:
rec_method = "FBP"
recon = astra_reconstruction(sinogram, center, angles=angles,
method=rec_method, ratio=ratio,
filter_name=filter_name,
apply_log=apply_log, ncore=ncore)
elif method == "gridrec": # pragma: no cover
recon = gridrec_reconstruction(sinogram, center, angles=angles,
ratio=ratio, filter_name=filter_name,
apply_log=apply_log, ncore=ncore)
else:
recon = dfi_reconstruction(sinogram, center, angles=angles,
ratio=ratio, filter_name=filter_name,
apply_log=apply_log, ncore=ncore)
return recon
def __calculate_histogram_entropy(recon_img, window):
"""
Supplementary method for '_find_center_based_slice_metric'. Used to
calculate a metric based on the entropy of histogram.
"""
recon = np.uint8(recon_img * 255)