]> Creatis software - clitk.git/blob - itk/clitkAddRelativePositionConstraintToLabelImageFilter.txx
itk4 migration
[clitk.git] / itk / clitkAddRelativePositionConstraintToLabelImageFilter.txx
1 /*=========================================================================
2   Program:   vv                     http://www.creatis.insa-lyon.fr/rio/vv
3
4   Authors belong to: 
5   - University of LYON              http://www.universite-lyon.fr/
6   - Léon Bérard cancer center       http://www.centreleonberard.fr
7   - CREATIS CNRS laboratory         http://www.creatis.insa-lyon.fr
8
9   This software is distributed WITHOUT ANY WARRANTY; without even
10   the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
11   PURPOSE.  See the copyright notices for more information.
12
13   It is distributed under dual licence
14
15   - BSD        See included LICENSE.txt file
16   - CeCILL-B   http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
17   ===========================================================================**/
18
19 // clitk
20 #include "clitkCommon.h"
21 #include "clitkBooleanOperatorLabelImageFilter.h"
22 #include "clitkAutoCropFilter.h"
23 #include "clitkResampleImageWithOptionsFilter.h"
24 #include "clitkBooleanOperatorLabelImageFilter.h"
25
26 // itk
27 #include <deque>
28 #include <itkStatisticsLabelMapFilter.h>
29 #include <itkLabelImageToStatisticsLabelMapFilter.h>
30 #include <itkRegionOfInterestImageFilter.h>
31 #include <itkBinaryThresholdImageFilter.h>
32 #include <itkBinaryErodeImageFilter.h>
33 #include <itkBinaryBallStructuringElement.h>
34 #include <itkAddImageFilter.h>
35 #if ITK_VERSION_MAJOR >= 4
36   #include <itkDivideImageFilter.h>
37 #else
38   #include <itkDivideByConstantImageFilter.h>
39 #endif
40
41 // itk [Bloch et al] 
42 #include "RelativePositionPropImageFilter.h"
43
44 //--------------------------------------------------------------------
45 template <class ImageType>
46 clitk::AddRelativePositionConstraintToLabelImageFilter<ImageType>::
47 AddRelativePositionConstraintToLabelImageFilter():
48   clitk::FilterBase(),
49   itk::ImageToImageFilter<ImageType, ImageType>()
50 {
51   this->SetNumberOfRequiredInputs(2);
52   SetFuzzyThreshold(0.6);
53   SetBackgroundValue(0);
54   SetObjectBackgroundValue(0);
55   ClearOrientationType();
56   IntermediateSpacingFlagOn();
57   SetIntermediateSpacing(10);
58   AutoCropFlagOn();
59   InverseOrientationFlagOff();
60   RemoveObjectFlagOn();
61   CombineWithOrFlagOff();
62   VerboseStepFlagOff();
63   WriteStepFlagOff();
64 }
65 //--------------------------------------------------------------------
66
67
68 //--------------------------------------------------------------------
69 template <class ImageType>
70 void 
71 clitk::AddRelativePositionConstraintToLabelImageFilter<ImageType>::
72 SetInput(const ImageType * image) 
73 {
74   // Process object is not const-correct so the const casting is required.
75   this->SetNthInput(0, const_cast<ImageType *>(image));
76 }
77 //--------------------------------------------------------------------
78   
79
80 //--------------------------------------------------------------------
81 template <class ImageType>
82 void 
83 clitk::AddRelativePositionConstraintToLabelImageFilter<ImageType>::
84 SetInputObject(const ImageType * image) 
85 {
86   // Process object is not const-correct so the const casting is required.
87   this->SetNthInput(1, const_cast<ImageType *>(image));
88 }
89 //--------------------------------------------------------------------
90   
91
92 //--------------------------------------------------------------------
93 template <class ImageType>
94 void 
95 clitk::AddRelativePositionConstraintToLabelImageFilter<ImageType>::
96 ClearOrientationType() 
97 {
98   m_OrientationTypeString.clear();
99   m_OrientationType.clear();
100   m_Angle1.clear();
101   m_Angle2.clear();
102 }
103 //--------------------------------------------------------------------
104
105
106 //--------------------------------------------------------------------
107 template <class ImageType>
108 int
109 clitk::AddRelativePositionConstraintToLabelImageFilter<ImageType>::
110 GetNumberOfAngles()
111 {
112   return m_OrientationType.size();
113 }
114 //--------------------------------------------------------------------
115
116
117 //--------------------------------------------------------------------
118 template <class ImageType>
119 void 
120 clitk::AddRelativePositionConstraintToLabelImageFilter<ImageType>::
121 AddOrientationTypeString(std::string t) 
122 {
123   m_OrientationTypeString.push_back(t);
124   switch (t[0]) {
125   case 'L' : AddOrientationType(AtLeftTo); break;
126   case 'R' : AddOrientationType(AtRightTo);break;
127   case 'A' : AddOrientationType(AntTo);break;
128   case 'P' : AddOrientationType(PostTo);break;
129   case 'S' : AddOrientationType(SupTo);break;
130   case 'I' : AddOrientationType(InfTo);break;
131   case 'N': 
132     if (t == "NotLeftTo") { AddOrientationType(AtLeftTo); InverseOrientationFlagOn(); break; }
133     if (t == "NotRightTo") { AddOrientationType(AtRightTo); InverseOrientationFlagOn(); break; }
134     if (t == "NotAntTo") { AddOrientationType(AntTo); InverseOrientationFlagOn(); break; }
135     if (t == "NotPostTo") { AddOrientationType(PostTo); InverseOrientationFlagOn(); break; }
136     if (t == "NotSupTo") { AddOrientationType(SupTo); InverseOrientationFlagOn(); break; }
137     if (t == "NotInfTo") { AddOrientationType(InfTo); InverseOrientationFlagOn(); break; }
138   default: clitkExceptionMacro("Error, you must provide L,R or A,P or S,I (or NotLeftTo, NotRightTo etc)");
139   }
140 }
141 //--------------------------------------------------------------------
142   
143
144 //--------------------------------------------------------------------
145 template <class ImageType>
146 void 
147 clitk::AddRelativePositionConstraintToLabelImageFilter<ImageType>::
148 GenerateOutputInformation() 
149
150   ImagePointer input = dynamic_cast<ImageType*>(itk::ProcessObject::GetInput(0));
151   ImagePointer outputImage = this->GetOutput(0);
152   outputImage->SetRegions(outputImage->GetLargestPossibleRegion());
153 }
154 //--------------------------------------------------------------------
155
156
157 //--------------------------------------------------------------------
158 template <class ImageType>
159 void 
160 clitk::AddRelativePositionConstraintToLabelImageFilter<ImageType>::
161 GenerateInputRequestedRegion() 
162 {
163   // Call default
164   itk::ImageToImageFilter<ImageType, ImageType>::GenerateInputRequestedRegion();
165   // Get input pointers and set requested region to common region
166   ImagePointer input1 = dynamic_cast<ImageType*>(itk::ProcessObject::GetInput(0));
167   ImagePointer input2 = dynamic_cast<ImageType*>(itk::ProcessObject::GetInput(1));
168   input1->SetRequestedRegion(input1->GetLargestPossibleRegion());
169   input2->SetRequestedRegion(input2->GetLargestPossibleRegion());
170 }
171 //--------------------------------------------------------------------
172
173   
174 //--------------------------------------------------------------------
175 template <class ImageType>
176 void 
177 clitk::AddRelativePositionConstraintToLabelImageFilter<ImageType>::
178 AddAngles(double a, double b) 
179 {
180   AddOrientationTypeString("Angle");
181   m_Angle1.push_back(a);
182   m_Angle2.push_back(b);
183 }
184 //--------------------------------------------------------------------
185
186
187 //--------------------------------------------------------------------
188 template <class ImageType>
189 void 
190 clitk::AddRelativePositionConstraintToLabelImageFilter<ImageType>::
191 AddOrientationType(OrientationTypeEnumeration orientation) 
192 {
193   m_OrientationType.push_back(orientation);
194   switch (orientation) {
195   case AtRightTo:   
196     m_Angle1.push_back(clitk::deg2rad(0));   
197     m_Angle2.push_back(clitk::deg2rad(0));
198     break;
199   case AtLeftTo:  
200     m_Angle1.push_back(clitk::deg2rad(180)); 
201     m_Angle2.push_back(clitk::deg2rad(0));
202     break;
203   case AntTo:
204     m_Angle1.push_back(clitk::deg2rad(90));
205     m_Angle2.push_back(clitk::deg2rad(0));
206     break;
207   case PostTo:
208     m_Angle1.push_back(clitk::deg2rad(-90)); 
209     m_Angle2.push_back(clitk::deg2rad(0));
210     break;
211   case InfTo:    
212     m_Angle1.push_back(clitk::deg2rad(0));   
213     m_Angle2.push_back(clitk::deg2rad(90));
214     break;
215   case SupTo:    
216     m_Angle1.push_back(clitk::deg2rad(0));   
217     m_Angle2.push_back(clitk::deg2rad(-90));
218     break;
219   case Angle:  break;
220   }
221   /*         A1   A2
222              Left      0    0
223              Right   180    0
224              Ant      90    0
225              Post    -90    0
226              Inf       0   90
227              Sup       0  -90
228   */
229 }
230 //--------------------------------------------------------------------
231
232
233 //--------------------------------------------------------------------
234 template <class ImageType>
235 void 
236 clitk::AddRelativePositionConstraintToLabelImageFilter<ImageType>::
237 GenerateData() 
238 {
239   if (GetNumberOfAngles() <1) {
240     clitkExceptionMacro("Add at least one orientation type");
241   }  
242
243   // Get input pointer
244   input = dynamic_cast<ImageType*>(itk::ProcessObject::GetInput(0));
245   object = dynamic_cast<ImageType*>(itk::ProcessObject::GetInput(1));
246   static const unsigned int dim = ImageType::ImageDimension;
247
248   // Step 2: object pad to input image -> we want to compute the
249   // relative position for each point belonging to the input image
250   // domain, so we have to extend (pad) the object image to fit the
251   // domain size
252   working_image = object;
253   if (!clitk::HaveSameSizeAndSpacing<ImageType, ImageType>(input, working_image)) {
254     StartNewStep("Pad (resize) object to input size");  
255
256     if (0) { // OLD VERSION (TO REMOVE)
257       StartNewStep("Pad object to image size");  
258       typename ImageType::Pointer output = ImageType::New();
259       SizeType size;
260       for(unsigned int i=0; i<dim; i++) {
261         size[i] = lrint((input->GetLargestPossibleRegion().GetSize()[i]*
262                          input->GetSpacing()[i])/(double)working_image->GetSpacing()[i]);
263       }
264
265       // The index of the input is not necessarily zero, so we have to
266       // take it into account (not done)
267       RegionType region;
268       IndexType index = input->GetLargestPossibleRegion().GetIndex();
269       region.SetSize(size);
270       for(unsigned int i=0; i<dim; i++) {
271         if (index[i] != 0) {
272           std::cerr << "Index diff from zero : " << index << ". not done yet !" << std::endl;
273           exit(0);
274         }
275       }
276       // output->SetLargestPossibleRegion(region);
277       output->SetRegions(region);
278       output->SetSpacing(working_image->GetSpacing());    
279       PointType origin = input->GetOrigin();
280       for(unsigned int i=0; i<dim; i++) {
281         origin[i] = index[i]*input->GetSpacing()[i] + input->GetOrigin()[i];
282       }
283       output->SetOrigin(origin);
284       //    output->SetOrigin(input->GetOrigin());
285
286       output->Allocate();
287       output->FillBuffer(m_BackgroundValue);
288       typename PasteFilterType::Pointer padFilter = PasteFilterType::New();
289       // typename PasteFilterType::InputImageIndexType index;
290       for(unsigned int i=0; i<dim; i++) {
291         index[i] = -index[i]*input->GetSpacing()[i]/(double)working_image->GetSpacing()[i]
292           + lrint((working_image->GetOrigin()[i] - input->GetOrigin()[i])/working_image->GetSpacing()[i]);
293       }
294       padFilter->SetSourceImage(working_image);
295       padFilter->SetDestinationImage(output);
296       padFilter->SetDestinationIndex(index);
297       padFilter->SetSourceRegion(working_image->GetLargestPossibleRegion());
298       padFilter->Update();
299       working_image = padFilter->GetOutput();
300     }
301
302     // Resize object like input
303     working_image = clitk::ResizeImageLike<ImageType>(working_image, input, GetBackgroundValue());
304     StopCurrentStep<ImageType>(working_image);
305   }
306
307   //--------------------------------------------------------------------
308   //--------------------------------------------------------------------
309   // Step 1 : resample
310   if (m_IntermediateSpacingFlag) {
311     StartNewStep("Resample object to intermediate spacing");  
312     typedef clitk::ResampleImageWithOptionsFilter<ImageType> ResampleFilterType;
313     typename ResampleFilterType::Pointer resampleFilter = ResampleFilterType::New();
314     resampleFilter->SetInput(working_image);
315     resampleFilter->SetDefaultPixelValue(0);
316     resampleFilter->SetOutputIsoSpacing(m_IntermediateSpacing);
317     resampleFilter->SetGaussianFilteringEnabled(false);
318     //    resampleFilter->SetVerboseOptions(true);
319     resampleFilter->Update();
320     working_image = resampleFilter->GetOutput();
321     StopCurrentStep<ImageType>(working_image);
322   }
323
324   // Keep object image (with resampline and pad)
325   object_resampled = working_image;
326
327   // Step 3: compute rel pos in object
328   StartNewStep("Relative Position Map");  
329   typedef itk::RelativePositionPropImageFilter<ImageType, FloatImageType> RelPosFilterType;
330   typename RelPosFilterType::Pointer relPosFilter;
331
332   typename FloatImageType::Pointer m_FuzzyMap;
333   for(int i=0; i<GetNumberOfAngles(); i++) {
334     // Compute fuzzy map
335     relPosFilter = RelPosFilterType::New();
336     relPosFilter->SetInput(working_image);
337     relPosFilter->SetAlpha1(m_Angle1[i]); // xy plane
338     relPosFilter->SetAlpha2(m_Angle2[i]);
339     relPosFilter->SetK1(M_PI/2.0); // Opening parameter, default = pi/2
340     relPosFilter->SetFast(true);
341     relPosFilter->SetRadius(1); // seems sufficient in this case
342     // relPosFilter->SetVerboseProgress(true);
343     relPosFilter->Update();
344     relPos = relPosFilter->GetOutput();
345
346     if (GetNumberOfAngles() != 1) {
347       // Creation of the first m_FuzzyMap
348       if (i==0) {
349         m_FuzzyMap = clitk::NewImageLike<FloatImageType>(relPos, true);
350         m_FuzzyMap->FillBuffer(0.0);
351       }
352       
353       // Add to current fuzzy map
354       typedef itk::AddImageFilter<FloatImageType, FloatImageType, FloatImageType> AddImageFilter;
355       typename AddImageFilter::Pointer addFilter = AddImageFilter::New();
356       addFilter->SetInput1(m_FuzzyMap);
357       addFilter->SetInput2(relPos);
358       addFilter->Update();
359       m_FuzzyMap = addFilter->GetOutput();
360     }
361     else m_FuzzyMap = relPos;
362   }
363
364   // Divide by the number of relpos
365   if (GetNumberOfAngles() != 1) {
366 #if ITK_VERSION_MAJOR >= 4
367     typedef itk::DivideImageFilter<FloatImageType, FloatImageType, FloatImageType> DivideFilter;
368     typename DivideFilter::Pointer divideFilter = DivideFilter::New();
369     divideFilter->SetConstant2(GetNumberOfAngles());
370 #else
371     typedef itk::DivideByConstantImageFilter<FloatImageType, float, FloatImageType> DivideFilter;
372     typename DivideFilter::Pointer divideFilter = DivideFilter::New();
373     divideFilter->SetConstant(GetNumberOfAngles());
374 #endif
375     divideFilter->SetInput(m_FuzzyMap);
376     divideFilter->Update();
377     m_FuzzyMap = divideFilter->GetOutput();
378   }
379
380   relPos = m_FuzzyMap;
381   StopCurrentStep<FloatImageType>(relPos);
382                
383   //--------------------------------------------------------------------
384   //--------------------------------------------------------------------
385   StartNewStep("Map Threshold");
386   // Step 1: threshold
387   typedef itk::BinaryThresholdImageFilter<FloatImageType, ImageType> BinaryThresholdImageFilterType;
388   typename BinaryThresholdImageFilterType::Pointer thresholdFilter = BinaryThresholdImageFilterType::New();
389   thresholdFilter->SetInput(relPos);
390   thresholdFilter->SetOutsideValue(m_BackgroundValue);
391   thresholdFilter->SetInsideValue(m_BackgroundValue+1);
392   thresholdFilter->SetLowerThreshold(m_FuzzyThreshold);
393   thresholdFilter->Update();
394   working_image = thresholdFilter->GetOutput();
395   StopCurrentStep<ImageType>(working_image);
396
397   //--------------------------------------------------------------------
398   //--------------------------------------------------------------------
399   StartNewStep("Post Processing: erosion with initial mask");
400   // Step 2 : erosion with initial mask to exclude pixels that were
401   // inside the resampled version and outside the original mask
402   typedef itk::BinaryBallStructuringElement<unsigned int, ImageDimension> StructuringElementType; 
403   StructuringElementType kernel;
404   kernel.SetRadius(1);
405   kernel.CreateStructuringElement();
406   typedef itk::BinaryErodeImageFilter<ImageType, ImageType, StructuringElementType> ErodeFilterType;
407   typename ErodeFilterType::Pointer erodeFilter = ErodeFilterType::New();
408   erodeFilter->SetInput(working_image);
409   erodeFilter->SetKernel(kernel);
410   erodeFilter->SetBackgroundValue(m_BackgroundValue);
411   erodeFilter->SetErodeValue(m_BackgroundValue+1);
412   erodeFilter->Update();
413   working_image = erodeFilter->GetOutput();
414   StopCurrentStep<ImageType>(working_image);
415
416   //--------------------------------------------------------------------
417   //--------------------------------------------------------------------
418   // Step 5: resample to initial spacing
419   if (m_IntermediateSpacingFlag) {
420     StartNewStep("Resample to come back to the same sampling than input");
421     typedef clitk::ResampleImageWithOptionsFilter<ImageType> ResampleFilterType;
422     typename ResampleFilterType::Pointer resampleFilter = ResampleFilterType::New();
423     resampleFilter->SetDefaultPixelValue(m_BackgroundValue);
424     resampleFilter->SetInput(working_image);
425     resampleFilter->SetOutputSpacing(input->GetSpacing());
426     resampleFilter->SetGaussianFilteringEnabled(false);
427     // resampleFilter->SetVerboseOptions(true);
428     resampleFilter->Update();
429     working_image = resampleFilter->GetOutput();
430     StopCurrentStep<ImageType>(working_image);
431   }
432
433   //--------------------------------------------------------------------
434   //--------------------------------------------------------------------
435   // Pre Step 6: pad if not the same size : it can occur when downsample and upsample
436   //if (!HaveSameSizeAndSpacing(working_image, input)) {
437   if (working_image->GetLargestPossibleRegion() != input->GetLargestPossibleRegion()) {
438     StartNewStep("Pad to get the same size than input");
439     typename ImageType::Pointer temp = ImageType::New();
440     temp->CopyInformation(input);
441     temp->SetRegions(input->GetLargestPossibleRegion()); // Do not forget !!
442     temp->Allocate();
443     temp->FillBuffer(m_BackgroundValue); 
444     typename PasteFilterType::Pointer padFilter2 = PasteFilterType::New();
445     padFilter2->SetSourceImage(working_image);
446     padFilter2->SetDestinationImage(temp);
447     padFilter2->SetDestinationIndex(input->GetLargestPossibleRegion().GetIndex());
448     padFilter2->SetSourceRegion(working_image->GetLargestPossibleRegion());
449     padFilter2->Update();
450     working_image = padFilter2->GetOutput();
451     StopCurrentStep<ImageType>(working_image);
452   }
453   else {
454     //DD("[debug] Rel Pos : no padding after");
455   }
456
457   //--------------------------------------------------------------------
458   //--------------------------------------------------------------------
459   // Step 6: combine input+thresholded relpos
460   StartNewStep("Combine with initial input (boolean And)");
461   typedef clitk::BooleanOperatorLabelImageFilter<ImageType> BoolFilterType;
462   typename BoolFilterType::Pointer combineFilter = BoolFilterType::New();
463   combineFilter->SetBackgroundValue(m_BackgroundValue);
464   combineFilter->SetBackgroundValue1(m_BackgroundValue);
465   combineFilter->SetBackgroundValue2(m_BackgroundValue);
466   combineFilter->SetForegroundValue(m_BackgroundValue+1);
467   combineFilter->SetInput1(input);
468   combineFilter->SetInput2(working_image);
469   if (GetInverseOrientationFlag())
470     combineFilter->SetOperationType(BoolFilterType::AndNot);
471   else {
472     if (GetCombineWithOrFlag())
473       combineFilter->SetOperationType(BoolFilterType::Or);
474     else
475       combineFilter->SetOperationType(BoolFilterType::And);
476   }
477   combineFilter->InPlaceOff(); // Do not modify initial input (!)
478   combineFilter->Update(); 
479   working_image = combineFilter->GetOutput();
480
481   // Remove (if needed the object from the support)
482   if (GetRemoveObjectFlag()) {
483     combineFilter = BoolFilterType::New();
484     combineFilter->SetInput1(working_image);
485     combineFilter->SetInput2(object);
486     combineFilter->SetOperationType(BoolFilterType::AndNot);
487     combineFilter->InPlaceOn();
488     combineFilter->Update(); 
489     working_image = combineFilter->GetOutput();
490   }
491   // In the other case, we must *add* the initial object to keep it
492   // but not more than the initial support
493   else { 
494     combineFilter = BoolFilterType::New();
495     combineFilter->SetInput1(working_image);
496     combineFilter->SetInput2(object);
497     combineFilter->SetOperationType(BoolFilterType::Or);
498     combineFilter->InPlaceOn();
499     combineFilter->Update(); 
500     working_image = combineFilter->GetOutput(); // not needed because InPlaceOn ?
501     combineFilter = BoolFilterType::New();
502     combineFilter->SetInput1(working_image);
503     combineFilter->SetInput2(input);
504     combineFilter->SetOperationType(BoolFilterType::And);
505     combineFilter->InPlaceOn();
506     combineFilter->Update(); 
507     working_image = combineFilter->GetOutput();
508   }
509
510   StopCurrentStep<ImageType>(working_image);
511
512   //--------------------------------------------------------------------
513   //--------------------------------------------------------------------
514   // Step 7: autocrop
515   if (GetAutoCropFlag()) {
516     StartNewStep("Final AutoCrop");
517     typedef clitk::AutoCropFilter<ImageType> CropFilterType;
518     typename CropFilterType::Pointer cropFilter = CropFilterType::New();
519     cropFilter->SetInput(working_image);
520     cropFilter->ReleaseDataFlagOff();
521     cropFilter->Update();   
522     working_image = cropFilter->GetOutput();
523     StopCurrentStep<ImageType>(working_image);
524   }
525
526   //--------------------------------------------------------------------
527   //--------------------------------------------------------------------
528   
529   // Final Step -> set output
530   this->SetNthOutput(0, working_image);
531   //  this->GraftOutput(working_image);
532 }
533 //--------------------------------------------------------------------
534