-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimgProcess.cpp
1734 lines (1443 loc) · 74.5 KB
/
imgProcess.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 <vector>
#include <string>
#include <math.h>
#include <yaml-cpp/yaml.h>
#include <itkImage.h>
#include <itkImageFileReader.h>
#include <itkImageFileWriter.h>
#include <itkBSplineInterpolateImageFunction.h>
#include "itkMeanImageFilter.h"
#include "itkLinearInterpolateImageFunction.h"
#include <itkFlipImageFilter.h>
#include <itkRescaleIntensityImageFilter.h>
#include <itkSubtractImageFilter.h>
#include <itkCastImageFilter.h>
#include <itkDiscreteGaussianImageFilter.h>
#include "itkDivideImageFilter.h"
#include "itkAddImageFilter.h"
#include "itkImageRegionIteratorWithIndex.h"
#include <itkExtractImageFilter.h>
#include <itkImageDuplicator.h>
#include "itkImageRegionIterator.h"
#include "itkImage.h"
#include "itkNeighborhoodIterator.h"
#include "itkStatisticsImageFilter.h"
#include <itkBoxImageFilter.h>
#include <rtkThreeDCircularProjectionGeometry.h>
#include "rtkThreeDCircularProjectionGeometryXMLFile.h"
#include <itkMultiplyImageFilter.h>
// Define the image types
typedef itk::Image<float, 3> ImageType; // Assuming images are 3D and of type float
typedef itk::Image<float, 2> ImageType2D;
typedef itk::Image<float, 1> ImageType1D;
typedef itk::ImageFileWriter<ImageType> WriterType;
int GetImageDimension(const std::string &filename)
{
// Create a GenericImageIO object that can handle any type of image
itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO(
filename.c_str(), itk::ImageIOFactory::ReadMode);
if (!imageIO)
{
std::cerr << "Could not CreateImageIO for: " << filename << std::endl;
return -1;
}
// Use the object to read the image file and get its meta-data information
imageIO->SetFileName(filename);
imageIO->ReadImageInformation();
// Return the dimension of the image
return imageIO->GetNumberOfDimensions();
}
void PrintImageDimensions(ImageType::Pointer image)
{
// Print size, spacing, origin
typename ImageType::SizeType imgSize = image->GetLargestPossibleRegion().GetSize();
const typename ImageType::SpacingType &imgSpacing = image->GetSpacing();
const typename ImageType::PointType &imgOrigin = image->GetOrigin();
std::cout << "Image Size: " << imgSize[0] << ", " << imgSize[1] << ", " << imgSize[2] << "." << std::endl;
std::cout << "Image Spacing: " << imgSpacing[0] << ", " << imgSpacing[1] << ", " << imgSpacing[2] << "." << std::endl;
std::cout << "Image Origin: " << imgOrigin[0] << ", " << imgOrigin[1] << ", " << imgOrigin[2] << "." << std::endl;
}
ImageType::Pointer ReadMHA(const std::string &filename)
{
// Define the image type and create a reader
// using ImageType = itk::Image<float, 3>;
using ReaderType = itk::ImageFileReader<ImageType>;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(filename);
reader->Update();
ImageType::Pointer image = reader->GetOutput();
return image;
}
void SetImageDimensions(ImageType::Pointer image, int sizeX, int sizeY, int nProjections, float PixelPitch)
{
ImageType::SizeType size;
size[0] = sizeX;
size[1] = sizeY;
size[2] = nProjections;
ImageType::SpacingType spacing;
spacing[0] = PixelPitch;
spacing[1] = PixelPitch;
spacing[2] = 1;
ImageType::PointType origin;
origin[0] = -((size[0] * PixelPitch / 2) - (spacing[0] / 2));
origin[1] = -((size[1] * PixelPitch / 2) - (spacing[1] / 2));
origin[2] = 1;
image->SetRegions(size);
image->SetSpacing(spacing);
image->SetOrigin(origin);
}
typedef itk::DiscreteGaussianImageFilter<ImageType, ImageType> GaussFilterType;
void LateralSmoothing(ImageType::Pointer &scatterEstimate, double variance)
{
GaussFilterType::Pointer filter = GaussFilterType::New();
filter->SetInput(scatterEstimate);
GaussFilterType::ArrayType varianceArray;
varianceArray[0] = variance; // x-direction variance
varianceArray[1] = variance; // y-direction variance
varianceArray[2] = 0; // z-direction variance (no smoothing)
filter->SetVariance(varianceArray);
try
{
filter->Update();
}
catch (itk::ExceptionObject &error)
{
std::cerr << "Error: " << error << std::endl;
return;
}
typedef itk::ImageDuplicator<ImageType> DuplicatorType;
DuplicatorType::Pointer duplicator = DuplicatorType::New();
duplicator->SetInputImage(filter->GetOutput());
duplicator->Update();
scatterEstimate = duplicator->GetOutput();
}
// AddImages: adds the two images pixelwise
ImageType::Pointer AddImages(ImageType::Pointer image1, ImageType::Pointer image2)
{
// Check if dimensions are the same
if (image1->GetLargestPossibleRegion().GetSize() != image2->GetLargestPossibleRegion().GetSize())
{
throw std::runtime_error("Images do not have the same dimensions.");
}
typedef itk::AddImageFilter<ImageType> AddImageFilterType;
AddImageFilterType::Pointer addFilter = AddImageFilterType::New();
addFilter->SetInput1(image1);
addFilter->SetInput2(image2);
addFilter->Update();
ImageType::Pointer outputImage = addFilter->GetOutput();
outputImage->SetSpacing(image1->GetSpacing());
outputImage->SetOrigin(image1->GetOrigin());
outputImage->SetDirection(image1->GetDirection());
return outputImage;
}
ImageType::Pointer AddMultipleImages(const std::vector<std::string> &filePaths)
{
ImageType::Pointer currentImage = ReadMHA(filePaths[0]);
if (filePaths.size() < 2)
{
std::cout << ("At least two image files are required to add. Returning the provided single image.") << std::endl;
return currentImage;
}
for (size_t i = 1; i < filePaths.size(); ++i)
{
ImageType::Pointer nextImage = ReadMHA(filePaths[i]);
currentImage = AddImages(currentImage, nextImage);
}
return currentImage;
}
// Causal recursive filter
void CausalRecursiveFilter(ImageType::Pointer inputImage, float theta)
{
typedef itk::ImageRegionIterator<ImageType> IteratorType;
itk::Size<3> size = inputImage->GetLargestPossibleRegion().GetSize();
for (unsigned int x = 0; x < size[0]; ++x)
{
for (unsigned int y = 0; y < size[1]; ++y)
{
double previousValue = 0.0;
for (unsigned int z = 0; z < size[2]; ++z)
{
ImageType::IndexType index = {x, y, z};
double currentValue = inputImage->GetPixel(index);
double outputValue = theta * currentValue + (1 - theta) * previousValue;
inputImage->SetPixel(index, outputValue);
previousValue = outputValue;
}
}
}
}
// Non-causal, forward-backward filter
ImageType::Pointer NonCausalFilter(ImageType::Pointer inputImage, int kernelWidth)
{
typedef itk::BoxImageFilter<ImageType, ImageType> MeanFilterType;
MeanFilterType::Pointer meanFilter = MeanFilterType::New();
MeanFilterType::SizeType radius;
radius.Fill(0);
radius[2] = kernelWidth / 2; // Kernel width in z-direction
meanFilter->SetRadius(radius);
meanFilter->SetInput(inputImage);
meanFilter->Update();
return meanFilter->GetOutput();
}
double calculateSNR(itk::Image<float, 3>::Pointer image3D, itk::ImageRegion<3> noiseRegion, unsigned int slice)
{
typedef itk::Image<float, 2> ImageType2D;
ImageType2D::Pointer image2D = ImageType2D::New();
ImageType2D::RegionType region2D;
ImageType2D::IndexType start;
ImageType2D::SizeType size;
start[0] = noiseRegion.GetIndex()[0];
start[1] = noiseRegion.GetIndex()[1];
size[0] = noiseRegion.GetSize()[0];
size[1] = noiseRegion.GetSize()[1];
region2D.SetSize(size);
region2D.SetIndex(start);
image2D->SetRegions(region2D);
image2D->Allocate();
typedef itk::ImageRegionIterator<ImageType2D> IteratorType2D;
IteratorType2D it2D(image2D, image2D->GetRequestedRegion());
itk::Image<float, 3>::IndexType start3D = noiseRegion.GetIndex();
start3D[2] = slice;
itk::Image<float, 3>::SizeType size3D = noiseRegion.GetSize();
size3D[2] = 0;
itk::Image<float, 3>::RegionType desiredRegion(start3D, size3D);
typedef itk::ImageRegionConstIterator<itk::Image<float, 3>> IteratorType3D;
IteratorType3D it3D(image3D, desiredRegion);
for (it3D.GoToBegin(), it2D.GoToBegin(); !it3D.IsAtEnd(); ++it3D, ++it2D)
{
it2D.Set(it3D.Get());
}
double noiseMean = 0.0;
double noiseStdDev = 0.0;
unsigned int noiseCount = 0;
// Calculate mean of noise region
for (it2D.GoToBegin(); !it2D.IsAtEnd(); ++it2D)
{
noiseMean += it2D.Get();
++noiseCount;
}
noiseMean /= noiseCount;
// Calculate standard deviation of noise region
for (it2D.GoToBegin(); !it2D.IsAtEnd(); ++it2D)
{
double val = it2D.Get() - noiseMean;
noiseStdDev += val * val;
}
noiseStdDev = std::sqrt(noiseStdDev / (noiseCount - 1));
return noiseMean / noiseStdDev; // Return SNR
}
ImageType2D::Pointer calculateLocalSNR(ImageType::Pointer image3D, int sliceIndex)
{
// Define a filter to extract the 2D slice
typedef itk::ExtractImageFilter<ImageType, ImageType2D> FilterType;
FilterType::Pointer filter = FilterType::New();
ImageType::RegionType inputRegion = image3D->GetLargestPossibleRegion();
ImageType::SizeType size = inputRegion.GetSize();
size[2] = 0;
ImageType::IndexType start = inputRegion.GetIndex();
start[2] = sliceIndex;
ImageType::RegionType desiredRegion;
desiredRegion.SetSize(size);
desiredRegion.SetIndex(start);
filter->SetExtractionRegion(desiredRegion);
filter->SetInput(image3D);
// Set the direction collapse strategy
filter->SetDirectionCollapseToSubmatrix(); // or filter->SetDirectionCollapseToIdentity();
filter->Update();
ImageType2D::Pointer image2D = filter->GetOutput();
// Create a new 2D image to store the local SNR values
ImageType2D::Pointer snrImage = ImageType2D::New();
snrImage->SetRegions(image2D->GetLargestPossibleRegion());
snrImage->SetSpacing(image2D->GetSpacing());
snrImage->SetOrigin(image2D->GetOrigin());
snrImage->SetDirection(image2D->GetDirection());
snrImage->Allocate();
// Create 3x3 neighborhood iterator for the original image
itk::Size<2> radius;
radius.Fill(1);
itk::NeighborhoodIterator<ImageType2D> nit(radius, image2D, image2D->GetLargestPossibleRegion());
// Create an iterator for the new SNR image
itk::ImageRegionIterator<ImageType2D> sit(snrImage, snrImage->GetLargestPossibleRegion());
// Calculate local SNR
for (nit.GoToBegin(), sit.GoToBegin(); !nit.IsAtEnd() && !sit.IsAtEnd(); ++nit, ++sit)
{
float sum = 0.0;
float sumSq = 0.0;
for (unsigned int i = 0; i < nit.Size(); ++i)
{
float val = nit.GetPixel(i);
sum += val;
sumSq += val * val;
}
float mean = sum / nit.Size();
float variance = (sumSq - sum * mean) / (nit.Size() - 1);
float stddev = std::sqrt(variance);
float localSNR = (stddev != 0.0) ? (mean / stddev) : 0.0;
sit.Set(localSNR);
}
return snrImage;
}
double calculateCNR(ImageType::Pointer image,
ImageType::RegionType signalRegion1, ImageType::RegionType signalRegion2,
ImageType::RegionType noiseRegion)
{
// Create iterators for the signal and noise regions
itk::ImageRegionIterator<ImageType> signalIterator1(image, signalRegion1);
itk::ImageRegionIterator<ImageType> signalIterator2(image, signalRegion2);
itk::ImageRegionIterator<ImageType> noiseIterator(image, noiseRegion);
double signalMean1 = 0.0;
double signalMean2 = 0.0;
double noiseStdDev = 0.0;
unsigned int signalCount1 = 0;
unsigned int signalCount2 = 0;
unsigned int noiseCount = 0;
// Calculate mean of signal regions
for (signalIterator1.GoToBegin(); !signalIterator1.IsAtEnd(); ++signalIterator1)
{
signalMean1 += signalIterator1.Get();
++signalCount1;
}
signalMean1 /= signalCount1;
for (signalIterator2.GoToBegin(); !signalIterator2.IsAtEnd(); ++signalIterator2)
{
signalMean2 += signalIterator2.Get();
++signalCount2;
}
signalMean2 /= signalCount2;
// Calculate standard deviation of noise region
for (noiseIterator.GoToBegin(); !noiseIterator.IsAtEnd(); ++noiseIterator)
{
double val = noiseIterator.Get() - ((signalMean1 + signalMean2) / 2);
noiseStdDev += val * val;
++noiseCount;
}
noiseStdDev = std::sqrt(noiseStdDev / (noiseCount - 1));
return std::abs(signalMean1 - signalMean2) / noiseStdDev; // Return CNR
}
double calculateNoise(ImageType::Pointer image, ImageType::RegionType noiseRegion)
{
itk::ImageRegionIterator<ImageType> noiseIterator(image, noiseRegion);
double noiseMean = 0.0;
double noiseStdDev = 0.0;
unsigned int noiseCount = 0;
// Calculate mean of noise region
for (noiseIterator.GoToBegin(); !noiseIterator.IsAtEnd(); ++noiseIterator)
{
noiseMean += noiseIterator.Get();
++noiseCount;
}
noiseMean /= noiseCount;
// Calculate standard deviation of noise region
for (noiseIterator.GoToBegin(); !noiseIterator.IsAtEnd(); ++noiseIterator)
{
double val = noiseIterator.Get() - noiseMean;
noiseStdDev += val * val;
}
noiseStdDev = std::sqrt(noiseStdDev / (noiseCount - 1));
return noiseStdDev; // Return standard deviation as a measure of noise
}
double CalculateMean(itk::Image<float, 3>::Pointer image)
{
using ImageType = itk::Image<float, 3>;
using StatisticsImageFilterType = itk::StatisticsImageFilter<ImageType>;
StatisticsImageFilterType::Pointer statsFilter = StatisticsImageFilterType::New();
statsFilter->SetInput(image);
statsFilter->Update();
return statsFilter->GetMean();
}
double CalculateStandardDeviation(itk::Image<float, 3>::Pointer image)
{
using ImageType = itk::Image<float, 3>;
using StatisticsImageFilterType = itk::StatisticsImageFilter<ImageType>;
StatisticsImageFilterType::Pointer statsFilter = StatisticsImageFilterType::New();
statsFilter->SetInput(image);
statsFilter->Update();
return statsFilter->GetSigma();
}
ImageType::Pointer ConcatenateImages(ImageType::Pointer image1, ImageType::Pointer image2, ImageType::SizeType concatSize)
{
ImageType::RegionType region1 = image1->GetLargestPossibleRegion();
ImageType::RegionType region2 = image2->GetLargestPossibleRegion();
ImageType::SizeType size1 = region1.GetSize();
ImageType::SizeType size2 = region2.GetSize();
long totalNumberOfPixels1 = size1[0] * size1[1] * size1[2];
long totalNumberOfPixels2 = size2[0] * size2[1] * size2[2];
std::vector<float> concatVector;
std::vector<float> pixelValues1(image1->GetBufferPointer(), image1->GetBufferPointer() + totalNumberOfPixels1);
std::vector<float> pixelValues2(image2->GetBufferPointer(), image2->GetBufferPointer() + totalNumberOfPixels2);
concatVector.insert(concatVector.end(), pixelValues1.begin(), pixelValues1.end());
concatVector.insert(concatVector.end(), pixelValues2.begin(), pixelValues2.end());
// Create an image.
ImageType::Pointer concatImage = ImageType::New();
// Define the region.
ImageType::RegionType region;
region.SetSize(concatSize);
// Set the region and allocate memory for the image.
concatImage->SetRegions(region);
concatImage->Allocate();
// Copy the data from the vector to the image.
std::copy(concatVector.begin(), concatVector.end(), concatImage->GetBufferPointer());
return concatImage;
}
ImageType::Pointer ConcatenateMultipleImages(std::vector<std::string> filenames)
{
// Assume that the images have the same size.
ImageType::Pointer image1 = ReadMHA(filenames[0]);
ImageType::SizeType concatSize = image1->GetLargestPossibleRegion().GetSize();
// Keep track of the current concatenated image.
ImageType::Pointer currentImage = image1;
for (int i = 1; i < filenames.size(); i++)
{
// Read the next image.
ImageType::Pointer image2 = ReadMHA(filenames[i]);
// Concatenate the current image with the next image.
ImageType::SizeType newSize;
newSize[0] = concatSize[0];
newSize[1] = concatSize[1];
newSize[2] = concatSize[2] + image2->GetLargestPossibleRegion().GetSize()[2];
currentImage = ConcatenateImages(currentImage, image2, newSize);
// Update the size for the next concatenation.
concatSize = newSize;
}
return currentImage;
}
using BSplineInterpolatorType = itk::BSplineInterpolateImageFunction<ImageType1D>;
using LinearInterpolatorType = itk::LinearInterpolateImageFunction<ImageType1D>;
// Function to interpolate a 1D image at a specified position
float interpolate1D(ImageType1D::Pointer image, ImageType1D::IndexType idx, int interpolationOrder)
{
if (interpolationOrder == 1)
{
LinearInterpolatorType::Pointer interpolator = LinearInterpolatorType::New();
interpolator->SetInputImage(image);
return interpolator->EvaluateAtIndex(idx);
}
else
{
BSplineInterpolatorType::Pointer interpolator = BSplineInterpolatorType::New();
interpolator->SetSplineOrder(interpolationOrder);
interpolator->SetInputImage(image);
return interpolator->EvaluateAtIndex(idx);
}
}
bool ConvertMHAtoNRRD(const std::string &inputFileName)
{
std::string outputFileName = inputFileName;
size_t lastdot = outputFileName.find_last_of(".");
if (lastdot != std::string::npos)
outputFileName = outputFileName.substr(0, lastdot) + ".nrrd";
using ReaderType = itk::ImageFileReader<ImageType>;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(inputFileName);
using WriterType = itk::ImageFileWriter<ImageType>;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName(outputFileName);
writer->SetInput(reader->GetOutput());
try
{
writer->Update();
}
catch (const itk::ExceptionObject &error)
{
std::cerr << "Error converting file: " << error << std::endl;
return false;
}
return true;
}
ImageType::Pointer ExtractFirstNSlices(const ImageType::Pointer &inputImage, unsigned int numberOfSlices)
{
// Define the region to extract
ImageType::RegionType inputRegion = inputImage->GetLargestPossibleRegion();
ImageType::SizeType size = inputRegion.GetSize();
size[2] = numberOfSlices; // Set the size in the z direction to the desired number of slices
ImageType::IndexType start = inputRegion.GetIndex();
start[2] = 0; // Start from the first slice
// Define the desired region
ImageType::RegionType desiredRegion;
desiredRegion.SetSize(size);
desiredRegion.SetIndex(start);
// Set up the extraction filter
typedef itk::ExtractImageFilter<ImageType, ImageType> FilterType;
typename FilterType::Pointer filter = FilterType::New();
filter->SetExtractionRegion(desiredRegion);
#if ITK_VERSION_MAJOR >= 4
filter->SetDirectionCollapseToIdentity(); // This line is only needed for ITK >= 4
#endif
filter->SetInput(inputImage);
// Apply the filter
filter->Update();
// The result is a new image with only the first numberOfSlices slices
return filter->GetOutput();
}
/**
* @brief Estimates unknown values in a dataset using polynomial interpolation.
*
* This function takes a vector of values and a vector of indices that indicate which values are unknown
* and need to be estimated. The known values are used to construct a Vandermonde matrix for a least squares
* fitting of a polynomial of a specified order. The polynomial is then used to estimate the unknown values.
*
* @param values A std::vector<float> containing the known and placeholder values for the unknowns in the dataset.
* @param unknownIndices A std::vector<int> containing the indices in the 'values' vector that need to be estimated.
* @param order The order of the polynomial to be fitted to the known values.
* @return A std::vector<float> containing the original known values and the newly estimated values for the unknowns.
*
* @note This function uses the Eigen library to solve the least squares problem and compute the polynomial coefficients.
* It assumes that 'values' contains at least 'order + 1' known values to construct a solvable system.
* The 'unknownIndices' should be within the range of 'values' vector indices.
*/
std::vector<float> estimateUnknownValues(const std::vector<float> &values, const std::vector<int> &unknownIndices, int order)
{
// Collect known data
std::vector<float> knownValues;
std::vector<int> knownIndices;
for (int i = 0; i < values.size(); ++i)
{
if (std::find(unknownIndices.begin(), unknownIndices.end(), i) == unknownIndices.end())
{
knownValues.push_back(values[i]);
knownIndices.push_back(i);
}
}
// Build the Vandermonde matrix
Eigen::MatrixXf X(knownIndices.size(), order + 1);
for (int i = 0; i < knownIndices.size(); ++i)
{
for (int j = 0; j <= order; ++j)
{
X(i, j) = std::pow(knownIndices[i], j);
}
}
// Build the y vector
Eigen::VectorXf y(knownValues.size());
for (int i = 0; i < knownValues.size(); ++i)
{
y[i] = knownValues[i];
}
// Solve for the polynomial coefficients
Eigen::VectorXf coeffs = X.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(y);
// Estimate the unknown values
std::vector<float> estimatedValues = values;
for (int i : unknownIndices)
{
float estimate = 0.0f;
for (int j = 0; j <= order; ++j)
{
estimate += coeffs[j] * std::pow(i, j);
}
estimatedValues[i] = estimate;
}
return estimatedValues;
}
using IndexType = ImageType::IndexType;
// Function to process each row of the 3D input image within the ROI
void estimateUnknownRows(ImageType::Pointer inputImage, ImageType::Pointer maskImage, int fitOrder)
{
ImageType::RegionType region = inputImage->GetLargestPossibleRegion();
ImageType::SizeType size = region.GetSize();
// Iterators for input and mask images
itk::ImageRegionIteratorWithIndex<ImageType> inputIt(inputImage, region);
itk::ImageRegionIteratorWithIndex<ImageType> maskIt(maskImage, region);
// Iterate over each slice (z-direction)
for (unsigned int z = 0; z < size[2]; ++z)
{
// Iterate over each row (y-direction)
for (unsigned int y = 0; y < size[1]; ++y)
{
std::vector<float> rowValues;
std::vector<int> unknownIndices;
// Collect row values and determine unknown indices based on the mask
for (unsigned int x = 0; x < size[0]; ++x)
{
ImageType::IndexType idx = {{x, y, z}};
inputIt.SetIndex(idx);
maskIt.SetIndex(idx);
rowValues.push_back(inputIt.Get());
if (maskIt.Get() == 1)
{ // If the mask indicates an unknown value
unknownIndices.push_back(x);
}
}
// Estimate the unknown values in the row
if (!unknownIndices.empty())
{
std::vector<float> estimatedRow = estimateUnknownValues(rowValues, unknownIndices, fitOrder);
// Write the estimated values back to the input image
for (int i : unknownIndices)
{
ImageType::IndexType idx = {{static_cast<unsigned int>(i), y, z}};
inputImage->SetPixel(idx, estimatedRow[i]);
}
}
}
}
}
// Function to process each column of the 3D input image within the ROI
void estimateUnknownColumns(ImageType::Pointer inputImage, ImageType::Pointer maskImage, int fitOrder)
{
ImageType::RegionType region = inputImage->GetLargestPossibleRegion();
ImageType::SizeType size = region.GetSize();
// Iterators for input and mask images
itk::ImageRegionIteratorWithIndex<ImageType> inputIt(inputImage, region);
itk::ImageRegionIteratorWithIndex<ImageType> maskIt(maskImage, region);
// Iterate over each slice (z-direction)
for (unsigned int z = 0; z < size[2]; ++z)
{
// Iterate over each column (x-direction)
for (unsigned int x = 0; x < size[0]; ++x)
{
std::vector<float> columnValues;
std::vector<int> unknownIndices;
// Collect column values and determine unknown indices based on the mask
for (unsigned int y = 0; y < size[1]; ++y)
{
ImageType::IndexType idx = {{x, y, z}};
inputIt.SetIndex(idx);
maskIt.SetIndex(idx);
columnValues.push_back(inputIt.Get());
if (maskIt.Get() == 1)
{ // If the mask indicates an unknown value
unknownIndices.push_back(y);
}
}
// Estimate the unknown values in the column
if (!unknownIndices.empty())
{
std::vector<float> estimatedColumn = estimateUnknownValues(columnValues, unknownIndices, fitOrder);
// Write the estimated values back to the input image
for (int i : unknownIndices)
{
ImageType::IndexType idx = {{x, static_cast<unsigned int>(i), z}};
inputImage->SetPixel(idx, estimatedColumn[i]);
}
}
}
}
}
// Function to add and average two images
ImageType::Pointer addAndAverage(ImageType::Pointer image1, ImageType::Pointer image2)
{
typedef itk::AddImageFilter<ImageType> AddImageFilterType;
typedef itk::DivideImageFilter<ImageType, ImageType, ImageType> DivideImageFilterType;
// Add the two images
AddImageFilterType::Pointer addFilter = AddImageFilterType::New();
addFilter->SetInput1(image1);
addFilter->SetInput2(image2);
addFilter->Update();
// Divide the result by 2 to average
DivideImageFilterType::Pointer divideFilter = DivideImageFilterType::New();
divideFilter->SetInput(addFilter->GetOutput());
divideFilter->SetConstant(2.0);
divideFilter->Update();
// Disconnect from the pipeline
ImageType::Pointer resultImage = divideFilter->GetOutput();
resultImage->DisconnectPipeline();
return resultImage;
}
void estimateROI(ImageType::Pointer inputImage, ImageType::Pointer maskImage, int fitOrder)
{
typedef itk::ImageDuplicator<ImageType> DuplicatorType;
// Duplicate inputImage for row-wise estimation
DuplicatorType::Pointer rowDuplicator = DuplicatorType::New();
rowDuplicator->SetInputImage(inputImage);
rowDuplicator->Update();
ImageType::Pointer rowEstimate = rowDuplicator->GetOutput();
rowEstimate->DisconnectPipeline(); // Disconnect to ensure independent manipulation
estimateUnknownRows(rowEstimate, maskImage, fitOrder);
// Duplicate inputImage for column-wise estimation
DuplicatorType::Pointer colDuplicator = DuplicatorType::New();
colDuplicator->SetInputImage(inputImage);
colDuplicator->Update();
ImageType::Pointer colEstimate = colDuplicator->GetOutput();
colEstimate->DisconnectPipeline(); // Disconnect to ensure independent manipulation
estimateUnknownColumns(colEstimate, maskImage, fitOrder);
// Add and average row and column estimates
ImageType::Pointer finalEstimate = addAndAverage(rowEstimate, colEstimate);
// Update inputImage with the final estimate within the ROI
itk::ImageRegionIteratorWithIndex<ImageType> inputIt(inputImage, inputImage->GetLargestPossibleRegion());
itk::ImageRegionIteratorWithIndex<ImageType> finalIt(finalEstimate, finalEstimate->GetLargestPossibleRegion());
itk::ImageRegionIteratorWithIndex<ImageType> maskIt(maskImage, maskImage->GetLargestPossibleRegion());
for (inputIt.GoToBegin(), finalIt.GoToBegin(), maskIt.GoToBegin(); !inputIt.IsAtEnd(); ++inputIt, ++finalIt, ++maskIt)
{
if (maskIt.Get() == 1)
{ // Only update pixels within the ROI
inputIt.Set(finalIt.Get());
}
}
}
// Define a struct to hold the collimator data
struct CollimatorOpening // Not the same collimator object "CollimatorInfo" being used for the simulation
{
float x, y, width, height;
};
// Assuming definitions for CollimatorOpening, Detector, and CTGeometry are provided as before
ImageType::Pointer CreateCollimatorMask(
const std::vector<CollimatorOpening> &collimatorOpenings, int pixelsX, int pixelsY,
float SDD, float SCD, float sourceX, float sourceY, float detectorPixelPitch)
{
// Create a 3D ITK image
ImageType::Pointer maskImage = ImageType::New();
// Defining the size of the 3D image
ImageType::SizeType size;
size[0] = pixelsX; // size along X
size[1] = pixelsY; // size along Y
size[2] = collimatorOpenings.size(); // size along Z
std::cout << "Dimension of Collimator Mask: " << size[0] << ", " << size[1] << ", " << size[2] << "." << std::endl;
// Setting the regions of the image
ImageType::RegionType region;
region.SetSize(size);
// Allocating memory for the image
maskImage->SetRegions(region);
maskImage->Allocate();
maskImage->FillBuffer(0); // Initializing with zeros
// For each collimator opening, projecting to detector and create a slice
for (int z = 0; z < collimatorOpenings.size(); ++z)
{
const auto &opening = collimatorOpenings[z];
// Projecting the collimator corners onto the detector plane
float collimatorDistanceRatio = SDD / SCD;
float projectedWidth = opening.width * collimatorDistanceRatio;
float projectedHeight = opening.height * collimatorDistanceRatio;
float projectedX = sourceX + (opening.x - sourceX) * collimatorDistanceRatio;
float projectedY = sourceY + (opening.y - sourceY) * collimatorDistanceRatio;
// Defining the projected collimator corners on the detector
float cut = 12;
float startX = ((pixelsX * detectorPixelPitch) / 2.0) + projectedX + cut;
float endX = startX + projectedWidth - cut * 2;
float startY = ((pixelsY * detectorPixelPitch) / 2.0) - projectedY + cut;
float endY = startY + projectedHeight - cut * 2;
// Iterate through the pixels of the detector
for (int y = 0; y < pixelsY; ++y)
{
for (int x = 0; x < pixelsX; ++x)
{
float pixelCenterX = (x + 0.5) * detectorPixelPitch;
float pixelCenterY = (y + 0.5) * detectorPixelPitch;
if (pixelCenterX >= startX && pixelCenterX <= endX &&
pixelCenterY >= startY && pixelCenterY <= endY)
{
ImageType::IndexType pixelIndex = {{x, y, z}};
maskImage->SetPixel(pixelIndex, 1);
}
}
}
}
return maskImage;
}
ImageType::Pointer ApplyCollimatorMask(
const ImageType::Pointer collimatorMask,
const ImageType::Pointer inputImage)
{
// Check if the mask and the input image are of the same size
if (collimatorMask->GetLargestPossibleRegion().GetSize() !=
inputImage->GetLargestPossibleRegion().GetSize())
{
throw std::runtime_error("Collimator Mask and the Input Image must be of the same size");
}
ImageType::Pointer outputImage = ImageType::New();
outputImage->SetRegions(inputImage->GetLargestPossibleRegion());
outputImage->Allocate();
outputImage->FillBuffer(0);
outputImage->SetSpacing(inputImage->GetSpacing());
outputImage->SetOrigin(inputImage->GetOrigin());
// Define iterators for the mask and the input image
itk::ImageRegionIterator<ImageType> maskIterator(collimatorMask, collimatorMask->GetLargestPossibleRegion());
itk::ImageRegionIterator<ImageType> inputIterator(inputImage, inputImage->GetLargestPossibleRegion());
itk::ImageRegionIterator<ImageType> outputIterator(outputImage, outputImage->GetLargestPossibleRegion());
// Iterate through the mask image
while (!maskIterator.IsAtEnd())
{
// Check the mask value
if (maskIterator.Get() == 1)
{
// If the mask value is 1, copy the input image value to the output image
outputIterator.Set(inputIterator.Get());
}
// Move to the next pixel in each image
++maskIterator;
++inputIterator;
++outputIterator;
}
return outputImage;
}
ImageType::Pointer ApplyMask(
const ImageType::Pointer collimatorMask,
const ImageType::Pointer boostedImage,
ImageType::Pointer unboostedImage)
{
// Check if all images are of the same size
if (collimatorMask->GetLargestPossibleRegion().GetSize() != boostedImage->GetLargestPossibleRegion().GetSize() ||
boostedImage->GetLargestPossibleRegion().GetSize() != unboostedImage->GetLargestPossibleRegion().GetSize())
{
throw std::runtime_error("Collimator Mask and Images must be of the same size");
}
// Get the ROI values
using SubtractFilterType = itk::SubtractImageFilter<ImageType>;
SubtractFilterType::Pointer subtractFilter = SubtractFilterType::New();
subtractFilter->SetInput1(boostedImage);
subtractFilter->SetInput2(unboostedImage);
subtractFilter->Update();
ImageType::Pointer output = subtractFilter->GetOutput(); // total - scatter = nonScatter = primary + tertiary
output->DisconnectPipeline();
output = ApplyCollimatorMask(collimatorMask, output);
// // For debug
// PrintImageDimensions(collimatorMask);
// PrintImageDimensions(output);
// PrintImageDimensions(unboostedImage);
// Just add the Roi Image and the Unboosted Image
typedef itk::AddImageFilter<ImageType> AddImageFilterType;
AddImageFilterType::Pointer addFilter = AddImageFilterType::New();
addFilter->SetInput1(output);
addFilter->SetInput2(unboostedImage);
addFilter->Update();
output = addFilter->GetOutput();
output->DisconnectPipeline();
return output;
}
ImageType::Pointer extractSlices(ImageType::Pointer image, const std::vector<int> &indices, const std::string outputFilepath)
{
// Get input image size and properties
ImageType::RegionType inputRegion = image->GetLargestPossibleRegion();
ImageType::SizeType inputSize = inputRegion.GetSize();
// Prepare the output image size and region
ImageType::SizeType outputSize = inputSize;
outputSize[2] = indices.size(); // Set the number of slices to the number of indices
ImageType::RegionType outputRegion;
outputRegion.SetSize(outputSize);
ImageType::Pointer outputImage = ImageType::New();
outputImage->SetRegions(outputRegion);
outputImage->Allocate();
outputImage->FillBuffer(0);
// Iterate over each index in indices to copy the slices
for (size_t i = 0; i < indices.size(); ++i)
{
if (indices[i] < 0 || indices[i] >= inputSize[2])
{
std::cout << "Invalid Index for extraction." << std::endl;
continue; // Skip invalid indices
}
// Define the region of the current slice
ImageType::IndexType start = {0, 0, indices[i]};
ImageType::RegionType desiredSlice;
ImageType::SizeType sliceSize = inputSize;
sliceSize[2] = 1; // Single slice
desiredSlice.SetSize(sliceSize);
desiredSlice.SetIndex(start);
// Extract the slice
itk::ImageRegionConstIterator<ImageType> inputIt(image, desiredSlice);