-
Notifications
You must be signed in to change notification settings - Fork 0
/
imageAndMask2Report.cxx
3350 lines (2920 loc) · 147 KB
/
imageAndMask2Report.cxx
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 "itkGDCMImageIO.h"
#include "itkGDCMSeriesFileNames.h"
#include "itkImageFileWriter.h"
#include "itkImageSeriesReader.h"
#include "itkMetaDataObject.h"
#include "itkBinaryBallStructuringElement.h"
#include "itkBinaryDilateImageFilter.h"
#include "itkBinaryErodeImageFilter.h"
#include "itkImageAdaptor.h"
#include "itkImageRegionConstIterator.h"
#include "itkImageRegionIterator.h"
#include "itkRGBPixel.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkScalarImageToHistogramGenerator.h"
#include "itkConnectedComponentImageFilter.h"
#include "itkLabelImageToShapeLabelMapFilter.h"
#include "itkLabelShapeKeepNObjectsImageFilter.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "gdcmAnonymizer.h"
#include "gdcmAttribute.h"
#include "gdcmDataSetHelper.h"
#include "gdcmDirectoryHelper.h"
#include "gdcmFileDerivation.h"
#include "gdcmFileExplicitFilter.h"
#include "gdcmGlobal.h"
#include "gdcmImageApplyLookupTable.h"
#include "gdcmImageChangePlanarConfiguration.h"
#include "gdcmImageChangeTransferSyntax.h"
#include "gdcmImageHelper.h"
#include "gdcmImageReader.h"
#include "gdcmImageWriter.h"
#include "gdcmMediaStorage.h"
#include "gdcmReader.h"
#include "gdcmRescaler.h"
#include "gdcmStringFilter.h"
#include "gdcmUIDGenerator.h"
#include "itkConstantPadImageFilter.h"
#include "itkShrinkImageFilter.h"
#include "itkAddImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkDenseFrequencyContainer2.h"
#include "itkHistogramToTextureFeaturesFilter.h"
#include "itkMultiplyImageFilter.h"
#include "itkRegionOfInterestImageFilter.h"
#include "itkScalarImageToCooccurrenceMatrixFilter.h"
#include "itkScalarImageToRunLengthMatrixFilter.h"
#include "itkContinuousIndex.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkGDCMImageIO.h"
#include "itkMetaDataDictionary.h"
#include "json.hpp"
#include "metaCommand.h"
#include <boost/algorithm/string.hpp>
#include <boost/date_time.hpp>
#include <boost/filesystem.hpp>
#include <boost/math/interpolators/catmull_rom.hpp>
#include <codecvt>
#include <locale> // wstring_convert
#include <map>
#include <zip.h>
#include "mytypes.h"
#include "report.h"
using json = nlohmann::json;
using namespace boost::filesystem;
json resultJSON;
bool verbose = false;
using ImageType2D = itk::Image<PixelType, 2>;
using MaskImageType2D = itk::Image<PixelType, 2>;
using CPixelType = itk::RGBPixel<unsigned char>;
using CImageType = itk::Image<CPixelType, 2>;
using LabelType = unsigned short;
using ShapeLabelObjectType = itk::ShapeLabelObject<LabelType, 3>;
using LabelMapType = itk::LabelMap<ShapeLabelObjectType>;
typedef itk::Image<PixelType, 3> ImageType3D;
struct generateImageReturn
{
CImageType::Pointer keyImage;
std::vector< std::array<int, 2> > pos;
std::vector< std::string > text;
std::vector<int> roi_order;
};
// generate a key image based on an input image mask and the ground truth image
// This key image generator shall generate a mosaic of images, one for each lesion.
generateImageReturn generateKeyImageMosaic(ImageType3D::Pointer image, LabelMapType *labelMap, std::vector<int> resolution, float lowerT, float upperT) {
if (verbose) {
fprintf(stdout, "Start generating a key image...\n");
}
std::vector<std::vector<float>> labelColors2 = {{0, 0, 0}, {166,206,227}, {31,120,180}, {178,223,138}, {51,160,44}, {251,154,153}, {227,26,28}, {253,191,111}, {255,127,0}, {202,178,214}, {106,61,154}, {255,255,153}, {177,89,40}};
generateImageReturn returns; // store keyImage and the location and text that should be presented ontop of the image
// based on the number of labels we will create an image mosaic (MPR for each region of interest)
int numObjects = labelMap->GetNumberOfLabelObjects();
if (numObjects < 1) {
fprintf(stderr, "Error: no object found, refuse to create a key image\n");
return(returns);
}
// lets use the base image resolution of
int base_image_sizeLW = 512; // we will put an axial square image next to coronal and sagittal on top of each other
int base_image_sizeLH = base_image_sizeLW;
int base_image_sizeRW = floor(base_image_sizeLW / 1.618);
int base_image_sizeRH = floor(base_image_sizeLH / 2.0);
// the total size of the image is now
resolution[0] = base_image_sizeLW + base_image_sizeRW;
resolution[1] = numObjects * base_image_sizeLH;
// create a new RGB image
CImageType::Pointer keyImage = CImageType::New();
returns.keyImage = keyImage;
using RegionType = itk::ImageRegion<2>;
RegionType::SizeType size;
size[0] = resolution[0]; // 512
size[1] = resolution[1]; // 512
RegionType::IndexType index;
index.Fill(0);
RegionType region(index, size);
keyImage->SetRegions(region);
keyImage->Allocate();
keyImage->FillBuffer(itk::NumericTraits<CPixelType>::Zero);
RegionType outputRegion = keyImage->GetLargestPossibleRegion();
//itk::ImageRegionIteratorWithIndex<CImageType> outputRGBIterator(keyImage, outputRegion);
//
// Compute the independently blurred channels for the fused image and all colors in 3D
//
//
// compute optimal window level for whole image, we will use the values for the curved slice
//
using ImageCalculatorFilterType = itk::MinimumMaximumImageCalculator<ImageType3D>;
ImageCalculatorFilterType::Pointer imageCalculatorFilter = ImageCalculatorFilterType::New();
imageCalculatorFilter->SetImage(image);
imageCalculatorFilter->Compute();
int minGray = imageCalculatorFilter->GetMinimum();
int maxGray = imageCalculatorFilter->GetMaximum();
using HistogramGeneratorType = itk::Statistics::ScalarImageToHistogramGenerator<ImageType3D>;
HistogramGeneratorType::Pointer histogramGenerator = HistogramGeneratorType::New();
histogramGenerator->SetInput(image);
int histogramSize = 1024;
histogramGenerator->SetNumberOfBins(histogramSize);
histogramGenerator->SetHistogramMin(minGray);
histogramGenerator->SetHistogramMax(maxGray);
histogramGenerator->Compute();
using HistogramType = HistogramGeneratorType::HistogramType;
const HistogramType *histogram = histogramGenerator->GetOutput();
// lowerT and upperT in percentages 0..1 are set in calling function
double t1 = -1;
double t2 = -1;
double sum = 0;
double total = 0;
for (unsigned int bin = 0; bin < histogramSize; bin++) {
total += histogram->GetFrequency(bin, 0);
}
for (unsigned int bin = 0; bin < histogramSize; bin++) {
double f = histogram->GetFrequency(bin, 0) / total;
// fprintf(stdout, "bin %d, value is %f\n", bin, f);
sum += f;
if (t1 == -1 && sum > lowerT) {
t1 = minGray + (maxGray - minGray) * (bin / (float)histogramSize);
}
if (t2 == -1 && sum > upperT) {
t2 = minGray + (maxGray - minGray) * (bin / (float)histogramSize);
break;
}
}
//if (verbose) {
// fprintf(stdout, "calculated best threshold low: %f, high: %f\n", t1, t2);
//}
// we need three 3D images for the red green and blue channel
// so we can blurr them before using them in the output image
typedef float FPixelType;
// typedef itk::Image<FPixelType, 2> FloatImageType;
using FloatImageType = itk::Image<FPixelType, 3>;
FloatImageType::Pointer red_channel = FloatImageType::New();
FloatImageType::Pointer green_channel = FloatImageType::New();
FloatImageType::Pointer blue_channel = FloatImageType::New();
ImageType3D::RegionType fusedRegion = image->GetLargestPossibleRegion();
red_channel->SetRegions(fusedRegion);
red_channel->Allocate();
red_channel->FillBuffer(itk::NumericTraits<FPixelType>::Zero);
red_channel->SetOrigin(image->GetOrigin());
red_channel->SetSpacing(image->GetSpacing());
red_channel->SetDirection(image->GetDirection());
green_channel->SetRegions(fusedRegion);
green_channel->Allocate();
green_channel->FillBuffer(itk::NumericTraits<FPixelType>::Zero);
green_channel->SetOrigin(image->GetOrigin());
green_channel->SetSpacing(image->GetSpacing());
green_channel->SetDirection(image->GetDirection());
blue_channel->SetRegions(fusedRegion);
blue_channel->Allocate();
blue_channel->FillBuffer(itk::NumericTraits<FPixelType>::Zero);
blue_channel->SetOrigin(image->GetOrigin());
blue_channel->SetSpacing(image->GetSpacing());
blue_channel->SetDirection(image->GetDirection());
std::vector<std::pair<int,int>> sizeByROI;
for (unsigned int roi = 0; roi < labelMap->GetNumberOfLabelObjects(); ++roi) {
ShapeLabelObjectType *labelObject = labelMap->GetNthLabelObject(roi); // the label number is the connected component number - not the one label as mask
sizeByROI.push_back(std::make_pair(labelObject->GetNumberOfPixels(), roi));
}
std::sort(sizeByROI.begin(), sizeByROI.end(), [](auto &left, auto &right) {
return left.first > right.first; // largest roi first
});
// add info as roi_order for later
//for (int roi_idx = 0; roi_idx < labelMap->GetNumberOfLabelObjects(); ++roi_idx) {
// returns.roi_order.push_back(sizeByROI[roi_idx].second);
//}
// here we need to compute using the label order, later when we look at the results we will use the returned roi_order?
// but we don't need both!!
for (unsigned int n_idx = 0; n_idx < labelMap->GetNumberOfLabelObjects(); n_idx++) {
unsigned int n = sizeByROI[n_idx].second;
ShapeLabelObjectType *labelObject = labelMap->GetNthLabelObject(n); // the label number is the connected component number - not the one label as mask
int label = labelObject->GetLabel(); // it might be that all regions have the same label and only n is a good choice for the color
// color is
std::vector<float> col = labelColors2[ (label % (labelColors2.size()-1)) +1 ];
itk::Index<3U> index;
for (unsigned int pixelId = 0; pixelId < labelObject->Size(); pixelId++) {
index = labelObject->GetIndex(pixelId);
// set this position in all three color images, values are between 0 and 1
red_channel->SetPixel(index, col[0]/255.0);
green_channel->SetPixel(index, col[1]/255.0);
blue_channel->SetPixel(index, col[2]/255.0);
}
}
// smooth all three channels independently from each other
using GFilterType = itk::DiscreteGaussianImageFilter<FloatImageType, FloatImageType>;
auto gaussFilterR = GFilterType::New();
gaussFilterR->SetInput(red_channel);
gaussFilterR->SetVariance(1.5f);
gaussFilterR->Update();
FloatImageType::Pointer smoothRed = gaussFilterR->GetOutput();
auto gaussFilterG = GFilterType::New();
gaussFilterG->SetInput(green_channel);
gaussFilterG->SetVariance(1.5f);
gaussFilterG->Update();
FloatImageType::Pointer smoothGreen = gaussFilterG->GetOutput();
auto gaussFilterB = GFilterType::New();
gaussFilterB->SetInput(blue_channel);
gaussFilterB->SetVariance(1.5f);
gaussFilterB->Update();
FloatImageType::Pointer smoothBlue = gaussFilterB->GetOutput();
itk::ImageRegionIterator<FloatImageType> redSIterator(smoothRed, fusedRegion);
itk::ImageRegionIterator<FloatImageType> greenSIterator(smoothGreen, fusedRegion);
itk::ImageRegionIterator<FloatImageType> blueSIterator(smoothBlue, fusedRegion);
itk::LinearInterpolateImageFunction<ImageType3D, double>::Pointer interpolator =
itk::LinearInterpolateImageFunction<ImageType3D, double>::New();
interpolator->SetInputImage(image);
itk::LinearInterpolateImageFunction<FloatImageType, double>::Pointer interpolatorRed =
itk::LinearInterpolateImageFunction<FloatImageType, double>::New();
interpolatorRed->SetInputImage(smoothRed);
itk::LinearInterpolateImageFunction<FloatImageType, double>::Pointer interpolatorGreen =
itk::LinearInterpolateImageFunction<FloatImageType, double>::New();
interpolatorGreen->SetInputImage(smoothGreen);
itk::LinearInterpolateImageFunction<FloatImageType, double>::Pointer interpolatorBlue =
itk::LinearInterpolateImageFunction<FloatImageType, double>::New();
interpolatorBlue->SetInputImage(smoothBlue);
float f = 0.4; // weight of the underlay, 0.1 is mostly mask visible
// TODO: sort roi's by size and start with the largest region of interest (top of the image)
for (unsigned int roi_idx = 0; roi_idx < sizeByROI.size(); ++roi_idx) {
unsigned int roi = sizeByROI[roi_idx].second;
ShapeLabelObjectType *labelObject = labelMap->GetNthLabelObject(roi); // the label number is the connected component number - not the one label as mask
int label = labelObject->GetLabel();
// do this for the left side
int targetLocationStart[2];
targetLocationStart[0] = 0;
targetLocationStart[1] = roi_idx * base_image_sizeLH;
int targetLocationEnd[2];
targetLocationEnd[0] = targetLocationStart[0] + base_image_sizeLW;
targetLocationEnd[1] = targetLocationStart[1] + base_image_sizeLH;
RegionType::SizeType targetSize;
targetSize[0] = targetLocationEnd[0] - targetLocationStart[0];
targetSize[1] = targetLocationEnd[1] - targetLocationStart[1];
RegionType::IndexType targetIndex;
targetIndex[0] = targetLocationStart[0];
targetIndex[1] = targetLocationStart[1];
// compute the bounding box for this object in all three orientations
std::vector<double> boundingBox(6); // three coordinates and one label value (in physical coordinates)
using PT = typename ImageType3D::PointType;
PT floatIndexA; // a single point's coordinate (in world coordinates)
itk::Index<3U> index;
for (unsigned int pixelId = 0; pixelId < labelObject->Size(); pixelId++) {
index = labelObject->GetIndex(pixelId);
// get the position in floating point from the index
image->TransformIndexToPhysicalPoint(index, floatIndexA);
if (pixelId == 0) {
boundingBox[0] = floatIndexA[0];
boundingBox[1] = floatIndexA[1];
boundingBox[2] = floatIndexA[2];
boundingBox[3] = floatIndexA[0];
boundingBox[4] = floatIndexA[1];
boundingBox[5] = floatIndexA[2];
}
if (boundingBox[0] > floatIndexA[0])
boundingBox[0] = floatIndexA[0];
if (boundingBox[1] > floatIndexA[1])
boundingBox[1] = floatIndexA[1];
if (boundingBox[2] > floatIndexA[2])
boundingBox[2] = floatIndexA[2];
if (boundingBox[3] < floatIndexA[0])
boundingBox[3] = floatIndexA[0];
if (boundingBox[4] < floatIndexA[1])
boundingBox[4] = floatIndexA[1];
if (boundingBox[5] < floatIndexA[2])
boundingBox[5] = floatIndexA[2];
}
// now make the bounding box bigger
std::vector<double> biggerBB(6);
// A bounding box can be too small if the label is tiny, we should enlarge the
// bounding box suffiently to reach a minimum of maybe 30% of the space in the volume.
float enlarge[3];
enlarge[0] = (boundingBox[3]-boundingBox[0]);
enlarge[1] = (boundingBox[4]-boundingBox[1]);
enlarge[2] = (boundingBox[5]-boundingBox[2]);
// if total volume still too small make it even larger, boundingBox size is in mm
if (enlarge[0]*3 < 100)
enlarge[0] = 100 - enlarge[0];
if (enlarge[1]*3 < 100)
enlarge[1] = 100 - enlarge[1];
if (enlarge[2]*3 < 100)
enlarge[2] = 100 - enlarge[2];
biggerBB[0] = boundingBox[0] - enlarge[0];
biggerBB[1] = boundingBox[1] - enlarge[1];
biggerBB[2] = boundingBox[2] - enlarge[2];
biggerBB[3] = boundingBox[3] + enlarge[0];
biggerBB[4] = boundingBox[4] + enlarge[1];
biggerBB[5] = boundingBox[5] + enlarge[2];
for (int counter = 0; counter < 6; counter++)
boundingBox[counter] = biggerBB[counter];
// by definition our label is in the center of the picture
returns.pos.push_back(std::array<int, 2>{(int)floor(targetLocationStart[0] + (targetLocationEnd[0]-targetLocationStart[0])/2.0), (int)floor(targetLocationStart[1] + (targetLocationEnd[1]-targetLocationStart[1])/2.0)});
returns.text.push_back(std::to_string(label));
// do the next steps 3 times, start with left image
{
RegionType targetRegion(targetIndex, targetSize); // the region we want to fill in the output key image
itk::ImageRegionIteratorWithIndex<CImageType> targetRGBIterator(keyImage, targetRegion);
// finished computing the maximum enclosing bounding box for this region of interest
// do we need that? We could zoom in, but that is costly... with a zoom factor.
// We would want to see the region of interest and double the space around the region.
targetRGBIterator.GoToBegin(); // 2D Volume of curved slice
while (!targetRGBIterator.IsAtEnd() ) {
CPixelType value = targetRGBIterator.Value(); // we ignore this value, will be filled in with correct one at the end
CImageType::IndexType idx = targetRGBIterator.GetIndex();
// the current output pixel (idx) in percentage of output image (index coordinates)
float idx_percent[2];
idx_percent[0] = ((float)idx[0] - (float)targetLocationStart[0])/((float)targetLocationEnd[0]-(float)targetLocationStart[0]);
idx_percent[1] = ((float)idx[1] - (float)targetLocationStart[1])/((float)targetLocationEnd[1]-(float)targetLocationStart[1]);
// the above should be between 0.0 and 1.0, test here
if (idx_percent[0] < 0.0 || idx_percent[0]>1.0) {
fprintf(stderr, "Error: idx_percent is not 0..1 but %f. Should not happen\n", idx_percent[0]);
}
if (idx_percent[1] < 0.0 || idx_percent[1]>1.0) {
fprintf(stderr, "Error: idx_percent is not 0..1 but %f. Should not happen\n", idx_percent[1]);
}
itk::ContinuousIndex<double, 3> pixel;
itk::ContinuousIndex<double, 3> floatIndexA;
// use x as fastest running index and y as second fast running, third dimension is at mid-point
// TODO: scaling of voxel size is not taken care of. We need to move differently based on pixel size
//auto voxelSize = image->GetSpacing();
float start0 = boundingBox[0];
float start1 = boundingBox[1];
float start2 = boundingBox[2];
float sx = (boundingBox[3]-boundingBox[0]);
float sy = (boundingBox[4]-boundingBox[1]);
float sz = (boundingBox[5]-boundingBox[2]);
if (sx > sy) {
// adjust the other bounding box to the same size, and center it
float midy = start1 + sy/2.0;
start1 = midy - (sx/2.0);
sy = sx;
} else {
// adjust the other bounding box to the same size, and center it
float midx = start0 + sx/2.0;
start0 = midx - (sy/2.0);
sx = sy;
}
// aspect ratio of output image is 1, so bounding box needs to be adjusted in the smaller dimension to have
// same aspect ratio based on larger dimension sx or sy
pixel[0] = (float)start0 + idx_percent[0]*sx; // in pixel coordinates of image, based on boundingBox of one dimension
pixel[1] = (float)start1 + idx_percent[1]*sy;
pixel[2] = (float)start2 + sz/2.0f; // middle
image->TransformPhysicalPointToContinuousIndex(pixel, floatIndexA);
// std::cout << "Value at 1.3: " << interpolator->EvaluateAtContinuousIndex(pixel) << std::endl;
float grayValue = 0;
float redValue = 0;
float blueValue = 0;
float greenValue = 0;
if (interpolator->IsInsideBuffer(floatIndexA)) {
grayValue = interpolator->EvaluateAtContinuousIndex(floatIndexA);
redValue = interpolatorRed->EvaluateAtContinuousIndex(floatIndexA);
greenValue = interpolatorGreen->EvaluateAtContinuousIndex(floatIndexA);
blueValue = interpolatorBlue->EvaluateAtContinuousIndex(floatIndexA);
} else {
//fprintf(stdout, "OUTSIDE region element at location %f %f %f\n", pixel[0], pixel[1], pixel[2]);
//fflush(stdout);
}
float scaledGrayValue = (grayValue - t1) / (t2-t1);
float red = f * scaledGrayValue + (1 - f) * redValue;
float green = f * scaledGrayValue + (1 - f) * greenValue;
float blue = f * scaledGrayValue + (1 - f) * blueValue;
//fprintf(stdout, "before clipping red, green blue: %f %f %f\n", red, green, blue);
red = std::min<float>(1, std::max<float>(0,red));
green = std::min<float>(1, std::max<float>(0,green));
blue = std::min<float>(1, std::max<float>(0,blue));
//fprintf(stdout, "red, green blue: %f %f %f\n", red, green, blue);
//fflush(stdout);
value.SetRed((int)(red * 255));
value.SetGreen((int)(green * 255));
value.SetBlue((int)(blue * 255));
targetRGBIterator.Set(value);
++targetRGBIterator;
}
} // Left image done
{ // Right top image (flip 180)
targetLocationStart[0] = base_image_sizeLW;
targetLocationStart[1] = roi_idx * base_image_sizeLH;
targetLocationEnd[0] = targetLocationStart[0] + base_image_sizeRW;
targetLocationEnd[1] = targetLocationStart[1] + base_image_sizeRH;
RegionType::SizeType targetSize;
targetSize[0] = targetLocationEnd[0] - targetLocationStart[0];
targetSize[1] = targetLocationEnd[1] - targetLocationStart[1];
RegionType::IndexType targetIndex;
targetIndex[0] = targetLocationStart[0];
targetIndex[1] = targetLocationStart[1];
RegionType targetRegion(targetIndex, targetSize); // the region we want to fill in the output key image
itk::ImageRegionIteratorWithIndex<CImageType> targetRGBIterator(keyImage, targetRegion);
// finished computing the maximum inclosing bounding box for this region of interest
// do we need that? We could zoom in, but that is costly... with a zoom factor.
// We would want to see the region of interest and double the space around the region.
targetRGBIterator.GoToBegin(); // 2D Volume of curved slice
while (!targetRGBIterator.IsAtEnd() ) {
CPixelType value = targetRGBIterator.Value(); // we ignore this value, will be filled in with correct one at the end
CImageType::IndexType idx = targetRGBIterator.GetIndex();
// the current output pixel (idx) in percentage of output image (index coordinates)
float idx_percent[2];
idx_percent[0] = ((float)idx[0] - (float)targetLocationStart[0])/((float)targetLocationEnd[0]-(float)targetLocationStart[0]);
idx_percent[1] = ((float)idx[1] - (float)targetLocationStart[1])/((float)targetLocationEnd[1]-(float)targetLocationStart[1]);
idx_percent[1] = 1.0f - idx_percent[1];
// the above should be between 0.0 and 1.0, test here
if (idx_percent[0] < 0.0 || idx_percent[0]>1.0) {
fprintf(stderr, "Error: idx_percent is not 0..1 but %f. Should not happen\n", idx_percent[0]);
}
if (idx_percent[1] < 0.0 || idx_percent[1]>1.0) {
fprintf(stderr, "Error: idx_percent is not 0..1 but %f. Should not happen\n", idx_percent[1]);
}
itk::ContinuousIndex<double, 3> pixel;
itk::ContinuousIndex<double, 3> floatIndexA;
float start0 = boundingBox[0];
float start1 = boundingBox[1];
float start2 = boundingBox[2];
float sx = (boundingBox[3]-boundingBox[0]);
float sy = (boundingBox[4]-boundingBox[1]);
float sz = (boundingBox[5]-boundingBox[2]);
if (sz > sx) {
// adjust the other bounding box to the same size, and center it
float midx = start0 + sx/2.0;
start0 = midx - (sz/2.0);
sx = sz;
} else {
// adjust the other bounding box to the same size, and center it
float midz = start2 + sz/2.0;
start2 = midz - (sx/2.0);
sz = sx;
}
// aspect ratio of output image is 1, so bounding box needs to be adjusted in the smaller dimension to have
// same aspect ratio based on larger dimension sx or sy
pixel[0] = (float)start0 + idx_percent[0]*sx; // in pixel coordinates of image, based on boundingBox of one dimension
pixel[1] = (float)start1 + sy/2.0;
pixel[2] = (float)start2 + idx_percent[1]*sz; // middle
// use x as fastest running index and y as second fast running, third dimension is at mid-point
//pixel[0] = (float)boundingBox[0] + idx_percent[0]*(boundingBox[3]-boundingBox[0]); // in pixel coordinates of image, based on boundingBox of one dimension
//pixel[1] = (float)boundingBox[1] + (boundingBox[4]-boundingBox[1])/2.0f; // middle
//pixel[2] = (float)boundingBox[2] + idx_percent[1]*(boundingBox[5]-boundingBox[2]);
image->TransformPhysicalPointToContinuousIndex(pixel, floatIndexA);
// std::cout << "Value at 1.3: " << interpolator->EvaluateAtContinuousIndex(pixel) << std::endl;
float grayValue = 0;
float redValue = 0;
float blueValue = 0;
float greenValue = 0;
if (interpolator->IsInsideBuffer(floatIndexA)) {
grayValue = interpolator->EvaluateAtContinuousIndex(floatIndexA);
redValue = interpolatorRed->EvaluateAtContinuousIndex(floatIndexA);
greenValue = interpolatorGreen->EvaluateAtContinuousIndex(floatIndexA);
blueValue = interpolatorBlue->EvaluateAtContinuousIndex(floatIndexA);
} else {
//fprintf(stdout, "OUTSIDE region element at location %f %f %f\n", pixel[0], pixel[1], pixel[2]);
//fflush(stdout);
}
float scaledGrayValue = (grayValue - t1) / (t2-t1);
float red = f * scaledGrayValue + (1 - f) * redValue;
float green = f * scaledGrayValue + (1 - f) * greenValue;
float blue = f * scaledGrayValue + (1 - f) * blueValue;
//fprintf(stdout, "before clipping red, green blue: %f %f %f\n", red, green, blue);
red = std::min<float>(1, std::max<float>(0,red));
green = std::min<float>(1, std::max<float>(0,green));
blue = std::min<float>(1, std::max<float>(0,blue));
//fprintf(stdout, "red, green blue: %f %f %f\n", red, green, blue);
//fflush(stdout);
value.SetRed((int)(red * 255));
value.SetGreen((int)(green * 255));
value.SetBlue((int)(blue * 255));
targetRGBIterator.Set(value);
++targetRGBIterator;
}
} // Right top image done
{ // Right bottom image
targetLocationStart[0] = base_image_sizeLW;
targetLocationStart[1] = roi_idx * base_image_sizeLH + base_image_sizeRH;
targetLocationEnd[0] = targetLocationStart[0] + base_image_sizeRW;
targetLocationEnd[1] = targetLocationStart[1] + base_image_sizeRH;
RegionType::SizeType targetSize;
targetSize[0] = targetLocationEnd[0] - targetLocationStart[0];
targetSize[1] = targetLocationEnd[1] - targetLocationStart[1];
RegionType::IndexType targetIndex;
targetIndex[0] = targetLocationStart[0];
targetIndex[1] = targetLocationStart[1];
RegionType targetRegion(targetIndex, targetSize); // the region we want to fill in the output key image
itk::ImageRegionIteratorWithIndex<CImageType> targetRGBIterator(keyImage, targetRegion);
// finished computing the maximum inclosing bounding box for this region of interest
// do we need that? We could zoom in, but that is costly... with a zoom factor.
// We would want to see the region of interest and double the space around the region.
targetRGBIterator.GoToBegin(); // 2D Volume of curved slice
while (!targetRGBIterator.IsAtEnd() ) {
CPixelType value = targetRGBIterator.Value(); // we ignore this value, will be filled in with correct one at the end
CImageType::IndexType idx = targetRGBIterator.GetIndex();
// the current output pixel (idx) in percentage of output image (index coordinates)
float idx_percent[2];
idx_percent[0] = ((float)idx[0] - (float)targetLocationStart[0])/((float)targetLocationEnd[0]-(float)targetLocationStart[0]);
idx_percent[1] = ((float)idx[1] - (float)targetLocationStart[1])/((float)targetLocationEnd[1]-(float)targetLocationStart[1]);
// the above should be between 0.0 and 1.0, test here
idx_percent[1] = 1.0f - idx_percent[1];
if (idx_percent[0] < 0.0 || idx_percent[0]>1.0) {
fprintf(stderr, "Error: idx_percent is not 0..1 but %f. Should not happen\n", idx_percent[0]);
}
if (idx_percent[1] < 0.0 || idx_percent[1]>1.0) {
fprintf(stderr, "Error: idx_percent is not 0..1 but %f. Should not happen\n", idx_percent[1]);
}
itk::ContinuousIndex<double, 3> pixel;
itk::ContinuousIndex<double, 3> floatIndexA;
float start0 = boundingBox[0];
float start1 = boundingBox[1];
float start2 = boundingBox[2];
float sx = (boundingBox[3]-boundingBox[0]);
float sy = (boundingBox[4]-boundingBox[1]);
float sz = (boundingBox[5]-boundingBox[2]);
if (sz > sy) {
// adjust the other bounding box to the same size, and center it
float midy = start1 + sy/2.0;
start1 = midy - (sz/2.0);
sy = sz;
} else {
// adjust the other bounding box to the same size, and center it
float midz = start2 + sz/2.0;
start2 = midz - (sy/2.0);
sz = sy;
}
// aspect ratio of output image is 1, so bounding box needs to be adjusted in the smaller dimension to have
// same aspect ratio based on larger dimension sx or sy
pixel[0] = (float)start0 + sx/2.0;; // in pixel coordinates of image, based on boundingBox of one dimension
pixel[1] = (float)start1 + idx_percent[0]*sy;
pixel[2] = (float)start2 + idx_percent[1]*sz; // middle
// use x as fastest running index and y as second fast running, third dimension is at mid-point
//pixel[0] = (float)boundingBox[0] + (boundingBox[3]-boundingBox[0])/2.0f; // middle
//pixel[1] = (float)boundingBox[1] + idx_percent[0]*(boundingBox[4]-boundingBox[1]); // in pixel coordinates of image, based on boundingBox of one dimension
//pixel[2] = (float)boundingBox[2] + idx_percent[1]*(boundingBox[5]-boundingBox[2]);
image->TransformPhysicalPointToContinuousIndex(pixel, floatIndexA);
// std::cout << "Value at 1.3: " << interpolator->EvaluateAtContinuousIndex(pixel) << std::endl;
float grayValue = 0;
float redValue = 0;
float blueValue = 0;
float greenValue = 0;
if (interpolator->IsInsideBuffer(floatIndexA)) {
grayValue = interpolator->EvaluateAtContinuousIndex(floatIndexA);
redValue = interpolatorRed->EvaluateAtContinuousIndex(floatIndexA);
greenValue = interpolatorGreen->EvaluateAtContinuousIndex(floatIndexA);
blueValue = interpolatorBlue->EvaluateAtContinuousIndex(floatIndexA);
} else {
//fprintf(stdout, "OUTSIDE region element at location %f %f %f\n", pixel[0], pixel[1], pixel[2]);
//fflush(stdout);
}
float scaledGrayValue = (grayValue - t1) / (t2-t1);
float red = f * scaledGrayValue + (1 - f) * redValue;
float green = f * scaledGrayValue + (1 - f) * greenValue;
float blue = f * scaledGrayValue + (1 - f) * blueValue;
//fprintf(stdout, "before clipping red, green blue: %f %f %f\n", red, green, blue);
red = std::min<float>(1, std::max<float>(0,red));
green = std::min<float>(1, std::max<float>(0,green));
blue = std::min<float>(1, std::max<float>(0,blue));
//fprintf(stdout, "red, green blue: %f %f %f\n", red, green, blue);
//fflush(stdout);
value.SetRed((int)(red * 255));
value.SetGreen((int)(green * 255));
value.SetBlue((int)(blue * 255));
targetRGBIterator.Set(value);
++targetRGBIterator;
}
} // Right bottom image done
}
return returns;
}
// generate a key image based on the input image and a mask (fused with names)
// test:
// ./imageAndMask2Report data/ror_trigger_run_Wednesday_980595789/ror_trigger_run_Wednesday_980595789/input data/ror_trigger_run_Wednesday_980595789/ror_trigger_run_Wednesday_980595789_output/labels/508bc8c54546f0c3383f4325ec6fa70e310328932af7bffcf812079391445.1/ /tmp/bla -u | less
generateImageReturn generateKeyImage(ImageType3D::Pointer image, LabelMapType *labelMap, std::vector<int> resolution, float lowerT, float upperT) {
if (verbose) {
fprintf(stdout, "Start generating a key image...\n");
}
std::vector<std::vector<float>> labelColors2 = {{0, 0, 0}, {166,206,227}, {31,120,180}, {178,223,138}, {51,160,44}, {251,154,153}, {227,26,28}, {253,191,111}, {255,127,0}, {202,178,214}, {106,61,154}, {255,255,153}, {177,89,40}};
generateImageReturn returns; // store keyImage and the location and text that should be presented ontop of the image
// create a new RGB image
CImageType::Pointer keyImage = CImageType::New();
returns.keyImage = keyImage;
using RegionType = itk::ImageRegion<2>;
RegionType::SizeType size;
size[0] = resolution[0]; // 512
size[1] = resolution[1]; // 512
RegionType::IndexType index;
index.Fill(0);
RegionType region(index, size);
keyImage->SetRegions(region);
keyImage->Allocate();
keyImage->FillBuffer(itk::NumericTraits<CPixelType>::Zero);
//
// for each label compute the center of mass for a spline function
//
std::vector< std::array<double, 4> > centers; // three coordinates and one label value (in physical coordinates)
std::array<double, 3> minPos, maxPos;
// keep a map of all pixel coordinates with label
//std::map< std::string, int > coord2Label;
for (unsigned int n = 0; n < labelMap->GetNumberOfLabelObjects(); ++n) {
// these are all in order
returns.roi_order.push_back(n);
ShapeLabelObjectType *labelObject = labelMap->GetNthLabelObject(n); // the label number is the connected component number - not the one label as mask
int label = labelObject->GetLabel();
using PT = typename ImageType3D::PointType;
PT floatIndexA; // a single points coordinates in world coordinates
PT centerHere; // we accumulate positions here to compute the center of mass for this object in 3D (world coordinates)
centerHere[0] = 0.0f;
centerHere[1] = 0.0f;
centerHere[2] = 0.0f;
itk::Index<3U> index;
for (unsigned int pixelId = 0; pixelId < labelObject->Size(); pixelId++) {
index = labelObject->GetIndex(pixelId);
// if we compute the key like this we can get the label for it,
// not being in the map means that we have a background pixel
//std::string key = std::to_string(index[0]) + "_" + std::to_string(index[1]) + "_" + std::to_string(index[2]);
//coord2Label.insert( std::make_pair(key, label) );
// get the position in floating point from the index
image->TransformIndexToPhysicalPoint(index, floatIndexA);
centerHere[0] += floatIndexA[0];
centerHere[1] += floatIndexA[1];
centerHere[2] += floatIndexA[2];
}
centerHere[0] /= labelObject->Size(); // center of mass
centerHere[1] /= labelObject->Size();
centerHere[2] /= labelObject->Size();
centers.push_back(std::array<double, 4>{centerHere[0], centerHere[1], centerHere[2], (double)label}); // keep track of the label (connected component generated int value)
if (n == 0) { // init
minPos[0] = centerHere[0]; minPos[1] = centerHere[1]; minPos[2] = centerHere[2];
maxPos[0] = centerHere[0]; maxPos[1] = centerHere[1]; maxPos[2] = centerHere[2];
} else {
for (int i = 0; i < 3; i++) {
if (centerHere[i] < minPos[i]) {
minPos[i] = centerHere[i];
}
if (centerHere[i] > maxPos[i]) {
maxPos[i] = centerHere[i];
}
}
}
}
if (centers.size() == 0) {
// nothing to do, return here
if (verbose)
fprintf(stdout, "nothing to do here, no centers found\n");
return returns;
}
// compute the extend in all three dimensions and the index of the longest axis
std::vector<double> dists{(maxPos[0]-minPos[0]),(maxPos[1]-minPos[1]),(maxPos[2]-minPos[2])};
int directionLongestAxis = std::max_element(dists.begin(), dists.end()) - dists.begin();
if (verbose)
fprintf(stdout, "direction longest axis is: %d\n", directionLongestAxis);
/*if (verbose)
for (int i = 0; i < centers.size(); i++) {
fprintf(stdout, "centers before sort %d is : %f %f %f\n", i, centers[i][0], centers[i][1], centers[i][2]);
}*/
// we want to interpolate between the points in the right order along the directionLongestAxis
// TODO: find out what the correct axis is based on some DICOM tags
std::sort(centers.begin(), centers.end(), [directionLongestAxis](const std::array<double, 4> a, const std::array<double, 4> b) {
return a.at(directionLongestAxis) > b.at(directionLongestAxis);
});
/*if (verbose)
for (int i = 0; i < centers.size(); i++) {
fprintf(stdout, "centers after sort %d is : %f %f %f\n", i, centers[i][0], centers[i][1], centers[i][2]);
}*/
// add two points at the beginning and at the end to continue to the center curve
auto one = centers[0];
// we can guarantee that we have one region here
if (centers.size() > 1) {
auto two = centers[1];
std::array<double, 4> newBeginning = std::array<double, 4>{ one[0] + (one[0] - two[0]), one[1] + (one[1] - two[1]), one[2] + (one[2] - two[2]), -1 };
centers.insert(centers.begin(), newBeginning);
one = centers[centers.size()-1];
two = centers[centers.size()-2];
std::array<double, 4> newEnding = std::array<double, 4>{ one[0] + (one[0] - two[0]), one[1] + (one[1] - two[1]), one[2] + (one[2] - two[2]), (double)(centers.size()+1) };
centers.push_back(newEnding);
} else {
auto two = std::array<double, 4>{ centers[0][0], centers[0][1], centers[0][2], -1 };
two[directionLongestAxis] += 10.0;
std::array<double, 4> newBeginning = std::array<double, 4>{ one[0] + (one[0] - two[0]), one[1] + (one[1] - two[1]), one[2] + (one[2] - two[2]), -1 };
centers.insert(centers.begin(), newBeginning);
one = centers[centers.size()-1];
two = centers[centers.size()-2];
std::array<double, 4> newEnding = std::array<double, 4>{ one[0] + (one[0] - two[0]), one[1] + (one[1] - two[1]), one[2] + (one[2] - two[2]), (double)(centers.size()+1) };
centers.push_back(newEnding);
}
// create an open spline
// Warning: we need at least 4 objects here
// If we have less than 4 but more than 2 regions we can use a linear function from start to end and hope for the best
// we can evaluate the spline
// TODO: use a linear extension in the direction of cr.prime() (tangent vector)
std::vector< std::vector< double > > interpolatedCenterLocations; // should be resolution[1] many, in physical space
if (centers.size() > 4) {
std::vector< std::array<double, 3> > positions; // make a copy of the first 3 dimensions
for (int p = 0; p < centers.size(); p++) {
positions.push_back( std::array<double, 3>{centers[p][0], centers[p][1], centers[p][2]});
}
boost::math::catmull_rom<std::array<double, 3>> cr(std::move(positions));
double dt = cr.max_parameter()/((float)resolution[1]-1.0);
for (int p = 0; p < resolution[1]; p++) {
float s = (double)p * dt;
auto point = cr( (double)p * dt );
interpolatedCenterLocations.push_back(std::vector<double>{point[0], point[1], point[2]});
//fprintf(stdout, "found a point at %d %f here: %f %f %f\n", p, s, point[0], point[1], point[2]);
}
//fflush(stdout);
} else if (centers.size() > 1) {
for (int p = 0; p < resolution[1]; p++) {
std::vector<double> point;
point.push_back(centers[0][0] + p*(centers[centers.size()-1][0] - centers[0][0])/((double)resolution[1]-1.0) );
point.push_back(centers[0][1] + p*(centers[centers.size()-1][1] - centers[0][1])/((double)resolution[1]-1.0) );
point.push_back(centers[0][2] + p*(centers[centers.size()-1][2] - centers[0][2])/((double)resolution[1]-1.0) );
interpolatedCenterLocations.push_back(std::vector<double>{point[0], point[1], point[2]});
}
} else {
fprintf(stderr, "Error: no key image for less than 2 points!\n");
// TODO: do a 3 axis view
}
// now sample the image, instead of normal and binormal use one of the other two dimensions
// sample dimension is directionLongestAxis+1 % 3
std::vector<double> sampleDirection{0,0,0};
int sampleDimension = (directionLongestAxis-1) % 3;
if (sampleDimension < 0 || sampleDimension > 2)
sampleDimension = 0; // fallback
sampleDirection[sampleDimension] = 1.0;
double stepSize = sqrtf( /*(interpolatedCenterLocations[1][0] - interpolatedCenterLocations[2][0]) * (interpolatedCenterLocations[1][0] - interpolatedCenterLocations[2][0]) +
(interpolatedCenterLocations[1][1] - interpolatedCenterLocations[2][1]) * (interpolatedCenterLocations[1][1] - interpolatedCenterLocations[2][1]) + */
(interpolatedCenterLocations[1][directionLongestAxis] - interpolatedCenterLocations[2][directionLongestAxis]) * (interpolatedCenterLocations[1][directionLongestAxis] - interpolatedCenterLocations[2][directionLongestAxis]) );
if (verbose) {
fprintf(stdout, "sample direction: %f %f %f, stepsize: %f\n", sampleDirection[0], sampleDirection[1], sampleDirection[2], stepSize);
fflush(stdout);
}
// now sample the output image using the coordinates system we established above
using IteratorTypeImage = itk::ImageRegionIteratorWithIndex< ImageType3D >;
// we can use coord2Label to lookup the mask values, maybe color is missing?
// we need to go through each pixel of the output image
RegionType outputRegion = keyImage->GetLargestPossibleRegion();
itk::ImageRegionIteratorWithIndex<CImageType> outputRGBIterator(keyImage, outputRegion);
//
// compute optimal window level for whole image, we will use the values for the curved slice
//
using ImageCalculatorFilterType = itk::MinimumMaximumImageCalculator<ImageType3D>;
ImageCalculatorFilterType::Pointer imageCalculatorFilter = ImageCalculatorFilterType::New();
imageCalculatorFilter->SetImage(image);
imageCalculatorFilter->Compute();
int minGray = imageCalculatorFilter->GetMinimum();
int maxGray = imageCalculatorFilter->GetMaximum();
using HistogramGeneratorType = itk::Statistics::ScalarImageToHistogramGenerator<ImageType3D>;
HistogramGeneratorType::Pointer histogramGenerator = HistogramGeneratorType::New();
histogramGenerator->SetInput(image);
int histogramSize = 1024;
histogramGenerator->SetNumberOfBins(histogramSize);
histogramGenerator->SetHistogramMin(minGray);
histogramGenerator->SetHistogramMax(maxGray);
histogramGenerator->Compute();
using HistogramType = HistogramGeneratorType::HistogramType;
const HistogramType *histogram = histogramGenerator->GetOutput();
// set in calling function
//double lowerT = 0.01;
//double upperT = 0.999;
double t1 = -1;
double t2 = -1;
double sum = 0;
double total = 0;
for (unsigned int bin = 0; bin < histogramSize; bin++) {
total += histogram->GetFrequency(bin, 0);
}
for (unsigned int bin = 0; bin < histogramSize; bin++) {
double f = histogram->GetFrequency(bin, 0) / total;
// fprintf(stdout, "bin %d, value is %f\n", bin, f);
sum += f;
if (t1 == -1 && sum > lowerT) {
t1 = minGray + (maxGray - minGray) * (bin / (float)histogramSize);
}
if (t2 == -1 && sum > upperT) {
t2 = minGray + (maxGray - minGray) * (bin / (float)histogramSize);
break;
}
}
//if (verbose) {
// fprintf(stdout, "calculated best threshold low: %f, high: %f\n", t1, t2);
//}
// we need three 3D images for the red green and blue channel
// so we can blurr them before using them in the output image
typedef float FPixelType;
// typedef itk::Image<FPixelType, 2> FloatImageType;
using FloatImageType = itk::Image<FPixelType, 3>;
FloatImageType::Pointer red_channel = FloatImageType::New();
FloatImageType::Pointer green_channel = FloatImageType::New();
FloatImageType::Pointer blue_channel = FloatImageType::New();
ImageType3D::RegionType fusedRegion = image->GetLargestPossibleRegion();
red_channel->SetRegions(fusedRegion);
red_channel->Allocate();
red_channel->FillBuffer(itk::NumericTraits<FPixelType>::Zero);
red_channel->SetOrigin(image->GetOrigin());
red_channel->SetSpacing(image->GetSpacing());
red_channel->SetDirection(image->GetDirection());
green_channel->SetRegions(fusedRegion);
green_channel->Allocate();
green_channel->FillBuffer(itk::NumericTraits<FPixelType>::Zero);
green_channel->SetOrigin(image->GetOrigin());
green_channel->SetSpacing(image->GetSpacing());
green_channel->SetDirection(image->GetDirection());
blue_channel->SetRegions(fusedRegion);
blue_channel->Allocate();
blue_channel->FillBuffer(itk::NumericTraits<FPixelType>::Zero);
blue_channel->SetOrigin(image->GetOrigin());
blue_channel->SetSpacing(image->GetSpacing());
blue_channel->SetDirection(image->GetDirection());
// itk::ImageRegionIterator<FloatImageType> redIterator(red_channel, fusedRegion);
// itk::ImageRegionIterator<FloatImageType> greenIterator(green_channel, fusedRegion);
// itk::ImageRegionIterator<FloatImageType> blueIterator(blue_channel, fusedRegion);
for (unsigned int n = 0; n < labelMap->GetNumberOfLabelObjects(); n++) {
ShapeLabelObjectType *labelObject = labelMap->GetNthLabelObject(n); // the label number is the connected component number - not the one label as mask
int label = labelObject->GetLabel(); // it might be that all regions have the same label and only n is a good choice for the color
// color is
std::vector<float> col = labelColors2[ (label % (labelColors2.size()-1)) +1 ];
itk::Index<3U> index;
for (unsigned int pixelId = 0; pixelId < labelObject->Size(); pixelId++) {
index = labelObject->GetIndex(pixelId);
// set this position in all three color images, values are between 0 and 1
red_channel->SetPixel(index, col[0]/255.0);
green_channel->SetPixel(index, col[1]/255.0);
blue_channel->SetPixel(index, col[2]/255.0);
}
}
// smooth all three channels independently from each other
using GFilterType = itk::DiscreteGaussianImageFilter<FloatImageType, FloatImageType>;
auto gaussFilterR = GFilterType::New();
gaussFilterR->SetInput(red_channel);
gaussFilterR->SetVariance(1.5f);
gaussFilterR->Update();
FloatImageType::Pointer smoothRed = gaussFilterR->GetOutput();
auto gaussFilterG = GFilterType::New();
gaussFilterG->SetInput(green_channel);
gaussFilterG->SetVariance(1.5f);
gaussFilterG->Update();
FloatImageType::Pointer smoothGreen = gaussFilterG->GetOutput();
auto gaussFilterB = GFilterType::New();
gaussFilterB->SetInput(blue_channel);
gaussFilterB->SetVariance(1.5f);
gaussFilterB->Update();
FloatImageType::Pointer smoothBlue = gaussFilterB->GetOutput();
itk::ImageRegionIterator<FloatImageType> redSIterator(smoothRed, fusedRegion);
itk::ImageRegionIterator<FloatImageType> greenSIterator(smoothGreen, fusedRegion);
itk::ImageRegionIterator<FloatImageType> blueSIterator(smoothBlue, fusedRegion);
// redSIterator.GoToBegin(); // 3D Volume iterators
// greenSIterator.GoToBegin();
// blueSIterator.GoToBegin();
// we want to do a tri-linear lookup in the input image
itk::LinearInterpolateImageFunction<ImageType3D, double>::Pointer interpolator =
itk::LinearInterpolateImageFunction<ImageType3D, double>::New();
interpolator->SetInputImage(image);
itk::LinearInterpolateImageFunction<FloatImageType, double>::Pointer interpolatorRed =