-
Notifications
You must be signed in to change notification settings - Fork 2
/
LungSegmentation.cxx
2838 lines (2469 loc) · 131 KB
/
LungSegmentation.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
// Nice map of lung segments:
// https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5489231/
#include "itkGDCMImageIO.h"
#include "itkGDCMSeriesFileNames.h"
#include "itkImageFileWriter.h"
#include "itkImageSeriesReader.h"
#include "itkMetaDataObject.h"
#include "itkSmoothingRecursiveGaussianImageFilter.h"
#include "itkBinaryBallStructuringElement.h"
#include "itkBinaryDilateImageFilter.h"
#include "itkBinaryErodeImageFilter.h"
#include "itkBinaryFillholeImageFilter.h"
#include "itkBinaryThresholdImageFilter.h"
#include "itkConnectedComponentImageFilter.h"
//#include "itkExtractImageFilter.h"
//#include "itkPasteImageFilter.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkHessianRecursiveGaussianImageFilter.h"
#include "itkImageAdaptor.h"
#include "itkLabelImageToShapeLabelMapFilter.h"
#include "itkLabelShapeKeepNObjectsImageFilter.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkRGBPixel.h"
#include "itkSliceBySliceImageFilter.h"
#include "itkSymmetricEigenAnalysisImageFilter.h"
#include "itkSymmetricSecondRankTensor.h"
//#include <itkPixelAccessor.h>
#include "itkImageRegionConstIterator.h"
#include "itkImageRegionIterator.h"
#include "itkBSplineInterpolateImageFunction.h"
#include "itkExtractImageFilter.h"
#include "itkResampleImageFilter.h"
#include "itkScalarImageToHistogramGenerator.h"
#include "itkWindowedSincInterpolateImageFunction.h"
#include "gdcmAnonymizer.h"
#include "gdcmAttribute.h"
#include "gdcmDataSetHelper.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 "gdcmRescaler.h"
#include "gdcmStringFilter.h"
#include "gdcmUIDGenerator.h"
#include "itkConstantPadImageFilter.h"
#include "itkShrinkImageFilter.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 <map>
#include "mytypes.h"
// this may need some types defined later, we should share those types in another header file
#include "curvedReslice/curvedReslice.hpp"
using json = nlohmann::json;
using namespace boost::filesystem;
// forward declaration
void CopyDictionary(itk::MetaDataDictionary &fromDict, itk::MetaDataDictionary &toDict);
template <typename TFilter> class CommandIterationUpdate : public itk::Command {
public:
typedef CommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro(Self);
protected:
CommandIterationUpdate() {}
public:
virtual void Execute(itk::Object *caller, const itk::EventObject &event) ITK_OVERRIDE { Execute((const itk::Object *)caller, event); }
virtual void Execute(const itk::Object *object, const itk::EventObject &event) ITK_OVERRIDE {
const TFilter *filter = dynamic_cast<const TFilter *>(object);
if (typeid(event) != typeid(itk::IterationEvent)) {
return;
}
if (filter->GetElapsedIterations() == 1) {
std::cout << "Current level = " << filter->GetCurrentLevel() + 1 << std::endl;
}
std::cout << " Iteration " << filter->GetElapsedIterations() << " (of " << filter->GetMaximumNumberOfIterations()[filter->GetCurrentLevel()] << "). ";
std::cout << " Current convergence value = " << filter->GetCurrentConvergenceMeasurement() << " (threshold = " << filter->GetConvergenceThreshold() << ")"
<< std::endl;
}
};
template <typename TValue> TValue Convert(std::string optionString) {
TValue value;
std::istringstream iss(optionString);
iss >> value;
return value;
}
template <typename TValue> std::vector<TValue> ConvertVector(std::string optionString) {
std::vector<TValue> values;
std::string::size_type crosspos = optionString.find('x', 0);
if (crosspos == std::string::npos) {
values.push_back(Convert<TValue>(optionString));
} else {
std::string element = optionString.substr(0, crosspos);
TValue value;
std::istringstream iss(element);
iss >> value;
values.push_back(value);
while (crosspos != std::string::npos) {
std::string::size_type crossposfrom = crosspos;
crosspos = optionString.find('x', crossposfrom + 1);
if (crosspos == std::string::npos) {
element = optionString.substr(crossposfrom + 1, optionString.length());
} else {
element = optionString.substr(crossposfrom + 1, crosspos);
}
std::istringstream iss2(element);
iss2 >> value;
values.push_back(value);
}
}
return values;
}
json resultJSON;
int main(int argc, char *argv[]) {
boost::posix_time::ptime timeLocal = boost::posix_time::second_clock::local_time();
resultJSON["run_date_time"] = to_simple_string(timeLocal);
itk::MultiThreaderBase::SetGlobalMaximumNumberOfThreads(4);
MetaCommand command;
command.SetAuthor("Hauke Bartsch");
command.SetDescription("LungSegmentation on CT DICOM images. Read DICOM image series and perform "
"a lung segmentation into left, right and trachea regions of interest. Exports a new DICOM series.");
command.AddField("indir", "Directory with input DICOM image series.", MetaCommand::STRING, true);
command.AddField("outdir", "Directory for output DICOM image series.", MetaCommand::STRING, true);
// command.SetOption("Mask", "m", false, "Provide a mask image as an additional input. If not
// supplied the mask will be calculated."); command.AddOptionField("Mask", "mask",
// MetaCommand::STRING, false);
// command.SetOption("Write", "s", false, "The shrink factor will make the problem easier to
// handle (sub-sample data). The larger the value the faster."); command.AddOptionField("Write",
// "shrinkFactor", MetaCommand::INT, false, "3");
command.SetOption("SeriesName", "n", false, "Select series by series name (if more than one series is present).");
command.AddOptionField("SeriesName", "seriesname", MetaCommand::STRING, false);
command.SetOption("SaveLabelfield", "b", false, "Save the label field as a nifty file in the current directory");
command.AddOptionField("SaveLabelfield", "labelfieldfilename", MetaCommand::STRING, true);
command.SetOption("SaveNifty", "u", false, "Save the corrected dataset as a nifty image to the current directory");
command.AddOptionField("SaveNifty", "niftyfilename", MetaCommand::STRING, true);
command.SetOption("SaveReslice", "r", false, "Save a resliced version of the data as DICOM");
// command.AddOptionField("SaveReslice", "reslicefilename", MetaCommand::STRING, true);
command.SetOption("Force", "f", false, "Ignore existing directories and force reprocessing. Default is to stop processing if directory already exists.");
command.SetOption("Verbose", "V", false, "Print more verbose output");
if (!command.Parse(argc, argv)) {
return 1;
}
std::string input = command.GetValueAsString("indir");
std::string output = command.GetValueAsString("outdir");
bool verbose = false;
if (command.GetOptionWasSet("Verbose"))
verbose = true;
bool force = false;
if (command.GetOptionWasSet("Force"))
force = true;
bool saveLabelField = false;
bool saveNifty = false;
bool seriesIdentifierFlag = false;
if (command.GetOptionWasSet("SaveLabelfield"))
saveLabelField = true;
if (command.GetOptionWasSet("SaveNifty")) {
saveNifty = true;
fprintf(stdout, "will save nifty\n");
}
// std::string reslicefilename("");
// if (command.GetOptionWasSet("SaveReslice")) {
// reslicefilename = command.GetValueAsString("SaveReslice", "reslicefilename");
//}
if (command.GetOptionWasSet("SeriesName"))
seriesIdentifierFlag = true;
std::string labelfieldfilename = command.GetValueAsString("SaveLabelfield", "labelfieldfilename");
// todo: the argument could not be there, in this case the labelfieldfilename might be empty
if (!saveLabelField) {
labelfieldfilename = output + "/label_field.nii";
}
std::string niftyfilename = command.GetValueAsString("SaveNifty", "niftyfilename");
std::string niftyfilename2 = niftyfilename + "_walls.nii";
size_t lastdot = niftyfilename.find_last_of(".");
if (lastdot == std::string::npos)
niftyfilename2 = niftyfilename + "_walls.nii";
else
niftyfilename2 = niftyfilename.substr(0, lastdot) + "_walls.nii";
std::string seriesName = command.GetValueAsString("SeriesName", "seriesname");
// store information in the result json file
resultJSON["command_line"] = json::array();
for (int i = 0; i < argc; i++) {
resultJSON["command_line"].push_back(std::string(argv[i]));
}
// typedef signed short PixelType;
typedef float FloatPixelType;
const unsigned int Dimension = 3;
// typedef itk::Image<PixelType, Dimension> ImageType;
typedef itk::Image<FloatPixelType, Dimension> FloatImageType;
typedef itk::ImageSeriesReader<ImageType> ReaderType;
ReaderType::Pointer reader = ReaderType::New();
typedef itk::Image<unsigned char, Dimension> MaskImageType;
typedef itk::Image<unsigned char, 2> MaskSliceImageType;
using StructuringElementType = itk::BinaryBallStructuringElement<PixelType, Dimension>;
using ErodeFilterType = itk::BinaryErodeImageFilter<MaskImageType, MaskImageType, StructuringElementType>;
using DilateFilterType = itk::BinaryDilateImageFilter<MaskImageType, MaskImageType, StructuringElementType>;
typedef itk::ConnectedComponentImageFilter<MaskImageType, ImageType> ConnectedComponentImageFilterType;
typedef itk::GDCMImageIO ImageIOType;
ImageIOType::Pointer dicomIO = ImageIOType::New();
dicomIO->LoadPrivateTagsOn();
reader->SetImageIO(dicomIO);
typedef itk::GDCMSeriesFileNames NamesGeneratorType;
NamesGeneratorType::Pointer nameGenerator = NamesGeneratorType::New();
nameGenerator->SetUseSeriesDetails(true);
nameGenerator->AddSeriesRestriction("0008|0021");
nameGenerator->SetRecursive(true);
nameGenerator->SetDirectory(input);
try {
typedef std::vector<std::string> SeriesIdContainer;
const SeriesIdContainer &seriesUID = nameGenerator->GetSeriesUIDs();
SeriesIdContainer::const_iterator seriesItr = seriesUID.begin();
SeriesIdContainer::const_iterator seriesEnd = seriesUID.end();
while (seriesItr != seriesEnd) {
std::cout << "Found DICOM Series: ";
std::cout << std::endl;
std::cout << " " << seriesItr->c_str() << std::endl;
++seriesItr;
}
std::string seriesIdentifier;
SeriesIdContainer runThese;
if (seriesIdentifierFlag) { // If no optional series identifier
// seriesIdentifier = seriesName;
runThese.push_back(seriesName);
} else {
// Todo: here we select only the first series. We should run
// N3 on all series.
seriesItr = seriesUID.begin();
seriesEnd = seriesUID.end();
// seriesIdentifier = seriesUID.begin()->c_str();
while (seriesItr != seriesEnd) {
runThese.push_back(seriesItr->c_str());
++seriesItr;
}
// Todo: if we have multiple phases they will all be in the same series.
// It does not make sense to handle them here as one big volume, we should
// look for the slice locations (consecutive) identify the first volume
// and run N3 on that one. The resulting bias field should be applied to
// all phases of the series.
}
seriesItr = runThese.begin();
seriesEnd = runThese.end();
while (seriesItr != seriesEnd) {
seriesIdentifier = seriesItr->c_str();
++seriesItr;
std::cout << "Processing series: " << std::endl;
std::cout << " " << seriesIdentifier << std::endl;
std::string outputSeries = output + "/" + seriesIdentifier;
if (!force && itksys::SystemTools::FileIsDirectory(outputSeries.c_str())) {
fprintf(stdout, "Skip this series %s, output directory exists already...\n", outputSeries.c_str());
exit(0); // this is no skip, that is giving up...
}
typedef std::vector<std::string> FileNamesContainer;
FileNamesContainer fileNames;
fileNames = nameGenerator->GetFileNames(seriesIdentifier);
if (fileNames.size() < 10) {
std::cout << "skip processing, not enough images in this series..." << std::endl;
continue;
}
fprintf(stdout, "sufficient number of images (%lu) in this series\n", fileNames.size());
resultJSON["series_identifier"] = seriesIdentifier;
// for (int i = 0; i < fileNames.size(); i++) {
// resultJSON["file_names"].push_back(fileNames[i]);
//}
// here we read in all the slices as a single volume for processing
// if we want to write them back out we have to read them slice by
// slice and get a copy of the meta data for each slice
reader->SetFileNames(fileNames);
reader->ForceOrthogonalDirectionOff(); // do we need this?
try {
reader->Update();
} catch (itk::ExceptionObject &ex) {
std::cout << ex << std::endl;
return EXIT_FAILURE;
}
// read the data dictionary
ImageType::Pointer inputImage = reader->GetOutput();
typedef itk::MetaDataDictionary DictionaryType;
DictionaryType &dictionary = dicomIO->GetMetaDataDictionary();
fprintf(stdout, "pixel spacing of input is: %f %f %f\n", inputImage->GetSpacing()[0], inputImage->GetSpacing()[1], inputImage->GetSpacing()[2]);
// overwrite a value in the dicom dictionary
// std::string entryId( "0010|0010" );
// std::string value( "MYNAME" );
// itk::EncapsulateMetaData<std::string>( dictionary, entryId, value );
std::string studyDescription;
std::string seriesDescription;
std::string patientID;
std::string patientName;
std::string sopClassUID;
std::string seriesDate;
std::string seriesTime;
std::string studyDate;
std::string studyTime;
std::string patientSex;
std::string convolutionKernelGroup;
std::string modality;
std::string manufacturer;
if (itk::ExposeMetaData<std::string>(dictionary, "0008|1030", studyDescription))
resultJSON["SeriesDescription"] = boost::algorithm::trim_copy(seriesDescription);
if (itk::ExposeMetaData<std::string>(dictionary, "0008|103e", seriesDescription))
resultJSON["StudyDescription"] = boost::algorithm::trim_copy(studyDescription);
if (itk::ExposeMetaData<std::string>(dictionary, "0008|0016", sopClassUID))
resultJSON["SOPClassUID"] = boost::algorithm::trim_copy(sopClassUID);
if (itk::ExposeMetaData<std::string>(dictionary, "0008|0021", seriesDate))
resultJSON["StudyDate"] = boost::algorithm::trim_copy(studyDate);
if (itk::ExposeMetaData<std::string>(dictionary, "0008|0031", seriesTime))
resultJSON["SeriesTime"] = boost::algorithm::trim_copy(seriesTime);
if (itk::ExposeMetaData<std::string>(dictionary, "0010|0020", patientID))
resultJSON["PatientID"] = boost::algorithm::trim_copy(patientID);
if (itk::ExposeMetaData<std::string>(dictionary, "0010|0010", patientName))
resultJSON["PatientName"] = boost::algorithm::trim_copy(patientName);
if (itk::ExposeMetaData<std::string>(dictionary, "0010|0040", patientSex))
resultJSON["PatientSex"] = boost::algorithm::trim_copy(patientSex);
if (itk::ExposeMetaData<std::string>(dictionary, "0008|0030", studyTime))
resultJSON["StudyTime"] = boost::algorithm::trim_copy(studyTime);
if (itk::ExposeMetaData<std::string>(dictionary, "0008|0020", studyDate))
resultJSON["SeriesDate"] = boost::algorithm::trim_copy(seriesDate);
if (itk::ExposeMetaData<std::string>(dictionary, "0018|9316", convolutionKernelGroup))
resultJSON["CTConvolutionKernelGroup"] = boost::algorithm::trim_copy(convolutionKernelGroup); // LUNG, BRAIN, BONE, SOFT_TISSUE
if (itk::ExposeMetaData<std::string>(dictionary, "0008|0060", modality))
resultJSON["Modality"] = boost::algorithm::trim_copy(modality);
if (itk::ExposeMetaData<std::string>(dictionary, "0008|0080", manufacturer))
resultJSON["Manufacturer"] = boost::algorithm::trim_copy(manufacturer);
MaskImageType::Pointer maskImage;
// if we have a mask on the command line
if (command.GetOptionWasSet("Mask")) {
std::string maskName = command.GetValueAsString("Mask", "mask");
typedef itk::ImageFileReader<MaskImageType> MaskReaderType;
MaskReaderType::Pointer maskreader = MaskReaderType::New();
maskreader->SetFileName(maskName);
try {
maskreader->Update();
maskImage = maskreader->GetOutput();
maskImage->DisconnectPipeline();
} catch (...) {
maskImage = ITK_NULLPTR;
}
}
if (!maskImage) { // segment tissue (body will be 1, air 0)
typedef itk::DiscreteGaussianImageFilter<ImageType, ImageType> gaussianFilterType;
gaussianFilterType::Pointer gaussianFilter = gaussianFilterType::New();
gaussianFilter->SetInput(inputImage);
gaussianFilter->SetVariance(2.0f);
typedef itk::BinaryThresholdImageFilter<ImageType, MaskImageType> ThresholderType;
ThresholderType::Pointer thresh = ThresholderType::New();
thresh->SetInput(gaussianFilter->GetOutput());
thresh->SetLowerThreshold(-20000);
thresh->SetUpperThreshold(-600); // not too bright because otherwise the airways will connect with the lungs
thresh->SetOutsideValue(1); // this marks our lungs as empty space and the body as 1!
thresh->SetInsideValue(0);
thresh->Update();
maskImage = thresh->GetOutput();
maskImage->DisconnectPipeline();
fprintf(stdout, "pixel spacing of mask image is: %f %f %f\n", maskImage->GetSpacing()[0], maskImage->GetSpacing()[1], maskImage->GetSpacing()[2]);
}
//
// improve the mask for the body by hole filling and smoothing (grow + shrink)
//
DilateFilterType::Pointer binaryDilate = DilateFilterType::New(); // grows inside the tissue
DilateFilterType::Pointer binaryDilate2 = DilateFilterType::New();
ErodeFilterType::Pointer binaryErode = ErodeFilterType::New(); // grows inside the lungs
ErodeFilterType::Pointer binaryErode2 = ErodeFilterType::New();
ErodeFilterType::Pointer binaryErode3 = ErodeFilterType::New();
ErodeFilterType::Pointer binaryErode4 = ErodeFilterType::New();
StructuringElementType structuringElement;
structuringElement.SetRadius(1); // 3x3 structuring element
structuringElement.CreateStructuringElement();
binaryDilate->SetKernel(structuringElement);
binaryDilate2->SetKernel(structuringElement);
binaryErode->SetKernel(structuringElement);
binaryErode2->SetKernel(structuringElement);
binaryErode3->SetKernel(structuringElement);
binaryErode4->SetKernel(structuringElement);
binaryDilate->SetInput(maskImage);
binaryDilate2->SetInput(binaryDilate->GetOutput());
binaryErode->SetInput(binaryDilate2->GetOutput());
// binaryErode2->SetInput( binaryErode->GetOutput() );
// binaryErode3->SetInput( binaryErode->GetOutput() );
binaryErode4->SetInput(binaryErode->GetOutput());
binaryDilate->SetDilateValue(1);
binaryDilate2->SetDilateValue(1);
binaryErode->SetErodeValue(1);
binaryErode2->SetErodeValue(1);
binaryErode3->SetErodeValue(1);
binaryErode4->SetErodeValue(1);
// binaryDilate->Update();
// binaryDilate2->Update();
// binaryErode->Update();
// binaryErode2->Update();
// binaryErode3->Update();
// binaryErode4->Update();
//
// fill holes in the binary image slice by slice (fills in air inside the body)
//
typedef itk::SliceBySliceImageFilter<MaskImageType, MaskImageType> SliceFilterType;
SliceFilterType::Pointer sliceFilter = SliceFilterType::New();
sliceFilter->SetInput(maskImage /* binaryErode4->GetOutput() */); // smoothing should get us a better body mask
// (touching bed problem)
if (0) { // debug, save the body mask
typedef itk::ImageFileWriter<MaskImageType> WriterType;
WriterType::Pointer writer = WriterType::New();
// check if that directory exists, create before writing
path p("/tmp/");
writer->SetFileName("/tmp/body_mask.nii");
writer->SetInput(/* binaryErode4->GetOutput() */ maskImage);
std::cout << "Writing the initial mask image as " << std::endl;
std::cout << "/tmp/body_mask.nii" << std::endl << std::endl;
try {
writer->Update();
} catch (itk::ExceptionObject &ex) {
std::cout << ex << std::endl;
return EXIT_FAILURE;
}
}
typedef itk::BinaryFillholeImageFilter<SliceFilterType::InternalInputImageType> HoleFillFilterType;
HoleFillFilterType::Pointer holefillfilter = HoleFillFilterType::New();
holefillfilter->SetForegroundValue(1);
sliceFilter->SetFilter(holefillfilter);
sliceFilter->Update();
ConnectedComponentImageFilterType::Pointer connected = ConnectedComponentImageFilterType::New();
connected->SetBackgroundValue(0);
connected->SetInput(sliceFilter->GetOutput());
connected->Update();
// keep only the large connected component
typedef itk::LabelShapeKeepNObjectsImageFilter<ImageType> LabelShapeKeepNObjectsImageFilterType;
LabelShapeKeepNObjectsImageFilterType::Pointer labelShapeKeepNObjectsImageFilter = LabelShapeKeepNObjectsImageFilterType::New();
labelShapeKeepNObjectsImageFilter->SetInput(connected->GetOutput());
labelShapeKeepNObjectsImageFilter->SetBackgroundValue(0);
labelShapeKeepNObjectsImageFilter->SetNumberOfObjects(1);
labelShapeKeepNObjectsImageFilter->SetAttribute(LabelShapeKeepNObjectsImageFilterType::LabelObjectType::NUMBER_OF_PIXELS);
labelShapeKeepNObjectsImageFilter->Update();
// the above image labelShapeKeepNObjectsImageFilter->GetOutput() is now a good mask for the
// body of the participant next we need to segment air inside that mask (do we need to make
// the mask tighter?, do we need to smooth the input? do we need to calculate this on a
// smaller scale?) use binaryErode2->GetOutput(),
// labelShapeKeepNObjectsImageFilter->GetOutput(), and inputImage to get lung mask
MaskImageType::Pointer mask1 = maskImage; // binaryErode4->GetOutput();
ImageType::Pointer mask2 = labelShapeKeepNObjectsImageFilter->GetOutput(); // body mask
// make mask2 appear over mask1
mask2->SetOrigin(mask1->GetOrigin());
mask2->SetSpacing(mask1->GetSpacing());
mask2->SetDirection(mask1->GetDirection());
MaskImageType::Pointer mask = MaskImageType::New();
MaskImageType::RegionType maskRegion = inputImage->GetLargestPossibleRegion();
MaskImageType::RegionType mask1Region = mask1->GetLargestPossibleRegion();
ImageType::RegionType mask2Region = mask2->GetLargestPossibleRegion();
mask->SetRegions(maskRegion);
mask->Allocate();
mask->FillBuffer(itk::NumericTraits<PixelType>::Zero);
mask->SetOrigin(inputImage->GetOrigin());
mask->SetSpacing(inputImage->GetSpacing());
mask->SetDirection(inputImage->GetDirection());
MaskImageType::SizeType regionSize = maskRegion.GetSize();
itk::ImageRegionIterator<MaskImageType> maskIterator(mask, maskRegion);
itk::ImageRegionIterator<MaskImageType> inputMask1Iterator(mask1, mask1Region);
itk::ImageRegionIterator<ImageType> inputMask2Iterator(mask2, mask2Region);
// everything that is 1 in mask2 and 0 in mask1
// problem is that mask2 can also be a value larger than 1! example is 0263 where the value is
// == 2
while (!maskIterator.IsAtEnd() && !inputMask1Iterator.IsAtEnd() && !inputMask2Iterator.IsAtEnd()) {
if (inputMask2Iterator.Get() > 0 && inputMask1Iterator.Get() == 0) {
// if (maskIterator.GetIndex()[0] > static_cast<ImageType::IndexValueType>(regionSize[0])
// / 2) {
maskIterator.Set(1);
}
++maskIterator;
++inputMask1Iterator;
++inputMask2Iterator;
}
fprintf(stdout, "pixel spacing of grow/shrunk image is: %f %f %f\n", mask->GetSpacing()[0], mask->GetSpacing()[1], mask->GetSpacing()[2]);
if (0) { // debug, save the body mask
typedef itk::ImageFileWriter<MaskImageType> WriterType;
WriterType::Pointer writer1 = WriterType::New();
// check if that directory exists, create before writing
writer1->SetFileName("/tmp/bodyLung_mask01.nii");
writer1->SetInput(mask1 /* mask */);
std::cout << "Writing the lung mask as " << std::endl;
std::cout << "/tmp/bodyLung_mask01.nii" << std::endl << std::endl;
try {
writer1->Update();
} catch (itk::ExceptionObject &ex) {
std::cout << ex << std::endl;
return EXIT_FAILURE;
}
typedef itk::ImageFileWriter<ImageType> WriterType2;
WriterType2::Pointer writer2 = WriterType2::New();
// check if that directory exists, create before writing
writer2->SetFileName("/tmp/bodyLung_mask02.nii");
writer2->SetInput(mask2 /* mask */);
std::cout << "Writing the lung mask as " << std::endl;
std::cout << "/tmp/bodyLung_mask02.nii" << std::endl << std::endl;
try {
writer2->Update();
} catch (itk::ExceptionObject &ex) {
std::cout << ex << std::endl;
return EXIT_FAILURE;
}
// connected->GetOutput()
WriterType2::Pointer writer3 = WriterType2::New();
// check if that directory exists, create before writing
writer3->SetFileName("/tmp/bodyLung_mask03.nii");
writer3->SetInput(connected->GetOutput());
std::cout << "Writing the lung mask as " << std::endl;
std::cout << "/tmp/bodyLung_mask03.nii" << std::endl << std::endl;
try {
writer3->Update();
} catch (itk::ExceptionObject &ex) {
std::cout << ex << std::endl;
return EXIT_FAILURE;
}
WriterType::Pointer writer4 = WriterType::New();
// check if that directory exists, create before writing
writer4->SetFileName("/tmp/bodyLung_mask04.nii");
writer4->SetInput(mask);
std::cout << "Writing the lung mask as " << std::endl;
std::cout << "/tmp/bodyLung_mask04.nii" << std::endl << std::endl;
try {
writer4->Update();
} catch (itk::ExceptionObject &ex) {
std::cout << ex << std::endl;
return EXIT_FAILURE;
}
}
// now in mask we have every air filled cavity inside the body, look for the largest one,
// assume its the lungs this will remove the outside the body parts that are created because
// the slice filling adds them in 2d
ConnectedComponentImageFilterType::Pointer connected2 = ConnectedComponentImageFilterType::New();
connected2->SetBackgroundValue(0);
connected2->SetInput(mask);
connected2->Update();
// std::cout << "Number of connected components: " << connected->GetObjectCount() <<
// std::endl;
// std::cout << "Number of connected components: " << connected->GetObjectCount() <<
// std::endl; we sometimes get the two lungs separated here, we should look for the size of
// connected components we do have a volume range we are looking for and getting two lungs
// with different volumes would be possible (see 0183)
using LabelType = unsigned short;
using ShapeLabelObjectType = itk::ShapeLabelObject<LabelType, 3>;
using LabelMapType = itk::LabelMap<ShapeLabelObjectType>;
using labelType = itk::LabelImageToShapeLabelMapFilter<ImageType, LabelMapType>;
labelType::Pointer label = labelType::New();
label->SetInput(connected2->GetOutput());
label->SetComputePerimeter(true);
label->Update();
int useNObjects = 0;
LabelMapType *labelMap = label->GetOutput();
if (labelMap->GetNumberOfLabelObjects() == 0) {
// error case
fprintf(stderr, "Could not find any object in the data using the current set of "
"thresholds, we can try to start again by lowering the threshold?\n");
}
for (unsigned int n = 0; n < labelMap->GetNumberOfLabelObjects(); ++n) {
ShapeLabelObjectType *labelObject = labelMap->GetNthLabelObject(n);
// fprintf(stdout, "object %d has %0.4f liters, %lu voxel\n", n,
// labelObject->GetPhysicalSize() / 1000000, labelObject->GetNumberOfPixels());
if (labelObject->GetNumberOfPixels() > 150000) // magick number using sample of 1 - should be selected based on volume instead
// of number of pixel
useNObjects++;
}
if (useNObjects < 1) {
fprintf(stdout, "useNObjects is: %d. Set manually to 1.\n", useNObjects);
useNObjects = 1;
}
fprintf(stdout, "found %d object%s with number of voxel large enough to be of interest...\n", useNObjects, useNObjects == 1 ? "" : "s");
// keep only the large connected component
typedef itk::LabelShapeKeepNObjectsImageFilter<ImageType> LabelShapeKeepNObjectsImageMaskFilterType;
LabelShapeKeepNObjectsImageMaskFilterType::Pointer labelShapeKeepNObjectsImageFilter2 = LabelShapeKeepNObjectsImageMaskFilterType::New();
labelShapeKeepNObjectsImageFilter2->SetInput(connected2->GetOutput());
labelShapeKeepNObjectsImageFilter2->SetBackgroundValue(0);
labelShapeKeepNObjectsImageFilter2->SetNumberOfObjects(useNObjects);
labelShapeKeepNObjectsImageFilter2->SetAttribute(LabelShapeKeepNObjectsImageFilterType::LabelObjectType::NUMBER_OF_PIXELS);
labelShapeKeepNObjectsImageFilter2->Update();
// the label filter will keep the id of the label, its not 1, what is it?
/*typedef itk::MinimumMaximumImageCalculator <ImageType> ImageCalculatorFilterType;
ImageCalculatorFilterType::Pointer imageCalculatorFilter = ImageCalculatorFilterType::New
(); imageCalculatorFilter->SetImage( labelShapeKeepNObjectsImageFilter2->GetOutput() );
imageCalculatorFilter->ComputeMaximum();
int maxValue = imageCalculatorFilter->GetMaximum();*/
int maxValue = 1;
// instead of keeping the labels we should get a single label here with the value 1
ImageType::Pointer lungs = labelShapeKeepNObjectsImageFilter2->GetOutput();
ImageType::RegionType lungRegion = lungs->GetLargestPossibleRegion();
itk::ImageRegionIterator<ImageType> lungIterator(lungs, lungRegion);
while (!lungIterator.IsAtEnd()) {
if (lungIterator.Get() > 0) {
lungIterator.Set(1);
}
++lungIterator;
}
//
// and fill holes in the final segmentation of the lung
//
typedef itk::SliceBySliceImageFilter<ImageType, ImageType> SliceFilterImageType;
SliceFilterImageType::Pointer sliceFilter2 = SliceFilterImageType::New();
sliceFilter2->SetInput(labelShapeKeepNObjectsImageFilter2->GetOutput());
typedef itk::BinaryFillholeImageFilter<SliceFilterImageType::InternalInputImageType> HoleFillFilterType2;
HoleFillFilterType2::Pointer holefillfilter2 = HoleFillFilterType2::New();
holefillfilter2->SetForegroundValue(maxValue);
sliceFilter2->SetFilter(holefillfilter2);
sliceFilter2->Update();
// now apply the lung mask to the input image and export that instead
ImageType::Pointer final = sliceFilter2->GetOutput();
ImageType::RegionType imRegion = inputImage->GetLargestPossibleRegion();
ImageType::RegionType maskRegion2 = final->GetLargestPossibleRegion();
itk::ImageRegionIterator<ImageType> imIterator(inputImage, imRegion);
itk::ImageRegionIterator<ImageType> maskIterator2(final, maskRegion2);
MaskImageType::Pointer labelField = MaskImageType::New();
MaskImageType::RegionType labelFieldRegion = inputImage->GetLargestPossibleRegion();
labelField->SetRegions(labelFieldRegion);
labelField->Allocate();
labelField->SetOrigin(inputImage->GetOrigin());
labelField->SetSpacing(inputImage->GetSpacing());
labelField->SetDirection(inputImage->GetDirection());
itk::ImageRegionIterator<MaskImageType> labelFieldIterator(labelField, labelFieldRegion);
// as the background voxel we can use the first voxel overall
int firstVoxel;
bool gotFirstVoxel = false;
size_t numberOfPixel = 0;
while (!imIterator.IsAtEnd() && !maskIterator2.IsAtEnd()) {
if (!gotFirstVoxel) {
gotFirstVoxel = true;
firstVoxel = imIterator.Get();
}
if (maskIterator2.Get() != 0) {
// if (maskIterator.GetIndex()[0] > static_cast<ImageType::IndexValueType>(regionSize[0])
// / 2) {
maskIterator2.Set(imIterator.Get());
labelFieldIterator.Set(1);
numberOfPixel++;
} else {
maskIterator2.Set(firstVoxel); // this depends on the pixel representation its ok
labelFieldIterator.Set(0);
}
++maskIterator2;
++imIterator;
++labelFieldIterator;
}
resultJSON["lung_number_of_voxel"] = numberOfPixel;
// calculate the volume of the lungs
double spacingx = inputImage->GetSpacing()[0];
double spacingy = inputImage->GetSpacing()[1];
double spacingz = inputImage->GetSpacing()[2];
double originx = inputImage->GetOrigin()[0];
double originy = inputImage->GetOrigin()[1];
double originz = inputImage->GetOrigin()[2];
resultJSON["voxel_size"] = json::array();
resultJSON["voxel_size"].push_back(spacingx);
resultJSON["voxel_size"].push_back(spacingy);
resultJSON["voxel_size"].push_back(spacingz);
resultJSON["data_dims"] = json::array();
resultJSON["data_dims"].push_back(inputImage->GetLargestPossibleRegion().GetSize()[0]);
resultJSON["data_dims"].push_back(inputImage->GetLargestPossibleRegion().GetSize()[1]);
resultJSON["data_dims"].push_back(inputImage->GetLargestPossibleRegion().GetSize()[2]);
// in liters
resultJSON["lung_volume"] = numberOfPixel * spacingx * spacingy * spacingz * 1e-6;
// save the label field (one lung)
if (saveLabelField) {
typedef itk::ImageFileWriter<MaskImageType> WriterType;
WriterType::Pointer writer = WriterType::New();
// check if that directory exists, create before writing
path p(labelfieldfilename);
create_directories(p.parent_path());
writer->SetFileName(labelfieldfilename);
writer->SetInput(labelField);
std::cout << "Writing the label field as " << std::endl;
std::cout << labelfieldfilename << std::endl << std::endl;
resultJSON["label_field_filename"] = std::string(labelfieldfilename);
fprintf(stdout, "label field voxel size is: %f %f %f\n", labelField->GetSpacing()[0], labelField->GetSpacing()[1], labelField->GetSpacing()[2]);
// std::string res2 = resultJSON.dump(4) + "\n";
// fprintf(stdout, "%s", res2.c_str());
try {
writer->Update();
} catch (itk::ExceptionObject &ex) {
std::cout << ex << std::endl;
return EXIT_FAILURE;
}
}
// in some slices we have more information, for example if there are only two objects in a
// slice we can assume that we have the left and the right lung. If there are three objects
// the middle one would be the trachae.
// we can also just give up and start computing a lung average image after elastic
// registration that one could be segmented and we take the label from there (if air and over
// average, use label from average).
////////////////////////////////////////////////////////////////////////////////////////////////
// we should now split the lungs into the airways and the lungs using region growing
// for this we need to find out if we have a label in the top image... we should have 3
// regions of interest if we start from the top, we should set a seed point into the middle
// one
using ExtractFilterType = itk::ExtractImageFilter<MaskImageType, MaskImageType>;
ExtractFilterType::Pointer extractFilter = ExtractFilterType::New();
extractFilter->SetDirectionCollapseToSubmatrix();
const MaskImageType *inImage = labelField;
ImageType::RegionType inputRegion = inImage->GetLargestPossibleRegion();
// GetBufferedRegion();
ImageType::SizeType size = inputRegion.GetSize();
unsigned int lastSlice = size[2];
unsigned int sliceNumber = size[2] - 1;
int minRegion = 0;
float minSeedx = 0;
float minSeedy = 0;
int minSeedIdx = 0;
int minSeedIdy = 0;
int minDist = 0;
int sliceSeedStart = 0;
int minNumObjects = 0;
for (; sliceNumber >= 0; sliceNumber--) {
size[2] = 1; // we extract along z direction
ImageType::IndexType start = inputRegion.GetIndex();
start[2] = sliceNumber;
ImageType::RegionType desiredRegion;
desiredRegion.SetSize(size);
desiredRegion.SetIndex(start);
extractFilter->SetExtractionRegion(desiredRegion);
extractFilter->SetInput(inImage);
// Now we can run connected components on the 2D image of the first slice
// we expect 3 distinct regions
ConnectedComponentImageFilterType::Pointer connected3 = ConnectedComponentImageFilterType::New();
connected3->SetBackgroundValue(0);
connected3->SetInput(extractFilter->GetOutput());
connected3->Update();
// using LabelType = unsigned short;
// using ShapeLabelObjectType = itk::ShapeLabelObject< LabelType, 3 >;
// using LabelMapType = itk::LabelMap< ShapeLabelObjectType >;
// using labelType = itk::LabelImageToShapeLabelMapFilter< ImageType, LabelMapType>;
labelType::Pointer labelTmp = labelType::New();
labelTmp->SetInput(connected3->GetOutput());
labelTmp->SetComputePerimeter(true);
labelTmp->Update();
// int useNObjects = 0;
LabelMapType *labelMapTmp = labelTmp->GetOutput();
if (labelMapTmp->GetNumberOfLabelObjects() == 0) {
// error case
fprintf(stderr,
"Look at slice %d, Could not find any object in the data using the current set "
"of thresholds, we can try to start again by "
"lowering the threshold?\n",
sliceNumber);
}
for (unsigned int n = 0; n < labelMapTmp->GetNumberOfLabelObjects(); ++n) {
ShapeLabelObjectType *labelObject = labelMapTmp->GetNthLabelObject(n);
fprintf(stdout, "top slice: object %d has %0.4f liters, %lu voxel\n", n, labelObject->GetPhysicalSize() / 1000000, labelObject->GetNumberOfPixels());
// if (labelObject->GetNumberOfPixels() > 150000) // magick number using sample of 1 -
// should be selected based on volume instead of number of pixel
// useNObjects++;
}
// it might be better to be able to stop early, there are some series with only a single
// lung for those we have to stop at 2. What we could do is stop as well if we are too far
// down in the image stack
if (labelMapTmp->GetNumberOfLabelObjects() == 3 || sliceNumber < 2 * lastSlice / 3) {
sliceSeedStart = sliceNumber;
fprintf(stdout, "found %lu objects in slice %d of %d\n", labelMapTmp->GetNumberOfLabelObjects(), sliceNumber + 1, lastSlice);
// seed point would be in the object that is closest to the center of mass in the image
// The above assumption is sometimes wrong. One of the lungs might be closer to the center of the image.
// Instead we could assume that the lungs are oriented in the same way in all images. That allows us to
// look at a single coordinate and to select the object that is in the middle of the other two objects.
// we could go to the last slice that has 3 objects as well...
// what if we have only one lung? We should detect the diameter of the airways instead..
// something like at least two objects
double spacingx = inputImage->GetSpacing()[0];
double spacingy = inputImage->GetSpacing()[1];
double spacingz = inputImage->GetSpacing()[2];
double originx = inputImage->GetOrigin()[0];
double originy = inputImage->GetOrigin()[1];
double originz = inputImage->GetOrigin()[2];
// what is in the middle in the x-direction? (assumes we have three objects!)
double x1 = labelMapTmp->GetNthLabelObject(0)->GetCentroid()[0];
double x2 = labelMapTmp->GetNthLabelObject(1)->GetCentroid()[0];
double x3 = labelMapTmp->GetNthLabelObject(2)->GetCentroid()[0];
if ((x1 > x2 && x1 < x3) || (x1 > x3 && x1 < x2)) {
// point 0 is the one we are looking for
minDist = 0;
minRegion = 0;
double x = labelMapTmp->GetNthLabelObject(0)->GetCentroid()[0];
double y = labelMapTmp->GetNthLabelObject(0)->GetCentroid()[1];
int seedx = roundf((x - originx) / spacingx);
int seedy = roundf((y - originy) / spacingy);
minSeedx = seedx;
minSeedy = seedy;
minNumObjects = labelMapTmp->GetNumberOfLabelObjects();
} else if ((x2 > x1 && x2 < x3) || (x2 > x3 && x2 < x1)) {
// point 1 is the one we are looking for
minDist = 0;
minRegion = 0;
double x = labelMapTmp->GetNthLabelObject(1)->GetCentroid()[0];
double y = labelMapTmp->GetNthLabelObject(1)->GetCentroid()[1];
int seedx = roundf((x - originx) / spacingx);
int seedy = roundf((y - originy) / spacingy);
minSeedx = seedx;
minSeedy = seedy;
minNumObjects = labelMapTmp->GetNumberOfLabelObjects();
} else {
// point 3 is the one we are looking for
minDist = 0;
minRegion = 0;
double x = labelMapTmp->GetNthLabelObject(2)->GetCentroid()[0];
double y = labelMapTmp->GetNthLabelObject(2)->GetCentroid()[1];
int seedx = roundf((x - originx) / spacingx);
int seedy = roundf((y - originy) / spacingy);
minSeedx = seedx;
minSeedy = seedy;
minNumObjects = labelMapTmp->GetNumberOfLabelObjects();
}
// which one is closest to the center (center of mass)
/*for (unsigned int n = 0; n < labelMapTmp->GetNumberOfLabelObjects(); n++) {
ShapeLabelObjectType *labelObject = labelMapTmp->GetNthLabelObject(n);
double x = labelObject->GetCentroid()[0];
double y = labelObject->GetCentroid()[1];
// fprintf(stdout, "location of object in pixel %d is %f x %f\n", n, x, y);
MaskImageType::RegionType bb = inputRegion;
double spacingx = inputImage->GetSpacing()[0];
double spacingy = inputImage->GetSpacing()[1];
double spacingz = inputImage->GetSpacing()[2];
double originx = inputImage->GetOrigin()[0];
double originy = inputImage->GetOrigin()[1];
double originz = inputImage->GetOrigin()[2];
x = x;
// originx + x *(spacingx);
y = y;
// originy + y *(spacingy);
fprintf(stdout, "location of object in patient space %d is %f x %f\n", n, x, y);
double COMx = originx + (spacingx) * ((size[0] - 1) / 2.0);
double COMy = originy + (spacingy) * ((size[1] - 1) / 2.0);
int seedx = roundf((x - originx) / spacingx);
int seedy = roundf((y - originy) / spacingy);
fprintf(stdout, "%lu %lu %lu, %f %f %f, %f %f %f, center %f %f\n", size[0], size[1], size[2], originx, originy, originz, spacingx, spacingy,
spacingz, COMx, COMy);
double dist = sqrtf((COMx - x) * (COMx - x) + (COMy - y) * (COMy - y));
if (n == 0 || dist < minDist) {
minDist = dist;
minRegion = n;
minSeedx = seedx;
minSeedy = seedy;
minNumObjects = labelMapTmp->GetNumberOfLabelObjects();
}
fprintf(stdout, "object %d is %f far away from center, centroid is at: %d %d\n", n, dist, seedx, seedy);
// inputRegion
} */
break;
}
}
fprintf(stdout, "min object is: %d, seed is at %f %f slice %d\n", minRegion, minSeedx, minSeedy, sliceSeedStart);
resultJSON["trachea_slice_location_pixel"] = json::array();
resultJSON["trachea_slice_location_pixel"].push_back(minSeedx);
resultJSON["trachea_slice_location_pixel"].push_back(minSeedy);
resultJSON["trachea_slice_location_pixel"].push_back(sliceSeedStart);
resultJSON["trachea_slice_number_objects"] = minNumObjects;
resultJSON["trachea_slice_min_region"] = minRegion;
resultJSON["trachea_slice_min_distance"] = minDist;
// before we try to separate the two lungs we should shrink our label again,
// that should help in cases where the trachea touch the lung wall
// if we do this we also have to grow the region again before we do an assignment to tissue
// type
///////////////////////////////////////////////////////////////////////////////
// ok now do a region growing in labelField starting at minSeedx maxSeedy for all voxel that
// have the value 1 we should have a second label field here how do we find neighbors?
MaskImageType::Pointer regionGrowingField = MaskImageType::New();
MaskImageType::RegionType regionGrowingFieldRegion = inputImage->GetLargestPossibleRegion();
regionGrowingField->SetRegions(regionGrowingFieldRegion);
regionGrowingField->Allocate();
regionGrowingField->FillBuffer(itk::NumericTraits<PixelType>::Zero);