/
fbp.cpp
2194 lines (1751 loc) · 73.9 KB
/
fbp.cpp
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
#include "fbp.h"
#include "pointprocess.h"
#include "fft.h"
#include "utilities.h"
#include "math/vectoroperations.h"
#include "interpolation.h"
#include "transform.h"
#include "filters.h"
#include "math/vec4.h"
#include "io/raw.h"
#include "generation.h"
#if defined(USE_OPENCL)
#if defined(__APPLE__)
#error OpenCL is not currently supported in MacOS builds. Use NO_OPENCL=1 make argument.
#define CL_HPP_ENABLE_EXCEPTIONS
#define CL_HPP_MINIMUM_OPENCL_VERSION 110
#define CL_HPP_TARGET_OPENCL_VERSION 110
// TODO: CL version seems to be different in MacOS, size_t template is missing.
// TODO: Update code to the newest version in Windows and Linux, and check if
// that works in MacOS, too.
#else
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#endif
#endif
#include <iostream>
#include <functional>
#include <array>
using namespace std;
namespace itl2
{
//ostream& operator<<(ostream& stream, const RecSettings& s)
//{
// // TODO: Do this through ImageMetaData object
// stream << "source_to_ra = " << s.sourceToRA << endl;
// stream << "rotation_direction = " << s.rotationDirection << endl;
// stream << "bhc = " << s.bhc << endl;
// stream << "rec_as_180_deg_scan = " << s.reconstructAs180degScan << endl;
// stream << "central_angle = " << s.centralAngleFor180degScan << endl;
// stream << "angle_tweak = " << s.angleTweak << endl;
// stream << "hswp = " << s.heuristicSinogramWindowingParameter << endl;
// stream << "rotation = " << s.rotation << endl;
// stream << "roi_center = " << s.roiCenter << endl;
// stream << "roi_size = " << s.roiSize << endl;
// stream << "crop_size = " << s.cropSize << endl;
// stream << "binning = " << s.binning << endl;
// stream << "remove_dead_pixels = " << s.removeDeadPixels << endl;
// stream << "dead_pixel_median_radius = " << s.deadPixelMedianRadius << endl;
// stream << "dead_pixel_std_dev_count = " << s.deadPixelStdDevCount << endl;
// stream << endl;
// stream << "center_shift = " << s.centerShift << endl;
// stream << "camera_z_shift = " << s.cameraZShift << endl;
// stream << "camera_rotation = " << s.cameraRotation << endl;
// stream << "cs_angle_slope = " << s.csAngleSlope << endl;
// stream << endl;
// stream << "pad_type = " << s.padType << endl;
// stream << "pad_size = " << s.padFraction << endl;
// stream << "filter_type = " << s.filterType << endl;
// stream << "filter_cut_off = " << s.filterCutOff << endl;
// stream << endl;
// stream << "phase_mode = " << s.phaseMode << endl;
// stream << "phase_pad_type = " << s.phasePadType << endl;
// stream << "phase_pad_size = " << s.phasePadFraction << endl;
// stream << "propagation_distance = " << s.objectCameraDistance << endl;
// stream << "delta = " << s.delta << endl;
// stream << "mu = " << s.mu << endl;
// stream << endl;
// stream << "range_min = " << s.dynMin << endl;
// stream << "range_max = " << s.dynMax << endl;
// stream << endl;
// stream << "shift_scale = " << s.shiftScaling << endl;
// stream << "use_shifts = " << s.useShifts << endl;
// stream << endl;
// stream << "angles" << endl;
// stream.precision(17);
// for (size_t n = 0; n < s.angles.size(); n++)
// stream << fixed << s.angles[n] << endl;
// stream << endl;
// stream << "sample_shifts" << endl;
// for (size_t n = 0; n < s.sampleShifts.size(); n++)
// stream << fixed << s.sampleShifts[n] << endl;
// stream << endl;
// stream << "source_shifts" << endl;
// for (size_t n = 0; n < s.sourceShifts.size(); n++)
// stream << fixed << s.sourceShifts[n] << endl;
// stream << endl;
// stream << "camera_shifts" << endl;
// for (size_t n = 0; n < s.cameraShifts.size(); n++)
// stream << fixed << s.cameraShifts[n] << endl;
// stream << endl;
// stream << "rotation_axis_shifts" << endl;
// for (size_t n = 0; n < s.rotationAxisShifts.size(); n++)
// stream << fixed << s.rotationAxisShifts[n] << endl;
// stream << endl;
// return stream;
//}
void RecSettings::toMeta(ImageMetadata& meta) const
{
meta.set("source_to_ra", sourceToRA);
meta.set("rotation_direction", rotationDirection);
meta.set("bhc", bhc);
meta.set("rec_as_180_deg_scan", reconstructAs180degScan);
meta.set("central_angle", centralAngleFor180degScan);
meta.set("hswp", heuristicSinogramWindowingParameter);
meta.set("rotation", rotation);
meta.set("roi_center", roiCenter);
meta.set("roi_size", roiSize);
meta.set("crop_size", cropSize);
meta.set("binning", binning);
meta.set("remove_dead_pixels", removeDeadPixels);
meta.set("dead_pixel_median_radius", deadPixelMedianRadius);
meta.set("dead_pixel_std_dev_count", deadPixelStdDevCount);
meta.set("center_shift", centerShift);
meta.set("camera_z_shift", cameraZShift);
meta.set("camera_rotation", cameraRotation);
meta.set("rotation_axis_tils", rotationAxisTilt);
meta.set("cs_angle_slope", csAngleSlope);
meta.set("angle_tweak", angleTweak);
meta.set("pad_type", padType);
meta.set("pad_size", padFraction);
meta.set("filter_type", filterType);
meta.set("filter_cut_off", filterCutOff);
meta.set("phase_mode", phaseMode);
meta.set("phase_pad_type", phasePadType);
meta.set("phase_pad_size", phasePadFraction);
meta.set("propagation_distance", objectCameraDistance);
meta.set("delta", delta);
meta.set("mu", mu);
meta.set("range_min", dynMin);
meta.set("range_max", dynMax);
meta.set("shift_scale", shiftScaling);
meta.set("use_shifts", useShifts);
meta.set("angles", angles);
meta.set("sample_shifts", sampleShifts);
meta.set("source_shifts", sourceShifts);
meta.set("camera_shifts", cameraShifts);
meta.set("rotation_axis_shifts", rotationAxisShifts);
}
void checkMetaItem(const string& item, const ImageMetadata& meta)
{
if (!meta.contains(item))
throw ITLException(string("'") + item + "' item is missing from image metadata.");
}
RecSettings RecSettings::fromMeta(ImageMetadata& meta)
{
// This constructs default settings
RecSettings s;
// Check that essential metadata exists.
checkMetaItem("source_to_ra", meta);
//checkMetaItem("angles", meta);
string anglesName;
if (meta.contains("angles"))
anglesName = "angles";
else if (meta.contains("Angles [deg]"))
anglesName = "Angles [deg]";
else
throw ITLException("'angles' item or 'Angles [deg]' item is missing from image metadata.");
s.sourceToRA = meta.get("source_to_ra", s.sourceToRA);
s.rotationDirection = meta.get("rotation_direction", s.rotationDirection);
s.bhc = meta.get("bhc", s.bhc);
s.reconstructAs180degScan = meta.get("rec_as_180_deg_scan", s.reconstructAs180degScan);
s.centralAngleFor180degScan = meta.get("central_angle", s.centralAngleFor180degScan);
s.heuristicSinogramWindowingParameter = meta.get("hswp", s.heuristicSinogramWindowingParameter);
s.rotation = meta.get("rotation", s.rotation);
s.roiCenter = meta.get("roi_center", s.roiCenter);
s.roiSize = meta.get("roi_size", s.roiSize);
s.cropSize = meta.get("crop_size", s.cropSize);
s.binning = meta.get("binning", s.binning);
s.removeDeadPixels = meta.get("remove_dead_pixels", s.removeDeadPixels);
s.deadPixelMedianRadius = meta.get("dead_pixel_median_radius", s.deadPixelMedianRadius);
s.deadPixelStdDevCount = meta.get("dead_pixel_std_dev_count", s.deadPixelStdDevCount);
s.centerShift = meta.get("center_shift", s.centerShift);
s.cameraZShift = meta.get("camera_z_shift", s.cameraZShift);
s.cameraRotation = meta.get("camera_rotation", s.cameraRotation);
s.rotationAxisTilt = meta.get("rotation_axis_tilt", s.rotationAxisTilt);
s.csAngleSlope = meta.get("cs_angle_slope", s.csAngleSlope);
s.angleTweak = meta.get("angle_tweak", s.angleTweak);
s.padType = meta.get("pad_type", s.padType);
s.padFraction = meta.get("pad_size", s.padFraction);
s.filterType = meta.get("filter_type", s.filterType);
s.filterCutOff = meta.get("filter_cut_off", s.filterCutOff);
s.phaseMode = meta.get("phase_mode", s.phaseMode);
s.phasePadType = meta.get("phase_pad_type", s.phasePadType);
s.phasePadFraction = meta.get("phase_pad_size", s.phasePadFraction);
s.objectCameraDistance = meta.get("propagation_distance", s.objectCameraDistance);
s.delta = meta.get("delta", s.delta);
s.mu = meta.get("mu", s.mu);
s.dynMin = meta.get("range_min", s.dynMin);
s.dynMax = meta.get("range_max", s.dynMax);
s.shiftScaling = meta.get("shift_scale", s.shiftScaling);
s.useShifts = meta.get("use_shifts", s.useShifts);
std::vector<float32_t> emptyV1;
s.angles = meta.getList<float32_t>(anglesName, emptyV1, true);
std::vector<Vec2f> emptyV2;
std::vector<Vec3f> emptyV3;
s.sampleShifts = meta.getList<Vec3f>("sample_shifts", emptyV3, false);
s.sourceShifts = meta.getList<Vec3f>("source_shifts", emptyV3, false);
s.cameraShifts = meta.getList<Vec3f>("camera_shifts", emptyV3, false);
s.rotationAxisShifts = meta.getList<Vec3f>("rotation_axis_shifts", emptyV3, false);
// If there are no shifts supplied, set all shifts to zero.
if (s.sampleShifts.size() <= 0)
{
while (s.sampleShifts.size() < s.angles.size())
s.sampleShifts.push_back(Vec3f(0, 0, 0));
}
return s;
}
/**
Performs phase retrieval for single projection slice.
*/
void paganinSlice(Image<float32_t>& slice, PadType padType, float32_t padFraction, float32_t objectSourceDistance, float32_t objectCameraDistance, float32_t delta, float32_t mu)
{
clamp(padFraction, 0.0f, 1.0f);
size_t mirrorSizeX = (size_t)round(padFraction * slice.width());
size_t mirrorSizeY = (size_t)round(padFraction * slice.height());
size_t paddedWidth = mirrorSizeX + slice.width() + mirrorSizeX;
size_t paddedHeight = mirrorSizeY + slice.height() + mirrorSizeY;
size_t width = (size_t)slice.width();
size_t height = (size_t)slice.height();
Image<float32_t> in(paddedWidth, paddedHeight);
Image<complex32_t> out;
for (size_t z0 = 0; z0 < paddedHeight; z0++)
{
int z = (int)z0 - (int)mirrorSizeY;
if (padType == PadType::Mirror)
{
if (z < 0)
z = -z;
else if (z >= (int)height)
z = (int)height - 1 - (z - (int)height);
}
else if (padType == PadType::Nearest)
{
if (z < 0)
z = 0;
else if (z >= (int)height)
z = (int)height - 1;
}
else
throw runtime_error("Pad type not supported.");
// Copy data to input buffer and do padding
for (size_t x = 0; x < mirrorSizeX; x++)
{
if (padType == PadType::Mirror)
in(mirrorSizeX - x - 1, z0) = slice(x, z);
else if (padType == PadType::Nearest)
in(mirrorSizeX - x - 1, z0) = slice(0, z); //in[z0 * paddedWidth + mirrorSize - x - 1]
else
throw runtime_error("Pad type not supported.");
}
for (size_t x = 0; x < width; x++)
{
in(mirrorSizeX + x, z0) = slice(x, z);
}
for (size_t x = 0; x < mirrorSizeX; x++)
{
if (padType == PadType::Mirror)
in(mirrorSizeX + width + x, z0) = slice(width - x - 1, z);
else if (padType == PadType::Nearest)
in(mirrorSizeX + width + x, z0) = slice(width - 1, z);
else
throw runtime_error("Pad type not supported.");
}
}
float32_t M = (objectCameraDistance + objectSourceDistance) / objectSourceDistance;
multiply(in, M*M);
// FFT
fft(in, out);
// Multiply by (1 + 4pi^2 d delta/mu |w|^2)^-1
// w = 0 are at (0, 0), and (0, outHeight)
for (coord_t y = 0; y < out.height(); y++)
{
for (coord_t x = 0; x < out.width(); x++)
{
double dx = (double)(x - 0);
double dy = (double)std::min(y - 0, out.height() - y);
double w2 = dx * dx + dy * dy;
double trans = 1 / (1 + 4 * PI * PI * objectCameraDistance * delta / mu * w2 / M);
out(x, y) *= (float)trans;
}
}
// Inverse FFT
ifft(out, in);
// Remove padding and replace original data
for (size_t z = 0; z < height; z++)
{
for (size_t x = 0; x < width; x++)
{
slice(x, z) = in(x + mirrorSizeX, z + mirrorSizeY);
}
}
// Take negative logarithm
negLog(slice);
}
/**
Performs Paganin phase retrieval.
*/
void paganin(Image<float32_t>& transmissionProjections, PadType padType, float32_t padFraction, float32_t objectSourceDistance, float32_t objectCameraDistance, float32_t delta, float32_t mu)
{
cout << "Single material Paganin phase-retrieval..." << endl;
// Calculate Paganin (single material) filtering
size_t counter = 0;
#pragma omp parallel for
for (coord_t anglei = 0; anglei < transmissionProjections.depth(); anglei++)
{
Image<float32_t> slice(transmissionProjections, anglei, anglei);
paganinSlice(slice, padType, padFraction, objectSourceDistance, objectCameraDistance, delta, mu);
showThreadProgress(counter, transmissionProjections.depth());
}
}
/**
Performs phase retrieval or -log operation on a single transmission projection slice.
*/
void phaseRetrievalSlice(Image<float32_t>& slice, PhaseMode phaseMode, PadType padType, float32_t padFraction, float32_t objectSourceDistance, float32_t objectCameraDistance, float32_t delta, float32_t mu)
{
switch (phaseMode)
{
case PhaseMode::Absorption:
negLog(slice);
break;
case PhaseMode::Paganin:
paganinSlice(slice, padType, padFraction, objectSourceDistance, objectCameraDistance, delta, mu);
break;
case PhaseMode::Direct:
// The data is already in -ln(I/I0) format or equivalent, so do not do anything.
break;
default:
throw ITLException("Unsupported phase retrieval mode.");
}
}
/**
Performs phase retrieval or -log operation on transmission projections.
*/
void phaseRetrieval(Image<float32_t>& transmissionProjections, PhaseMode phaseMode, PadType padType, float32_t padFraction, float32_t objectSourceDistance, float32_t objectCameraDistance, float32_t delta, float32_t mu)
{
switch (phaseMode)
{
case PhaseMode::Absorption:
negLog(transmissionProjections);
break;
case PhaseMode::Paganin:
paganin(transmissionProjections, padType, padFraction, objectSourceDistance, objectCameraDistance, delta, mu);
break;
case PhaseMode::Direct:
// The data is already in -ln(I/I0) format or equivalent, so do not do anything.
break;
default:
throw ITLException("Unsupported phase retrieval mode.");
}
}
/*
Performs beam hardening correction for data for which -log has been taken. Replaces original data.
*/
void beamHardeningCorrection(Image<float32_t>& transmissionProjections, float32_t bhc)
{
#pragma omp parallel for if(!omp_in_parallel())
for (coord_t n = 0; n < transmissionProjections.pixelCount(); n++)
{
float32_t x = transmissionProjections(n);
x = x + bhc * x * x;
if (!isfinite(x))
x = 0;
transmissionProjections(n) = x;
}
}
namespace internals
{
/**
Calculate true central angle for scan from user-specified central angle.
@param gammamax0 Maximum half cone angle on optical axis.
*/
float32_t calculateTrueCentralAngle(float32_t centralAngleFor180degScan, const vector<float32_t>& angles, float32_t gammamax0)
{
float32_t minAngle = min(angles) + 90 + gammamax0;
float32_t maxAngle = max(angles) - 90 - gammamax0;
clamp(centralAngleFor180degScan, minAngle, maxAngle);
return centralAngleFor180degScan;
}
/**
Calculates maximum half cone angle on optical axis.
@param d Distance between object and cone tip.
*/
float32_t calculateGammaMax0(float32_t projectionWidth, float32_t d)
{
return atan2f(projectionWidth / 2.0f, d) / PIf * 180.0f;
}
float32_t csAnglePerturbation(size_t angleIndex, float32_t centralAngle, const vector<float32_t>& angles, float32_t csAngleSlope)
{
return (angles[angleIndex] - centralAngle) * csAngleSlope;
}
/**
Checks that projection images and settings correspond to each other.
Adjusts zero elements in roi size vector to full image dimension.
*/
void sanityCheck(const Image<float32_t>& transmissionProjections, RecSettings& settings, bool projectionsAreBinned)
{
if (transmissionProjections.depth() != settings.angles.size())
throw ITLException("Count of projection images and count of angles do not match.");
size_t projCount = settings.angles.size();
if (settings.sampleShifts.size() > 0 && settings.sampleShifts.size() != projCount)
throw ITLException("Count of sample shifts and count of angles do not match.");
if (settings.rotationAxisShifts.size() > 0 && settings.rotationAxisShifts.size() != projCount)
throw ITLException("Count of rotation axis shifts and count of angles do not match.");
if (settings.cameraShifts.size() > 0 && settings.cameraShifts.size() != projCount)
throw ITLException("Count of camera shifts and count of angles do not match.");
if (settings.sourceShifts.size() > 0 && settings.sourceShifts.size() != projCount)
throw ITLException("Count of source shifts and count of angles do not match.");
if (NumberUtils<float32_t>::lessThanOrEqual(settings.sourceToRA, 0))
throw ITLException("Non-positive source to rotation axis distance.");
if (settings.binning < 1)
throw ITLException("Binning must be at least 1.");
// Roi size and position
if (settings.roiSize.x <= 0)
settings.roiSize.x = projectionsAreBinned ? transmissionProjections.width() * settings.binning : transmissionProjections.width();
if (settings.roiSize.x <= 0)
settings.roiSize.x = 1;
if (settings.roiSize.y <= 0)
settings.roiSize.y = projectionsAreBinned ? transmissionProjections.width() * settings.binning : transmissionProjections.width();
if (settings.roiSize.y <= 0)
settings.roiSize.y = 1;
if (settings.roiSize.z <= 0)
settings.roiSize.z = projectionsAreBinned ? transmissionProjections.height() * settings.binning : transmissionProjections.height();
if (settings.roiSize.z <= 0)
settings.roiSize.z = 1;
}
}
/**
Applies cone-beam related weighting of -log data (after beam hardening correction, before filtering) for single projection image slice.
*/
void fbpWeightingSlice(Image<float32_t>& slice, coord_t angleIndex, bool reconstructAs180DegScan, const vector<float32_t>& angles, float32_t baseCenterShift, float32_t csAngleSlope, float32_t sourceToRA, float32_t cameraZShift, float32_t centralAngle, float32_t gammaMax0, float32_t heuristicSinogramWindowingParameter)
{
// TODO: How to calculate these in the new geometry? These shifts are probably not very important...
//float32_t dx = settings.objectShifts[anglei].x;
//float32_t dz = settings.objectShifts[anglei].y;
float32_t dx = 0;
float32_t dz = 0;
float proj_weight = 1;
if (!reconstructAs180DegScan)
{
// Remove data outside of 360 deg range
if (angleIndex > 0)
{
if (NumberUtils<float32_t>::greaterThan(abs(angles[angleIndex] - angles[0]), 360 - (angles[1] - angles[0]), 0.1f * abs(angles[1] - angles[0])))
{
//cout << "Excess projection removed (index = " << angleIndex << ", angle = " << angles[angleIndex] << " deg)." << endl;
proj_weight = 0;
}
}
}
float centerShift = baseCenterShift + internals::csAnglePerturbation(angleIndex, centralAngle, angles, csAngleSlope);
//cout << "angle = " << angles[phi] << ", cs = " << centerShift << endl;
float32_t d = sourceToRA;
coord_t height = slice.height();
coord_t width = slice.width();
for (coord_t z = 0; z < height; z++)
{
float Z = (float)z - (height / 2.0f - dz) - cameraZShift;
for (coord_t y = 0; y < width; y++)
{
float Y = (float)y - ((float)width / 2.0f - dx) - centerShift;
// Weight inherent in FDK algorithm
float w = d / sqrt(d * d + Y * Y + Z * Z);
float sin_weight = 1;
if (reconstructAs180DegScan)
{
// Smooth sinogram windowing for 180 deg scan
// Original version with symmetric smoothing
float f = abs(Z / (0.5f * height));
float gammamax = (1 - f) * gammaMax0 + f * heuristicSinogramWindowingParameter * gammaMax0;
// Angle from view direction to current ray
float gamma = atan2f(Y, d) / PIf * 180.0f;
// Angle of the current projection
float beta = (float)(angles[angleIndex] - (centralAngle - 90));
// Determine weight
if (-gammamax <= beta && beta <= gammamax - 2 * gamma) // Left side shape
{
float sinterm = sinf((45 * ((beta + gammamax) / (gammamax - gamma))) / 180 * PIf);
sin_weight = sinterm * sinterm;
}
else if (-gammamax <= beta - 360 && beta - 360 <= gammamax - 2 * gamma) // Left side shape modulo
{
float sinterm = sinf((45 * ((beta - 360) + gammamax) / (gammamax - gamma)) / 180 * PIf);
sin_weight = sinterm * sinterm;
}
else if (gammamax - 2 * gamma <= beta && beta <= 180 - gammamax - 2 * gamma || // Middle flat
gammamax - 2 * gamma <= beta + 360 && beta + 360 <= 180 - gammamax - 2 * gamma || // Middle flat modulo
gammamax - 2 * gamma <= beta - 360 && beta - 360 <= 180 - gammamax - 2 * gamma) // Middle flat modulo
{
sin_weight = 1;
}
else if (180 - gammamax - 2 * gamma <= beta && beta <= 180 + gammamax) // Right side shape
{
float sinterm = sinf((45 * ((180 + gammamax - beta) / (gammamax + gamma))) / 180 * PIf);
sin_weight = sinterm * sinterm;
}
else if (180 - gammamax - 2 * gamma <= beta + 360 && beta + 360 <= 180 + gammamax) // Right side shape modulo
{
float sinterm = sinf((45 * (180 + gammamax - (beta + 360)) / (gammamax + gamma)) / 180 * PIf);
sin_weight = sinterm * sinterm;
}
else
{
sin_weight = 0;
}
}
slice(y, z) *= w * sin_weight * proj_weight;
}
}
}
/**
Applies cone-beam related weighting of -log data (after beam hardening correction, before filtering).
*/
void fbpWeighting(Image<float32_t>& transmissionProjections, bool reconstructAs180DegScan, const vector<float32_t>& angles, float32_t centerShift, float32_t csAngleSlope, float32_t sourceToRA, float32_t cameraZShift, float32_t centralAngle, float32_t gammaMax0, float32_t heuristicSinogramWindowingParameter)
{
// Apply weighting
#pragma omp parallel for
for (int anglei = 0; anglei < transmissionProjections.depth(); anglei++)
{
Image<float32_t> slice(transmissionProjections, anglei, anglei);
fbpWeightingSlice(slice, anglei, reconstructAs180DegScan, angles, centerShift, csAngleSlope, sourceToRA, cameraZShift, centralAngle, gammaMax0, heuristicSinogramWindowingParameter);
}
}
/**
Constructs a backprojection filter into given image. Image width must be set to correct value.
@param cutoff Frequency cutoff, 1 corresponds to Nyquist frequency, 0 to DC.
*/
void createFilter(Image<float32_t>& filter, FilterType filterType, float32_t cutoff)
{
switch (filterType)
{
case FilterType::IdealRamp:
{
// Normal sharp |w| filter
// This filter was used in the old versions.
double k1 = (1.0 - 0.0) / (filter.width() - 1 - 0.0);
for (coord_t x = 0; x < filter.width(); x++)
{
float r = (float)(k1*x);
filter(x) = r;
}
break;
}
case FilterType::Ramp:
{
initFFTW();
coord_t s = filter.width() - 1;
coord_t pow2 = s << 1;
Image<complex32_t> F(pow2);
fftwf_plan plan;
#pragma omp critical
{
plan = fftwf_plan_dft_1d((int)pow2, (fftwf_complex*)F.getData(), (fftwf_complex*)F.getData(), FFTW_FORWARD, FFTW_ESTIMATE);
}
F(0) = 0.25;
for (coord_t i = 1; i < F.width(); i++)
{
if (i <= s)
{
if (i & 0x1)
F(i) = -1.0f / (PIf * PIf * (float32_t)i * (float32_t)i);
else
F(i) = 0;
}
else
F(i) = F(pow2 - i);
}
fftwf_execute(plan);
for (coord_t n = 0; n < filter.width(); n++)
filter(n) = 2 * F(n).real();
#pragma omp critical
{
fftwf_destroy_plan(plan);
}
break;
}
case FilterType::SheppLogan:
{
createFilter(filter, FilterType::Ramp, cutoff);
for (coord_t i = 1; i < filter.width(); i++)
{
double factor = (PI * filter(i)) / (2.0 * cutoff);
filter(i) *= (float32_t)(sin(factor) / factor);
}
break;
}
case FilterType::Cosine:
{
createFilter(filter, FilterType::Ramp, cutoff);
for (coord_t i = 1; i < filter.width(); i++)
{
double factor = (PI * filter(i)) / (2.0 * cutoff);
filter(i) *= (float32_t)cos(factor);
}
break;
}
case FilterType::Hamming:
{
createFilter(filter, FilterType::Ramp, cutoff);
for (coord_t i = 1; i < filter.width(); i++)
{
double factor = (PI * filter(i)) / cutoff;
filter(i) *= (float32_t)(0.54 + 0.46 * cos(factor));
}
break;
}
case FilterType::Hann:
{
createFilter(filter, FilterType::Ramp, cutoff);
for (coord_t i = 1; i < filter.width(); i++)
{
double factor = (PI * filter(i)) / cutoff;
filter(i) *= (float32_t)(0.5 + 0.5 * cos(factor));
}
break;
}
case FilterType::Blackman:
{
createFilter(filter, FilterType::Ramp, cutoff);
for (coord_t i = 1; i < filter.width(); i++)
{
double factor = (PI * filter(i)) / cutoff + PI;
filter(i) *= (float32_t)(0.42 - 0.5 * cos(factor) + 0.08 * cos(2 * factor));
}
break;
}
case FilterType::Parzen:
{
createFilter(filter, FilterType::Ramp, cutoff);
for (coord_t i = 1; i < filter.width(); i++)
{
double L = 2.0 * (double)filter.width() * cutoff;
double n = (double)i;// filter(i);
double q = n / (L / 2);
double w;
if (n <= L / 4)
w = 1 - 6 * q * q * (1 - q);
else
w = 2 * (1 - q) * (1 - q) * (1 - q);
filter(i) *= (float32_t)w;
}
break;
}
default:
{
throw ITLException("Unsupported backprojection filter.");
}
}
// Reset everything above cutoff
coord_t ind = pixelRound<coord_t>(cutoff * (filter.width() - 1));
for (coord_t n = ind + 1; n < filter.width(); n++)
filter(n) = 0;
}
struct FilterSettings
{
/**
Input buffer.
*/
Image<float32_t> in;
/**
FFT buffer.
*/
Image<complex32_t> out;
/**
Filter that is to be applied.
Currently this is created separately for each thread but the data is the same for all of them.
*/
Image<float32_t> H;
/**
FFT plans.
*/
fftwf_plan forward;
fftwf_plan backward;
/**
Amount of padding on each size of the buffers in pixels.
*/
coord_t mirrorSize;
FilterSettings(float32_t padFraction, coord_t projectionWidth, FilterType filterType, float32_t cutoff)
{
clamp(padFraction, 0.0f, 1.0f);
mirrorSize = (coord_t)round(padFraction * projectionWidth);
if (mirrorSize < 10)
mirrorSize = 10;
size_t paddedWidth = mirrorSize + projectionWidth + mirrorSize;
in.ensureSize(paddedWidth);
// Build filter
size_t outSize = paddedWidth / 2 + 1;
out.ensureSize(outSize);
H.ensureSize(outSize);
createFilter(H, filterType, cutoff);
#pragma omp critical
{
forward = fftwf_plan_dft_r2c_1d((int)paddedWidth, in.getData(), (fftwf_complex*)out.getData(), FFTW_ESTIMATE);
backward = fftwf_plan_dft_c2r_1d((int)paddedWidth, (fftwf_complex*)out.getData(), in.getData(), FFTW_ESTIMATE);
}
}
~FilterSettings()
{
#pragma omp critical
{
fftwf_destroy_plan(backward);
fftwf_destroy_plan(forward);
}
}
};
void filterSlice(Image<float32_t>& slice, FilterSettings& settings, PadType padType)
{
coord_t projectionWidth = slice.width();
for (coord_t z = 0; z < slice.height(); z++)
{
// Copy data to input buffer
for (coord_t x = 0; x < settings.mirrorSize; x++)
{
if (padType == PadType::Mirror)
settings.in(settings.mirrorSize - x - 1) = slice(x, z);
else if (padType == PadType::Nearest)
settings.in(settings.mirrorSize - x - 1) = slice(0, z);
else
throw runtime_error("Pad type not supported.");
}
for (coord_t x = 0; x < projectionWidth; x++)
{
settings.in(settings.mirrorSize + x) = slice(x, z);
}
for (coord_t x = 0; x < settings.mirrorSize; x++)
{
if (padType == PadType::Mirror)
settings.in(settings.mirrorSize + projectionWidth + x) = slice(projectionWidth - x - 1, z);
else if (padType == PadType::Nearest)
settings.in(settings.mirrorSize + projectionWidth + x) = slice(projectionWidth - 1, z);
else
throw runtime_error("Pad type not supported.");
}
// Transform
// NOTE: Output stores only non-negative frequencies!
fftwf_execute(settings.forward);
// Apply filter
for (coord_t x = 0; x < settings.out.width(); x++)
settings.out(x) *= settings.H(x);
// Inverse transform
fftwf_execute(settings.backward);
// Normalize and copy to output
for (coord_t x = 0; x < projectionWidth; x++)
{
slice(x, z) = settings.in(settings.mirrorSize + x) / settings.in.width();
}
}
}
/**
Performs sinogram filtering.
*/
void fbpFilter(Image<float32_t>& transmissionProjections, PadType padType, float32_t padFraction, FilterType filterType, float32_t cutoff)
{
initFFTW();
#pragma omp parallel
{
FilterSettings settings(padFraction, transmissionProjections.width(), filterType, cutoff);
#pragma omp for
for (coord_t anglei = 0; anglei < transmissionProjections.depth(); anglei++)
{
Image<float32_t> slice(transmissionProjections, anglei, anglei);
filterSlice(slice, settings, padType);
}
}
}
/**
Remove bad pixels from one slice of projection data.
@param slice View of the slice.
@param med, tmp Temporary images.
@return Count of bad pixels in the slice.
*/
size_t deadPixelRemovalSlice(Image<float32_t>& slice, Image<float32_t>& med, Image<float32_t>& tmp, coord_t medianRadius = 2, float32_t stdDevCount = 30)
{
// Calculate median filtering of slice
nanMedianFilter(slice, med, medianRadius, NeighbourhoodType::Rectangular, BoundaryCondition::Nearest);
// Calculate abs(slice - median)
setValue(tmp, slice);
subtract(tmp, med);
abs(tmp);
// Calculate its mean and standard deviation
Vec2d v = maskedMeanAndStdDev(tmp, numeric_limits<float32_t>::signaling_NaN());
//float32_t meandifference = (float32_t)v.x;
float32_t stddifference = (float32_t)v.y;
// Perform filtering
size_t badPixelCount = 0;
for (coord_t y = 0; y < slice.height(); y++)
{
for (coord_t x = 0; x < slice.width(); x++)
{
float32_t p = slice(x, y);
float32_t m = med(x, y);
if (NumberUtils<float32_t>::isnan(p) || abs(m - p) > stdDevCount * stddifference)
{
slice(x, y) = m;
badPixelCount++;
}
}
}
return badPixelCount;
}
void printBadPixelInfo(float averageBadPixels, size_t maxBadPixels)
{
cout << "Average number of bad pixels per slice: " << averageBadPixels << endl;
cout << "Maximum number of bad pixels in slice: " << maxBadPixels << endl;
if (maxBadPixels > 100)
cout << "WARNING: Maximum number of bad pixels is high: " << maxBadPixels << ". Consider changing settings for bad pixel removal." << endl;
}
/**
Removes dead pixels from each slice of the input image.
*/
void deadPixelRemoval(Image<float32_t>& img, coord_t medianRadius = 1, float32_t stdDevCount = 30)
{
if (medianRadius <= 0)
throw ITLException("Invalid median radius.");
if (stdDevCount <= 0)
throw ITLException("Invalid standard deviation count.");
float32_t averageBadPixels = 0;
size_t maxBadPixels = 0;
size_t counter = 0;
#pragma omp parallel
{
Image<float32_t> med(img.width(), img.height());
Image<float32_t> tmp(img.width(), img.height());
#pragma omp for
for (coord_t n = 0; n < img.depth(); n++)
{
Image<float32_t> slice(img, n, n);
size_t badPixelCount = deadPixelRemovalSlice(img, med, tmp, medianRadius, stdDevCount);
#pragma omp critical(badpixels)
{
averageBadPixels += badPixelCount;
maxBadPixels = std::max(maxBadPixels, badPixelCount);
}
showThreadProgress(counter, img.depth());
}
}
printBadPixelInfo(averageBadPixels / (float)img.depth(), maxBadPixels);
}
namespace internals
{