-
Notifications
You must be signed in to change notification settings - Fork 12
/
leapctype.py
7545 lines (6319 loc) · 375 KB
/
leapctype.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 2022-2023 Lawrence Livermore National Security, LLC and other
# LEAP project developers. See the LICENSE file for details.
# SPDX-License-Identifier: MIT
#
# LivermorE AI Projector for Computed Tomography (LEAP)
# ctype tomographicModels class
################################################################################
import ctypes
import os
import sys
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
import site
import glob
import imageio
from sys import platform as _platform
from numpy.ctypeslib import ndpointer
import numpy as np
try:
import torch
has_torch = True
except:
has_torch = False
from leap_filter_sequence import *
#testFS = filterSequence()
class tomographicModels:
""" Python class for tomographicModels bindings
Usage Example:
from leapctype import *
leapct = tomographicModels()
leapct.set_conebeam(...)
leapct.set_default_volume(...)
...
leapct.project(g,f)
"""
def __init__(self, param_id=None, lib_dir=""):
"""Constructor
The functions in this class can take as input and output data that is either on the CPU or the GPU.
Note that all input and ouput data for all functions must lie either on a specific GPU or on the CPU.
You cannot have some data on the CPU and some on a GPU.
If the data is on the CPU (works for both numpy arrays or pytorch tensors):
1) and one wishes the computations to take place on the CPU, then run the following
command: set_gpu(-1).
2) and one wishes the computations to take place on one of more GPUs, then run
the following command: set_gpus(list_of_gpu_indices), e.g., set_gpus([0,1])
The default setting is for LEAP to use all GPUs, so if this is what you want
there is no need to run the set_gpus function
If the data is on the GPU (only possible with torch tensors):
then the computations must also take place on this particular GPU and
you must run the following command: set_gpu(index), where index is GPU index
of where the data resides.
Providing data that is already on a GPU is best for small data sets, where data
transfers to and from the GPU are more time consuming than the computations
for the actual data processing.
Providing data that is on the CPU is best for medium to large data sets because this
allows for multi-GPU processing and LEAP will automatically divide up the data
into small enough chunks so that is does not exceed the GPU memory.
The LEAP library has the ability to generate and track several parameter sets.
By default every new object instance will create a new parameter set.
Otherwise one can use the param_id parameter so that the object will utilize a parameter set
that is also shared by another object of this class. But this parameter index must already be in use.
Do not use this argument if you want to create a NEW parameter set. See the param_id argument description below.
Args:
param_id (int): If no value is given, then a new parameter set is generated, otherwise one can specify a parameter set index to use, but this parameter index must already be in use
lib_dir (string): Path to the LEAP dynamic library, default value is the same path as this file
"""
if len(lib_dir) > 0:
current_dir = lib_dir
else:
current_dir = os.path.abspath(os.path.dirname(__file__))
if _platform == "linux" or _platform == "linux2":
import readline
from ctypes import cdll
#libdir = site.getsitepackages()[0]
#libname = glob.glob(os.path.join(libdir, "leapct*.so"))
libname = glob.glob(os.path.join(current_dir, "*leapct*.so"))
if len(libname) == 0:
fullPath = os.path.join(current_dir, 'libleapct.so')
fullPath_backup = os.path.join(current_dir, '../build/lib/libleapct.so')
elif len(libname) == 1:
fullPath = libname[0]
fullPath_backup = ""
elif len(libname) >= 2:
fullPath = libname[0]
fullPath_backup = libname[1]
if os.path.isfile(fullPath):
self.libprojectors = cdll.LoadLibrary(fullPath)
elif os.path.isfile(fullPath_backup):
self.libprojectors = cdll.LoadLibrary(fullPath_backup)
else:
print('Error: could not find LEAP dynamic library at')
print(fullPath)
print('or')
print(fullPath_backup)
self.libprojectors = None
elif _platform == "win32":
from ctypes import windll
libname = glob.glob(os.path.join(current_dir, "*leapct*.dll"))
if len(libname) == 0:
fullPath = os.path.join(current_dir, 'libleapct.dll')
fullPath_backup = os.path.join(current_dir, r'..\win_build\bin\Release\libleapct.dll')
elif len(libname) == 1:
fullPath = libname[0]
fullPath_backup = ""
elif len(libname) >= 2:
fullPath = libname[0]
fullPath_backup = libname[1]
if os.path.isfile(fullPath):
try:
self.libprojectors = windll.LoadLibrary(fullPath)
except:
self.libprojectors = ctypes.CDLL(fullPath, winmode=0)
elif os.path.isfile(fullPath_backup):
try:
self.libprojectors = windll.LoadLibrary(fullPath_backup)
except:
self.libprojectors = ctypes.CDLL(fullPath_backup, winmode=0)
else:
print('Error: could not find LEAP dynamic library at')
print(fullPath)
print('or')
print(fullPath_backup)
self.libprojectors = None
elif _platform == "darwin": # Darwin is the name for MacOS in Python's platform module
from ctypes import cdll
libname = glob.glob(os.path.join(current_dir, "*leapct*.dylib"))
if len(libname) == 0:
fullPath = os.path.join(current_dir, 'libleapct.dylib')
fullPath_backup = os.path.join(current_dir, '../build/lib/libleapct.dylib')
elif len(libname) == 1:
fullPath = libname[0]
fullPath_backup = ""
elif len(libname) >= 2:
fullPath = libname[0]
fullPath_backup = libname[1]
if os.path.isfile(fullPath):
self.libprojectors = cdll.LoadLibrary(fullPath)
elif os.path.isfile(fullPath_backup):
self.libprojectors = cdll.LoadLibrary(fullPath_backup)
else:
print('Error: could not find LEAP dynamic library at')
print(fullPath)
print('or')
print(fullPath_backup)
self.libprojectors = None
if self.libprojectors is None:
self.param_id = -1
else:
if param_id is not None:
self.param_id = param_id
else:
self.param_id = self.create_new_model()
self.set_model()
self.print_cost = False
self.print_warnings = True
self.volume_mask = None
self.file_dtype = np.float32
self.wmin = 0.0
self.wmax = None
def test_script(self):
self.libprojectors.test_script()
def set_model(self, i=None):
""" This should be considered a private class function """
self.libprojectors.set_model.restype = ctypes.c_bool
self.libprojectors.set_model.argtypes = [ctypes.c_int]
if i is None:
return self.libprojectors.set_model(self.param_id)
else:
return self.libprojectors.set_model(i)
def set_log_error(self):
"""Sets logging level to logERROR
This logging level prints out the fewest statements (only error statements)
"""
self.libprojectors.set_log_error()
self.print_cost = False
self.print_warnings = False
def set_log_warning(self):
"""Sets logging level to logWARNING
This logging level prints out the second fewest statements (only error and warning statements)
and is the default setting. It includes iterative reconstruction warnings and iteration number.
"""
self.libprojectors.set_log_warning()
self.print_cost = False
self.print_warnings = True
def set_log_status(self):
"""Sets logging level to logSTATUS
This logging level prints out the second most statements, including iterative reconstruction
cost at every iteration (these extra computations will slow down processing)
"""
self.libprojectors.set_log_status()
self.print_cost = True
self.print_warnings = True
def set_log_debug(self):
"""Sets logging level to logDEBUG
This logging level prints out the most statements
"""
self.libprojectors.set_log_debug()
self.print_cost = True
self.print_warnings = True
def set_fileIO_parameters(self, dtype=np.float32, wmin=0.0, wmax=None):
r""" This function sets parameters dealing with how tiff stacks are saved
If dtype is np.float32, the data is not clipped
Args:
dtype: the data type to use, can be: np.float32, np.uint8, or np.uint16
wmin (float): the low value for clipping the data (default is 0.0)
wmax (float): the high value for clipping the data (default is the max of the 3D data)
Returns:
True if the dtype is valid, False otherwise
"""
if dtype == np.float32 or dtype == np.uint8 or dtype == np.uint16:
self.file_dtype = dtype
self.wmin = wmin
self.wmax = wmax
else:
print('Error: invalid dtype; must be np.float32, np.uint8, or np.uint16')
return False
def set_maxSlicesForChunking(self, N):
"""This function effects how forward and backprojection jobs are divided into multiple processing jobs on the GPU
Smaller numbers use less GPU memory, but may slow down processing. Only use this function if you know what you are doing.
For forward projection it specifies the maximum number of detector rows used per job.
For backprojection it specifies the maximum number of CT volume z-slices used per job.
Args:
N (int): the chunk size
"""
self.libprojectors.set_maxSlicesForChunking.restype = ctypes.c_bool
self.libprojectors.set_maxSlicesForChunking.argtypes = [ctypes.c_int]
self.set_model()
return self.libprojectors.set_maxSlicesForChunking(N)
def create_new_model(self):
self.libprojectors.create_new_model.restype = ctypes.c_int
return self.libprojectors.create_new_model()
def copy_parameters(self, leapct):
"""Copies the parameters from another instance of this class"""
self.print_cost = leapct.print_cost
self.print_warnings = leapct.print_warnings
self.volume_mask = leapct.volume_mask
self.set_model()
self.libprojectors.copy_parameters.restype = ctypes.c_bool
self.libprojectors.copy_parameters.argtypes = [ctypes.c_int]
return self.libprojectors.copy_parameters(leapct.param_id)
def reset(self):
"""reset
Resets and clears all parameters
"""
self.set_model()
return self.libprojectors.reset()
def include_cufft(self):
"""Returns True if LEAP is using CUFFT, False otherwise"""
self.libprojectors.include_cufft.restype = ctypes.c_bool
return self.libprojectors.include_cufft()
def about(self):
"""prints info about LEAP, including the version number"""
self.set_model()
self.libprojectors.about()
def version(self):
"""Returns version number string"""
try:
versionText = ctypes.create_string_buffer(16)
self.libprojectors.version(versionText)
if sys.version_info[0] == 3:
return versionText.value.decode("utf-8")
else:
return versionText.value
except:
return "unknown"
def printParameters(self):
"""printParameters
prints all CT geometry and CT volume parameters to the screen
"""
return self.print_parameters()
def print_param(self):
"""printParameters
prints all CT geometry and CT volume parameters to the screen
"""
return self.print_parameters()
def print_parameters(self):
"""print_parameters
prints all CT geometry and CT volume parameters to the screen
"""
self.libprojectors.print_parameters.restype = ctypes.c_bool
self.set_model()
return self.libprojectors.print_parameters()
def all_defined(self):
"""Returns True if all CT geometry and CT volume parameters are defined, False otherwise"""
self.set_model()
self.libprojectors.all_defined.restype = ctypes.c_bool
return self.libprojectors.all_defined()
def ct_geometry_defined(self):
"""Returns True if all CT geometry parameters are defined, False otherwise"""
self.set_model()
self.libprojectors.ct_geometry_defined.restype = ctypes.c_bool
return self.libprojectors.ct_geometry_defined()
def ct_volume_defined(self):
"""Returns True if all CT volume parameters are defined, False otherwise"""
self.set_model()
self.libprojectors.ct_volume_defined.restype = ctypes.c_bool
return self.libprojectors.ct_volume_defined()
def verify_inputs(self, g, f):
""" Verifies that the projection data (g) and the volume data (f) are compatible with the specified parameters """
#if f is None:
# f = g
# check they are the same type
if type(g) != type(f):
print('Error: projection and volume data must be the same type')
return False
# check they are numpy array or torch.tensor
if has_torch:
if type(g) is not np.ndarray and type(g) is not torch.Tensor:
print('Error: projection and volume data must be either numpy arrays or torch tensors')
return False
if type(g) is torch.Tensor:
if g.is_cuda != f.is_cuda:
print('Error: projection and volume data must either both be on the CPU or both be on the GPU')
return False
elif type(g) is not np.ndarray:
print('Error: projection and volume data must be either numpy arrays or torch tensors')
return False
# check they are float32
if has_torch and type(g) is torch.Tensor:
if g.dtype != torch.float32 or f.dtype != torch.float32:
print('Error: projection and volume data must be float32 data type')
return False
if g.is_contiguous() == False or f.is_contiguous() == False:
print('Error: projection and volume data must be contiguous')
return False
else:
if g.dtype != np.float32 or f.dtype != np.float32:
print('Error: projection and volume data must be float32 data type')
return False
if g.data.c_contiguous == False or f.data.c_contiguous == False:
print('Error: projection and volume data must be contiguous')
return False
# check are they 3D arrays
if len(g.shape) != 3 or len(f.shape) != 3:
print('Error: projection and volume data must be 3D arrays')
return False
# check size
self.libprojectors.verify_input_sizes.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int]
self.libprojectors.verify_input_sizes.restype = ctypes.c_bool
self.set_model()
retVal = self.libprojectors.verify_input_sizes(g.shape[0], g.shape[1], g.shape[2], f.shape[0], f.shape[1], f.shape[2])
if retVal == False:
print('Error: projection and/ or volume data shapes do not match specified LEAP settings')
return retVal
def optimalFFTsize(self, N):
self.libprojectors.getOptimalFFTsize.argtypes = [ctypes.c_int]
self.libprojectors.getOptimalFFTsize.restype = ctypes.c_int
return self.libprojectors.getOptimalFFTsize(N)
def extraColumnsForOffsetScan(self):
"""Get the number of extra columns that need to be padded in order to do an offset scan FBP reconstruction
We don't recommend users to use this function. It is just a utility function for the filterProjections function.
"""
if self.get_offsetScan() == False:
return 0
else:
self.set_model()
self.libprojectors.extraColumnsForOffsetScan.restype = ctypes.c_int
return self.libprojectors.extraColumnsForOffsetScan()
###################################################################################################################
###################################################################################################################
# THIS SECTION OF FUNCTIONS SET THE CT SCANNER GEOMETRY PARAMETERS
###################################################################################################################
###################################################################################################################
def set_coneparallel(self, numAngles, numRows, numCols, pixelHeight, pixelWidth, centerRow, centerCol, phis, sod, sdd, tau=0.0, helicalPitch=0.0):
r"""Sets the parameters for a cone-parallel CT geometry
The origin of the coordinate system is always at the center of rotation. The forward (P) and back (P*) projection operators are given by
.. math::
\begin{eqnarray*}
Pf(s, \varphi, \nu) &=& \int_\mathbb{R} f\left(s\boldsymbol{\theta}^\perp(\varphi) + \sqrt{R^2-s^2}\boldsymbol{\theta}(\varphi) + \Delta\left(\varphi + \alpha(s) \right)\widehat{\boldsymbol{z}} + \frac{l}{\sqrt{1+\nu^2}}\left[-\boldsymbol{\theta} + \nu\widehat{\boldsymbol{z}}\right]\right) \, dl \\
P^*g(\boldsymbol{x}) &=& \int \frac{\sqrt{R^2 + \nu^2(\boldsymbol{x},\varphi)}}{\sqrt{R^2-(\boldsymbol{x}\cdot\boldsymbol{\theta}^\perp(\varphi))^2} - \boldsymbol{x}\cdot\boldsymbol{\theta}(\varphi)} g\left(\boldsymbol{x}\cdot\boldsymbol{\theta}^\perp(\varphi), \varphi, \nu(\boldsymbol{x},\varphi) \right) \, d\varphi \\
\nu(\boldsymbol{x},\varphi) &:=& \frac{x_3 - \Delta\left(\varphi + \alpha(\boldsymbol{x}\cdot\boldsymbol{\theta}^\perp(\varphi)) \right)}{\sqrt{R^2-(\boldsymbol{x}\cdot\boldsymbol{\theta}^\perp(\varphi))^2} - \boldsymbol{x}\cdot\boldsymbol{\theta}(\varphi)} \\
\alpha(s) &:=& \sin^{-1}\left(\frac{s}{R}\right) + \sin^{-1}\left(\frac{\tau}{R}\right)
\end{eqnarray*}
Here, we have used :math:`R` for sod, :math:`\tau` for tau, :math:`\Delta` for helicalPitch, and v = t/sdd.
Args:
numAngles (int): number of projection angles
numRows (int): number of rows in the x-ray detector
numCols (int): number of columns in the x-ray detector
pixelHeight (float): the detector pixel pitch (i.e., pixel size) between detector rows, measured in mm
pixelWidth (float): the detector pixel pitch (i.e., pixel size) between detector columns, measured in mm
centerRow (float): the detector pixel row index for the ray that passes from the source, through the origin, and hits the detector
centerCol (float): the detector pixel column index for the ray that passes from the source, through the origin, and hits the detector
phis (float32 numpy array): a numpy array for specifying the angles of each projection, measured in degrees
sod (float): source to object distance, measured in mm; this can also be viewed as the source to center of rotation distance
sdd (float): source to detector distance, measured in mm
tau (float): center of rotation offset
helicalPitch (float): the helical pitch (mm/radians)
Returns:
True if the parameters were valid, false otherwise
"""
self.libprojectors.set_coneparallel.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float, ndpointer(ctypes.c_float, flags="C_CONTIGUOUS"), ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float]
self.libprojectors.set_coneparallel.restype = ctypes.c_bool
if has_torch and type(phis) is torch.Tensor:
phis = phis.cpu().detach().numpy()
elif type(phis) is not np.ndarray:
angularRange = float(phis)
phis = self.setAngleArray(numAngles, angularRange)
if phis.size != numAngles:
print('Error: phis.size != numAngles')
return False
self.set_model()
return self.libprojectors.set_coneparallel(numAngles, numRows, numCols, pixelHeight, pixelWidth, centerRow, centerCol, phis, sod, sdd, tau, helicalPitch)
def set_conebeam(self, numAngles, numRows, numCols, pixelHeight, pixelWidth, centerRow, centerCol, phis, sod, sdd, tau=0.0, helicalPitch=0.0, tiltAngle=0.0):
r"""Sets the parameters for a cone-beam CT geometry
The origin of the coordinate system is always at the center of rotation. The forward (P) and back (P*) projection operators are given by
.. math::
\begin{eqnarray*}
Pf(u,\varphi,v) &:=& \int_\mathbb{R} f\left(R\boldsymbol{\theta}(\varphi) - \tau\boldsymbol{\theta}^\perp(\varphi) + \Delta\varphi\widehat{\boldsymbol{z}} + \frac{l}{\sqrt{1+u^2+v^2}}\left[-\boldsymbol{\theta}(\varphi)+u\boldsymbol{\theta}^\perp(\varphi) + v\widehat{\boldsymbol{z}} \right] \right) \, dl \\
P^*g(\boldsymbol{x}) &=& \int \frac{\sqrt{1+ u^2(\boldsymbol{x},\varphi) +v^2(\boldsymbol{x},\varphi)}}{(R-\boldsymbol{x}\cdot\boldsymbol{\theta}(\varphi))^2} g\left( u(\boldsymbol{x},\varphi), \varphi, v(\boldsymbol{x},\varphi)\right) \, d\varphi \\
u(\boldsymbol{x},\varphi) &:=& \frac{\boldsymbol{x}\cdot \boldsymbol{\theta}^\perp(\varphi) + \tau}{R - \boldsymbol{x}\cdot\boldsymbol{\theta}(\varphi)} \\
v(\boldsymbol{x},\varphi) &:=& \frac{x_3 - \Delta\varphi}{R - \boldsymbol{x}\cdot\boldsymbol{\theta}(\varphi)}
\end{eqnarray*}
for flat-panel cone-beam and
.. math::
\begin{eqnarray*}
Pf(\alpha,\varphi,\nu) &=& \int_\mathbb{R} f\left(R\boldsymbol{\theta}(\varphi) - \tau\boldsymbol{\theta}^\perp(\varphi) + \Delta\varphi\widehat{\boldsymbol{z}} + \frac{l}{\sqrt{1+\nu^2}}\left[-\boldsymbol{\theta}(\varphi-\alpha) + \nu\widehat{\boldsymbol{z}} \right] \right) \, dl \\
P^*g(\boldsymbol{x}) &=& \int \frac{\sqrt{1+\nu^2(\boldsymbol{x},\varphi)}}{\| R\boldsymbol{\theta}(\varphi) - \tau\boldsymbol{\theta}^\perp(\varphi) - \boldsymbol{x} \|^2} g\left(\alpha(\boldsymbol{x},\varphi), \varphi, \nu(\boldsymbol{x},\varphi)\right) \, d\varphi \\
\alpha(\boldsymbol{x},\varphi) &:=& \tan^{-1}\left( \frac{\boldsymbol{x}\cdot \boldsymbol{\theta}^\perp(\varphi) + \tau}{R - \boldsymbol{x}\cdot\boldsymbol{\theta}(\varphi)} \right) \\
\nu(\boldsymbol{x},\varphi) &:=& \frac{x_3 - \Delta\varphi}{\|R\boldsymbol{\theta}(\varphi) - \tau\boldsymbol{\theta}^\perp(\varphi) - \boldsymbol{x} \|}
\end{eqnarray*}
for curved detector cone-beam data. Here, we have used :math:`R` for sod, :math:`\tau` for tau, :math:`\Delta` for helicalPitch, u = s/sdd, and v = t/sdd.
Note that :math:`u = \tan\alpha` and :math:`v = \nu \sqrt{1+u^2}`.
To switch between flat and curved detectors, use the set_flatDetector() and set_curvedDetector() functions. Flat detectors are the default setting.
Args:
numAngles (int): number of projection angles
numRows (int): number of rows in the x-ray detector
numCols (int): number of columns in the x-ray detector
pixelHeight (float): the detector pixel pitch (i.e., pixel size) between detector rows, measured in mm
pixelWidth (float): the detector pixel pitch (i.e., pixel size) between detector columns, measured in mm
centerRow (float): the detector pixel row index for the ray that passes from the source, through the origin, and hits the detector
centerCol (float): the detector pixel column index for the ray that passes from the source, through the origin, and hits the detector
phis (float32 numpy array): a numpy array for specifying the angles of each projection, measured in degrees
sod (float): source to object distance, measured in mm; this can also be viewed as the source to center of rotation distance
sdd (float): source to detector distance, measured in mm
tau (float): center of rotation offset
helicalPitch (float): the helical pitch (mm/radians)
tiltAngle (float) the rotation of the detector around the optical axis (degrees)
Returns:
True if the parameters were valid, false otherwise
"""
self.libprojectors.set_conebeam.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float, ndpointer(ctypes.c_float, flags="C_CONTIGUOUS"), ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float]
self.libprojectors.set_conebeam.restype = ctypes.c_bool
if has_torch and type(phis) is torch.Tensor:
phis = phis.cpu().detach().numpy()
elif type(phis) is not np.ndarray:
angularRange = float(phis)
phis = self.setAngleArray(numAngles, angularRange)
if phis.size != numAngles:
print('Error: phis.size != numAngles')
return False
self.set_model()
return self.libprojectors.set_conebeam(numAngles, numRows, numCols, pixelHeight, pixelWidth, centerRow, centerCol, phis, sod, sdd, tau, tiltAngle, helicalPitch)
def set_coneBeam(self, numAngles, numRows, numCols, pixelHeight, pixelWidth, centerRow, centerCol, phis, sod, sdd, tau=0.0, helicalPitch=0.0, tiltAngle=0.0):
"""Alias for set_conebeam
"""
return self.set_conebeam(numAngles, numRows, numCols, pixelHeight, pixelWidth, centerRow, centerCol, phis, sod, sdd, tau, helicalPitch, tiltAngle)
def set_fanbeam(self, numAngles, numRows, numCols, pixelHeight, pixelWidth, centerRow, centerCol, phis, sod, sdd, tau=0.0):
r"""Sets the parameters for a fan-beam CT geometry
The origin of the coordinate system is always at the center of rotation. The forward (P) and back (P*) projection operators are given by
.. math::
\begin{eqnarray*}
Pf(u,\varphi,x_3) &:=& \int_\mathbb{R} f\left(R\boldsymbol{\theta}(\varphi) - \tau\boldsymbol{\theta}^\perp(\varphi) - \frac{l}{\sqrt{1+u^2}}\left[\boldsymbol{\theta}(\varphi) - u\boldsymbol{\theta}^\perp(\varphi) \right] + x_3\widehat{\boldsymbol{z}} \right) \, dl \\
P^*g(\boldsymbol{x}) &=& \int \frac{1}{R-\boldsymbol{x}\cdot\boldsymbol{\theta}(\varphi)} \sqrt{1 + u^2(\boldsymbol{x},\varphi)} g\left( u(\boldsymbol{x},\varphi), \varphi, x_3\right) \, d\varphi \\
u(\boldsymbol{x},\varphi) &:=& \frac{\boldsymbol{x}\cdot \boldsymbol{\theta}^\perp(\varphi) + \tau}{R - \boldsymbol{x}\cdot\boldsymbol{\theta}(\varphi)}
\end{eqnarray*}
Args:
numAngles (int): number of projection angles
numRows (int): number of rows in the x-ray detector
numCols (int): number of columns in the x-ray detector
pixelHeight (float): the detector pixel pitch (i.e., pixel size) between detector rows, measured in mm
pixelWidth (float): the detector pixel pitch (i.e., pixel size) between detector columns, measured in mm
centerRow (float): the detector pixel row index for the ray that passes from the source, through the origin, and hits the detector
centerCol (float): the detector pixel column index for the ray that passes from the source, through the origin, and hits the detector
phis (float32 numpy array): a numpy array for specifying the angles of each projection, measured in degrees
sod (float): source to object distance, measured in mm; this can also be viewed as the source to center of rotation distance
sdd (float): source to detector distance, measured in mm
tau (float): center of rotation offset
Returns:
True if the parameters were valid, false otherwise
"""
self.libprojectors.set_fanbeam.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float, ndpointer(ctypes.c_float, flags="C_CONTIGUOUS"), ctypes.c_float, ctypes.c_float, ctypes.c_float]
self.libprojectors.set_fanbeam.restype = ctypes.c_bool
if has_torch and type(phis) is torch.Tensor:
phis = phis.cpu().detach().numpy()
elif type(phis) is not np.ndarray:
angularRange = float(phis)
phis = self.setAngleArray(numAngles, angularRange)
if phis.size != numAngles:
print('Error: phis.size != numAngles')
return False
self.set_model()
return self.libprojectors.set_fanbeam(numAngles, numRows, numCols, pixelHeight, pixelWidth, centerRow, centerCol, phis, sod, sdd, tau)
def set_fanBeam(self, numAngles, numRows, numCols, pixelHeight, pixelWidth, centerRow, centerCol, phis, sod, sdd, tau=0.0):
"""Alias for set_fanbeam
"""
return self.set_fanbeam(numAngles, numRows, numCols, pixelHeight, pixelWidth, centerRow, centerCol, phis, sod, sdd, tau)
def set_parallelbeam(self, numAngles, numRows, numCols, pixelHeight, pixelWidth, centerRow, centerCol, phis):
r"""Sets the parameters for a parallel-beam CT geometry
The origin of the coordinate system is always at the center of rotation. The forward (P) and back (P*) projection operators are given by
.. math::
\begin{eqnarray*}
Pf(s, \varphi, x_3) &:=& \int_\mathbb{R} f(s\boldsymbol{\theta}^\perp(\varphi) - l\boldsymbol{\theta}(\varphi) + x_3\widehat{\boldsymbol{z}}) \, dl \\
P^*g(\boldsymbol{x}) &=& \int g(\boldsymbol{x}\cdot\boldsymbol{\theta}^\perp(\varphi), \varphi, x_3) \, d\varphi
\end{eqnarray*}
Args:
numAngles (int): number of projection angles
numRows (int): number of rows in the x-ray detector
numCols (int): number of columns in the x-ray detector
pixelHeight (float): the detector pixel pitch (i.e., pixel size) between detector rows, measured in mm
pixelWidth (float): the detector pixel pitch (i.e., pixel size) between detector columns, measured in mm
centerRow (float): the detector pixel row index for the ray that passes from the source, through the origin, and hits the detector
centerCol (float): the detector pixel column index for the ray that passes from the source, through the origin, and hits the detector
phis (float32 numpy array): a numpy array for specifying the angles of each projection, measured in degrees
Returns:
True if the parameters were valid, false otherwise
"""
self.libprojectors.set_parallelbeam.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float, ndpointer(ctypes.c_float, flags="C_CONTIGUOUS")]
self.libprojectors.set_parallelbeam.restype = ctypes.c_bool
if has_torch and type(phis) is torch.Tensor:
phis = phis.cpu().detach().numpy()
elif type(phis) is not np.ndarray:
angularRange = float(phis)
phis = self.setAngleArray(numAngles, angularRange)
if phis.size != numAngles:
print('Error: phis.size != numAngles')
return False
self.set_model()
return self.libprojectors.set_parallelbeam(numAngles, numRows, numCols, pixelHeight, pixelWidth, centerRow, centerCol, phis)
def set_parallelBeam(self, numAngles, numRows, numCols, pixelHeight, pixelWidth, centerRow, centerCol, phis):
"""Alias for set_parallelbeam
"""
return self.set_parallelbeam(numAngles, numRows, numCols, pixelHeight, pixelWidth, centerRow, centerCol, phis)
def set_modularbeam(self, numAngles, numRows, numCols, pixelHeight, pixelWidth, sourcePositions, moduleCenters, rowVectors, colVectors):
r"""Sets the parameters for a modular-beam CT geometry
The origin of the coordinate system is always at the center of rotation. The forward (P) and back (P*) projection operators are given by
.. math::
\begin{eqnarray*}
Pf(s,t) &:=& \int_{\mathbb{R}} f\left( \boldsymbol{y} + \frac{l}{\sqrt{D^2 + s^2 + t^2}}\left[ \boldsymbol{c}-\boldsymbol{y} + s\boldsymbol{\widehat{u}} + t\boldsymbol{\widehat{v}} \right] \right) \, dl, \\
P^*g(\boldsymbol{x}) &=& <\boldsymbol{c} - \boldsymbol{y}, \boldsymbol{n}> \frac{\| \boldsymbol{c} - \boldsymbol{y} + s\boldsymbol{u} + t\boldsymbol{v} \|}{<\boldsymbol{x} - \boldsymbol{y}, \boldsymbol{n}>^2} g\left(s(\boldsymbol{x}),t(\boldsymbol{x})\right)
\end{eqnarray*}
where
.. math::
\begin{eqnarray*}
s(\boldsymbol{x}) &:=& \frac{<\boldsymbol{c}-\boldsymbol{y},\boldsymbol{n}>}{<\boldsymbol{x}-\boldsymbol{y},\boldsymbol{n}>}<\boldsymbol{x}-\boldsymbol{y},\boldsymbol{u}> - <\boldsymbol{c}-\boldsymbol{y},\boldsymbol{u}> \\
t(\boldsymbol{x}) &:=& \frac{<\boldsymbol{c}-\boldsymbol{y},\boldsymbol{n}>}{<\boldsymbol{x}-\boldsymbol{y},\boldsymbol{n}>}<\boldsymbol{x}-\boldsymbol{y},\boldsymbol{v}> - <\boldsymbol{c}-\boldsymbol{y},\boldsymbol{v}>
\end{eqnarray*}
and :math:`\boldsymbol{y}` be a location of sourcePositions, :math:`\boldsymbol{c}` be a location of moduleCenters,
:math:`\boldsymbol{\widehat{v}}` be a rowVectors instance, :math:`\boldsymbol{\widehat{u}}` be a colVectors instance,
:math:`D := \|\boldsymbol{c}-\boldsymbol{y}\|`, and :math:`\boldsymbol{n} := \boldsymbol{\widehat{u}} \times \boldsymbol{\widehat{v}}`.
Args:
numAngles (int): number of projection angles
numRows (int): number of rows in the x-ray detector
numCols (int): number of columns in the x-ray detector
pixelHeight (float): the detector pixel pitch (i.e., pixel size) between detector rows, measured in mm
pixelWidth (float): the detector pixel pitch (i.e., pixel size) between detector columns, measured in mm
sourcePositions ((numAngles X 3) numpy array): the (x,y,z) position of each x-ray source
moduleCenters ((numAngles X 3) numpy array): the (x,y,z) position of the center of the front face of the detectors
rowVectors ((numAngles X 3) numpy array): the (x,y,z) unit vector pointing along the positive detector row direction
colVectors ((numAngles X 3) numpy array): the (x,y,z) unit vector pointing along the positive detector column direction
Returns:
True if the parameters were valid, false otherwise
"""
if sourcePositions.shape[0] != numAngles:
print('Error: sourcePositions.shape[0] != numAngles')
return False
if moduleCenters.shape[0] != numAngles:
print('Error: moduleCenters.shape[0] != numAngles')
return False
if rowVectors.shape[0] != numAngles:
print('Error: rowVectors.shape[0] != numAngles')
return False
if colVectors.shape[0] != numAngles:
print('Error: colVectors.shape[0] != numAngles')
return False
if sourcePositions.shape[1] != 3:
print('Error: sourcePositions.shape[1] != 3')
return False
if moduleCenters.shape[1] != 3:
print('Error: moduleCenters.shape[1] != 3')
return False
if rowVectors.shape[1] != 3:
print('Error: rowVectors.shape[1] != 3')
return False
if colVectors.shape[1] != 3:
print('Error: colVectors.shape[1] != 3')
return False
self.libprojectors.set_modularbeam.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_float, ctypes.c_float, ndpointer(ctypes.c_float, flags="C_CONTIGUOUS"), ndpointer(ctypes.c_float, flags="C_CONTIGUOUS"), ndpointer(ctypes.c_float, flags="C_CONTIGUOUS"), ndpointer(ctypes.c_float, flags="C_CONTIGUOUS")]
self.libprojectors.set_modularbeam.restype = ctypes.c_bool
self.set_model()
return self.libprojectors.set_modularbeam(numAngles, numRows, numCols, pixelHeight, pixelWidth, sourcePositions, moduleCenters, rowVectors, colVectors)
def set_modularBeam(self, numAngles, numRows, numCols, pixelHeight, pixelWidth, sourcePositions, moduleCenters, rowVectors, colVectors):
"""Alias for set_modularbeam
"""
return self.set_modularbeam(numAngles, numRows, numCols, pixelHeight, pixelWidth, sourcePositions, moduleCenters, rowVectors, colVectors)
def set_geometry(self, which):
"""Sets the CT geometry type parameter"""
self.libprojectors.set_geometry.argtypes = [ctypes.c_int]
self.libprojectors.set_geometry.restype = ctypes.c_bool
self.set_model()
if isinstance(which, int):
return self.set_geometry(which)
elif isinstance(which, str):
if which == 'CONE':
return self.libprojectors.set_geometry(0)
elif which == 'PARALLEL':
return self.libprojectors.set_geometry(1)
elif which == 'FAN':
return self.libprojectors.set_geometry(2)
elif which == 'MODULAR':
return self.libprojectors.set_geometry(3)
elif which == 'CONE-PARALLEL':
return self.libprojectors.set_geometry(4)
else:
return False
else:
return False
def set_tau(self, tau):
"""Set the tau parameter
Args:
tau (float): center of rotation offset in mm (fan- and cone-beam data only)
Returns:
True if the parameters were valid, false otherwise
"""
self.libprojectors.set_tau.argtypes = [ctypes.c_float]
self.libprojectors.set_tau.restype = ctypes.c_bool
self.set_model()
return self.libprojectors.set_tau(tau)
def set_tiltAngle(self, tiltAngle):
"""Set the tiltAngle parameter
Args:
tiltAngle (float): the rotation of the detector around the optical axis (degrees)
Returns:
True if the parameters were valid, false otherwise
"""
self.libprojectors.set_tiltAngle.argtypes = [ctypes.c_float]
self.libprojectors.set_tiltAngle.restype = ctypes.c_bool
self.set_model()
return self.libprojectors.set_tiltAngle(tiltAngle)
def set_helicalPitch(self, helicalPitch):
r"""Set the helicalPitch parameter
This function sets the helicalPitch parameter which is measured in mm/radians. Sometimes the helical pitch is specified in a normalized fashion.
If so, please use the set_normalizedHelicalPitch function.
If we denote the helical pitch by :math:`h` and the normalized helical pitch by :math:`\widehat{h}`, then they are related by
.. math::
\begin{eqnarray*}
h = \frac{numRows * pixelHeight \frac{sod}{sdd}}{2\pi} \widehat{h}
\end{eqnarray*}
Args:
helicalPitch (float): the helical pitch (mm/radians) (cone-beam and cone-parallel data only)
Returns:
True if the parameters were valid, false otherwise
"""
self.libprojectors.set_helicalPitch.argtypes = [ctypes.c_float]
self.libprojectors.set_helicalPitch.restype = ctypes.c_bool
self.set_model()
return self.libprojectors.set_helicalPitch(helicalPitch)
def set_normalizedHelicalPitch(self, normalizedHelicalPitch):
r"""Set the normalized helicalPitch parameter
This function sets the helicalPitch parameter by specifying the normalized helical pitch value.
If we denote the helical pitch by :math:`h` and the normalized helical pitch by :math:`\widehat{h}`, then they are related by
.. math::
\begin{eqnarray*}
h = \frac{numRows * pixelHeight \frac{sod}{sdd}}{2\pi} \widehat{h}
\end{eqnarray*}
Args:
normalizedHelicalPitch (float): the normalized helical pitch (unitless) (cone-beam and cone-parallel data only)
Returns:
True if the parameters were valid, false otherwise
"""
self.libprojectors.set_normalizedHelicalPitch.argtypes = [ctypes.c_float]
self.libprojectors.set_normalizedHelicalPitch.restype = ctypes.c_bool
self.set_model()
return self.libprojectors.set_normalizedHelicalPitch(normalizedHelicalPitch)
def get_normalizedHelicalPitch(self):
"""Get the normalized helical pitch"""
#self.libprojectors.get_normalizedHelicalPitch.argtypes = []
self.libprojectors.get_normalizedHelicalPitch.restype = ctypes.c_float
self.set_model()
return self.libprojectors.get_normalizedHelicalPitch()
def set_flatDetector(self):
"""Set the detectorType to FLAT"""
self.set_model()
self.libprojectors.set_flatDetector.restype = ctypes.c_bool
return self.libprojectors.set_flatDetector()
def set_curvedDetector(self):
"""Set the detectorType to CURVED (only for cone-beam data)"""
self.set_model()
self.libprojectors.set_curvedDetector.restype = ctypes.c_bool
return self.libprojectors.set_curvedDetector()
def get_detectorType(self):
"""Get the detectorType"""
self.set_model()
self.libprojectors.get_detectorType.restype = ctypes.c_int
if self.libprojectors.get_detectorType() == 0:
return 'FLAT'
else:
return 'CURVED'
def set_centerCol(self, centerCol):
"""Set centerCol parameter"""
self.set_model()
self.libprojectors.set_centerCol.restype = ctypes.c_bool
self.libprojectors.set_centerCol.argtypes = [ctypes.c_float]
return self.libprojectors.set_centerCol(centerCol)
def find_centerCol(self, g, iRow=-1, searchBounds=None):
r"""Find the centerCol parameter
This function works by minimizing the difference of conjugate rays, by changing the detector column sample locations. The cost functions
for parallel-beam and fan-beam are given by
.. math::
\begin{eqnarray*}
&&\int \int \left[g(s,\varphi) - g(-s,\varphi \pm \pi)\right]^2 \, ds \, d\varphi \\
&&\int \int \left[g(u,\varphi) - g\left(\frac{-u+\frac{2\tau R}{R^2-\tau^2}}{1+u\left(\frac{2\tau R}{R^2-\tau^2}\right)},\varphi -2\tan^{-1}u + \tan^{-1}\left(\frac{2\tau R}{R^2-\tau^2}\right) \pm \pi\right)\right]^2 \, du \, d\varphi, \\
\end{eqnarray*}
respectively. For rays near the mid-plane, one can also use these cost functions for cone-parallel and cone-beam coordinates as well.
Note that this only works for parallel-, fan-, and cone-beam CT geometry types (i.e., everything but modular-beam)
and one may not get an accurate estimate if the projections are truncated on the right and/or left sides.
If you have any bad edge detectors, these must be cropped out before running this algorithm.
If this function does not return a good estimate, try changing the iRow parameter value or try using the
inconsistencyReconstruction function is this class.
See d12_geometric_calibration.py for a working example that uses this function.
Args:
g (C contiguous float32 numpy array or torch tensor): projection data
iRow (int): The detector row index to be used for the estimation, if no value is given, uses the row closest to the centerRow parameter
searchBounds (2-element array): optional argument to specify the interval for which to perform the search
Returns:
the error metric value
"""
if iRow is None:
iRow = -1
if searchBounds is None:
searchBounds = -1.0*np.ones(2, dtype=np.float32)
else:
searchBounds = np.array(searchBounds, dtype=np.float32)
self.libprojectors.find_centerCol.restype = ctypes.c_float
self.set_model()
if has_torch == True and type(g) is torch.Tensor:
self.libprojectors.find_centerCol.argtypes = [ctypes.c_void_p, ctypes.c_int, ndpointer(ctypes.c_float, flags="C_CONTIGUOUS"), ctypes.c_bool]
return self.libprojectors.find_centerCol(g.data_ptr(), iRow, searchBounds, g.is_cuda == False)
else:
self.libprojectors.find_centerCol.argtypes = [ndpointer(ctypes.c_float, flags="C_CONTIGUOUS"), ctypes.c_int, ndpointer(ctypes.c_float, flags="C_CONTIGUOUS"), ctypes.c_bool]
return self.libprojectors.find_centerCol(g, iRow, searchBounds, True)
def find_tau(self, g, iRow=-1, searchBounds=None):
r"""Find the tau parameter
This function works by minimizing the difference of conjugate rays, by changing the horizontal source position shift (equivalent to rotation stage shifts).
The cost function for fan-beam is given by
.. math::
\begin{eqnarray*}
&&\int \int \left[g(u,\varphi) - g\left(\frac{-u+\frac{2\tau R}{R^2-\tau^2}}{1+u\left(\frac{2\tau R}{R^2-\tau^2}\right)},\varphi -2\tan^{-1}u + \tan^{-1}\left(\frac{2\tau R}{R^2-\tau^2}\right) \pm \pi\right)\right]^2 \, du \, d\varphi, \\
\end{eqnarray*}
For rays near the mid-plane, one can also use these cost functions for cone-beam coordinates as well.
Note that this only works for fan- and cone-beam CT geometry types
and one may not get an accurate estimate if the projections are truncated on the right and/or left sides.
If you have any bad edge detectors, these must be cropped out before running this algorithm.
If this function does not return a good estimate, try changing the iRow parameter value or try using the
inconsistencyReconstruction function is this class.
See d12_geometric_calibration.py for a working example that uses this function.
Args:
g (C contiguous float32 numpy array or torch tensor): projection data
iRow (int): The detector row index to be used for the estimation, if no value is given, uses the row closest to the centerRow parameter
searchBounds (2-element array): optional argument to specify the interval for which to perform the search
Returns:
the error metric value
"""
if iRow is None:
iRow = -1
if searchBounds is None:
searchBounds = -1.0*np.ones(2, dtype=np.float32)
else:
searchBounds = np.array(searchBounds, dtype=np.float32)
self.libprojectors.find_tau.restype = ctypes.c_float
self.set_model()
if has_torch == True and type(g) is torch.Tensor:
self.libprojectors.find_tau.argtypes = [ctypes.c_void_p, ctypes.c_int, ndpointer(ctypes.c_float, flags="C_CONTIGUOUS"), ctypes.c_bool]
return self.libprojectors.find_tau(g.data_ptr(), iRow, searchBounds, g.is_cuda == False)
else:
self.libprojectors.find_tau.argtypes = [ndpointer(ctypes.c_float, flags="C_CONTIGUOUS"), ctypes.c_int, ndpointer(ctypes.c_float, flags="C_CONTIGUOUS"), ctypes.c_bool]
return self.libprojectors.find_tau(g, iRow, searchBounds, True)
def estimate_tilt(self, g):
"""Estimates the tilt angle (around the optical axis) of the detector
This algorithm works by minimizing the difference between conjugate projections (those projections separated by 180 degrees).
If the input data is fan-beam or cone-beam it first rebins the data to parallel-beam or cone-parallel coordinates first
and then calculates the difference of conjugate projections. This algorithm works best if centerCol is properly specified
before running this algorithm.
Note that this function does not update any CT geometry parameters.
See also the conjugate_difference function.
Example Usage:
gamma = leapct.estimate_tilt(g)
leapct.set_tiltAngle(gamma)
Note that it only works for parallel-beam, fan-beam, cone-beam, and cone-parallel CT geometry types (i.e., everything but modular-beam)
and one may not get an accurate estimate if the projections are truncated on the right and/or left sides.
If you have any bad edge detectors, these must be cropped out before running this algorithm.
If this function does not return a good estimate, try using the
inconsistencyReconstruction function is this class.
See d12_geometric_calibration.py for a working example that uses this function.
Args:
g (C contiguous float32 numpy array or torch tensor): projection data
Returns:
the tilt angle (in degrees)
"""
self.libprojectors.estimate_tilt.restype = ctypes.c_float
self.set_model()
if has_torch == True and type(g) is torch.Tensor:
self.libprojectors.estimate_tilt.argtypes = [ctypes.c_void_p, ctypes.c_bool]
return self.libprojectors.estimate_tilt(g.data_ptr(), g.is_cuda == False)
else:
self.libprojectors.estimate_tilt.argtypes = [ndpointer(ctypes.c_float, flags="C_CONTIGUOUS"), ctypes.c_bool]
return self.libprojectors.estimate_tilt(g, True)
def conjugate_difference(self, g, alpha=0.0, centerCol=None):
"""Calculates the difference of conjugate projections with optional detector rotation and detector shift
This algorithm calculates the difference between conjugate projections (those projections separated by 180 degrees).
If the input data is fan-beam or cone-beam it first rebins the data to parallel-beam or cone-parallel coordinates first
and then calculates the difference of conjugate projections. The purpose of this function is to provide a metric
for estimating detector tilt (rotation around the optical axis) and horizonal detector shifts (centerCol).
Note that it only works for parallel-beam, fan-beam, cone-beam, and cone-parallel CT geometry types (i.e., everything but modular-beam)
and one may not get an accurate estimate if the projections are truncated on the right and/or left sides.
If you have any bad edge detectors, these must be cropped out before running this algorithm.
If this function does not return a good estimate, try using the
inconsistencyReconstruction function is this class.
See d12_geometric_calibration.py for a working example that uses this function.
Args:
g (C contiguous float32 numpy array or torch tensor): projection data
alpha (float): detector rotation (around the optical axis) in degrees
centerCol (float): the centerCol parameter to use (if unspecified uses the current value of centerCol)
Returns:
2D numpy array of the difference of two conjugate projections
"""