]> Creatis software - clitk.git/blob - itk/clitkSegmentationUtils.txx
Merge branch 'master' of git.creatis.insa-lyon.fr:clitk
[clitk.git] / itk / clitkSegmentationUtils.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 "clitkSetBackgroundImageFilter.h"
21 #include "clitkSliceBySliceRelativePositionFilter.h"
22 #include "clitkCropLikeImageFilter.h"
23 #include "clitkMemoryUsage.h"
24
25 // itk
26 #include <itkConnectedComponentImageFilter.h>
27 #include <itkRelabelComponentImageFilter.h>
28 #include <itkBinaryThresholdImageFilter.h>
29 #include <itkPasteImageFilter.h>
30 #include <itkStatisticsLabelMapFilter.h>
31 #include <itkBinaryBallStructuringElement.h>
32 #include <itkBinaryDilateImageFilter.h>
33 #include <itkConstantPadImageFilter.h>
34 #include <itkImageSliceIteratorWithIndex.h>
35 #include <itkBinaryMorphologicalOpeningImageFilter.h>
36 #include <itkImageDuplicator.h>
37 #include <itkSignedMaurerDistanceMapImageFilter.h>
38
39 namespace clitk {
40
41   //--------------------------------------------------------------------
42   template<class ImageType, class TMaskImageType>
43   typename ImageType::Pointer
44   SetBackground(const ImageType * input, 
45                 const TMaskImageType * mask, 
46                 typename TMaskImageType::PixelType maskBG,
47                 typename ImageType::PixelType outValue, 
48                 bool inPlace) {
49     typedef SetBackgroundImageFilter<ImageType, TMaskImageType, ImageType> 
50       SetBackgroundImageFilterType;
51     typename SetBackgroundImageFilterType::Pointer setBackgroundFilter 
52       = SetBackgroundImageFilterType::New();
53     //  if (inPlace) setBackgroundFilter->ReleaseDataFlagOn(); // No seg fault
54     setBackgroundFilter->SetInPlace(inPlace); // This is important to keep memory low
55     setBackgroundFilter->SetInput(input);
56     setBackgroundFilter->SetInput2(mask);
57     setBackgroundFilter->SetMaskValue(maskBG);
58     setBackgroundFilter->SetOutsideValue(outValue);
59     setBackgroundFilter->Update();
60     return setBackgroundFilter->GetOutput();
61   }
62   //--------------------------------------------------------------------
63
64
65   //--------------------------------------------------------------------
66   template<class ImageType>
67   int GetNumberOfConnectedComponentLabels(const ImageType * input, 
68                                           typename ImageType::PixelType BG, 
69                                           bool isFullyConnected) {
70     // Connected Component label 
71     typedef itk::ConnectedComponentImageFilter<ImageType, ImageType> ConnectFilterType;
72     typename ConnectFilterType::Pointer connectFilter = ConnectFilterType::New();
73     connectFilter->SetInput(input);
74     connectFilter->SetBackgroundValue(BG);
75     connectFilter->SetFullyConnected(isFullyConnected);
76     connectFilter->Update();
77   
78     // Return result
79     return connectFilter->GetObjectCount();
80   }
81   //--------------------------------------------------------------------
82
83   //--------------------------------------------------------------------
84   /*
85     Warning : in this cas, we consider outputType like inputType, not
86     InternalImageType. Be sure it fits.
87   */
88   template<class ImageType>
89   typename ImageType::Pointer
90   Labelize(const ImageType * input, 
91            typename ImageType::PixelType BG, 
92            bool isFullyConnected, 
93            int minimalComponentSize) {
94     // InternalImageType for storing large number of component
95     typedef itk::Image<int, ImageType::ImageDimension> InternalImageType;
96   
97     // Connected Component label 
98     typedef itk::ConnectedComponentImageFilter<ImageType, InternalImageType> ConnectFilterType;
99     typename ConnectFilterType::Pointer connectFilter = ConnectFilterType::New();
100     //  connectFilter->ReleaseDataFlagOn(); 
101     connectFilter->SetInput(input);
102     connectFilter->SetBackgroundValue(BG);
103     connectFilter->SetFullyConnected(isFullyConnected);
104   
105     // Sort by size and remove too small area.
106     typedef itk::RelabelComponentImageFilter<InternalImageType, ImageType> RelabelFilterType;
107     typename RelabelFilterType::Pointer relabelFilter = RelabelFilterType::New();
108     //  relabelFilter->ReleaseDataFlagOn(); // if yes, fail when ExplosionControlledThresholdConnectedImageFilter ???
109     relabelFilter->SetInput(connectFilter->GetOutput());
110     relabelFilter->SetMinimumObjectSize(minimalComponentSize);
111     relabelFilter->Update();
112
113     // Return result
114     typename ImageType::Pointer output = relabelFilter->GetOutput();
115     return output;
116   }
117   //--------------------------------------------------------------------
118
119
120   //--------------------------------------------------------------------
121   /*
122     Warning : in this cas, we consider outputType like inputType, not
123     InternalImageType. Be sure it fits.
124   */
125   template<class ImageType>
126   typename ImageType::Pointer
127   LabelizeAndCountNumberOfObjects(const ImageType * input, 
128                                   typename ImageType::PixelType BG, 
129                                   bool isFullyConnected, 
130                                   int minimalComponentSize, 
131                                   int & nb) {
132     // InternalImageType for storing large number of component
133     typedef itk::Image<int, ImageType::ImageDimension> InternalImageType;
134   
135     // Connected Component label 
136     typedef itk::ConnectedComponentImageFilter<ImageType, InternalImageType> ConnectFilterType;
137     typename ConnectFilterType::Pointer connectFilter = ConnectFilterType::New();
138     //  connectFilter->ReleaseDataFlagOn(); 
139     connectFilter->SetInput(input);
140     connectFilter->SetBackgroundValue(BG);
141     connectFilter->SetFullyConnected(isFullyConnected);
142   
143     // Sort by size and remove too small area.
144     typedef itk::RelabelComponentImageFilter<InternalImageType, ImageType> RelabelFilterType;
145     typename RelabelFilterType::Pointer relabelFilter = RelabelFilterType::New();
146     //  relabelFilter->ReleaseDataFlagOn(); // if yes, fail when ExplosionControlledThresholdConnectedImageFilter ???
147     relabelFilter->SetInput(connectFilter->GetOutput());
148     relabelFilter->SetMinimumObjectSize(minimalComponentSize);
149     relabelFilter->Update();
150
151     nb = relabelFilter->GetNumberOfObjects();
152     // DD(relabelFilter->GetOriginalNumberOfObjects());
153     // DD(relabelFilter->GetSizeOfObjectsInPhysicalUnits()[0]);
154
155     // Return result
156     typename ImageType::Pointer output = relabelFilter->GetOutput();
157     return output;
158   }
159   //--------------------------------------------------------------------
160
161
162
163   //--------------------------------------------------------------------
164   template<class ImageType>
165   typename ImageType::Pointer
166   RemoveLabels(const ImageType * input, 
167                typename ImageType::PixelType BG,
168                std::vector<typename ImageType::PixelType> & labelsToRemove) {
169     assert(labelsToRemove.size() != 0);
170     typename ImageType::Pointer working_image;// = input;
171     for (unsigned int i=0; i <labelsToRemove.size(); i++) {
172       typedef SetBackgroundImageFilter<ImageType, ImageType> SetBackgroundImageFilterType;
173       typename SetBackgroundImageFilterType::Pointer setBackgroundFilter = SetBackgroundImageFilterType::New();
174       setBackgroundFilter->SetInput(input);
175       setBackgroundFilter->SetInput2(input);
176       setBackgroundFilter->SetMaskValue(labelsToRemove[i]);
177       setBackgroundFilter->SetOutsideValue(BG);
178       setBackgroundFilter->Update();
179       working_image = setBackgroundFilter->GetOutput();
180     }
181     return working_image;
182   }
183   //--------------------------------------------------------------------
184
185
186   //--------------------------------------------------------------------
187   template<class ImageType>
188   typename ImageType::Pointer
189   KeepLabels(const ImageType * input, 
190              typename ImageType::PixelType BG, 
191              typename ImageType::PixelType FG, 
192              typename ImageType::PixelType firstKeep, 
193              typename ImageType::PixelType lastKeep, 
194              bool useLastKeep) {
195     typedef itk::BinaryThresholdImageFilter<ImageType, ImageType> BinarizeFilterType; 
196     typename BinarizeFilterType::Pointer binarizeFilter = BinarizeFilterType::New();
197     binarizeFilter->SetInput(input);
198     binarizeFilter->SetLowerThreshold(firstKeep);
199     if (useLastKeep) binarizeFilter->SetUpperThreshold(lastKeep);
200     binarizeFilter->SetInsideValue(FG);
201     binarizeFilter->SetOutsideValue(BG);
202     binarizeFilter->Update();
203     return binarizeFilter->GetOutput();
204   }
205   //--------------------------------------------------------------------
206
207
208   //--------------------------------------------------------------------
209   template<class ImageType>
210   typename ImageType::Pointer
211   LabelizeAndSelectLabels(const ImageType * input,
212                           typename ImageType::PixelType BG, 
213                           typename ImageType::PixelType FG, 
214                           bool isFullyConnected,
215                           int minimalComponentSize,
216                           LabelizeParameters<typename ImageType::PixelType> * param)
217   {
218     typename ImageType::Pointer working_image;
219     working_image = Labelize<ImageType>(input, BG, isFullyConnected, minimalComponentSize);
220     if (param->GetLabelsToRemove().size() != 0)
221       working_image = RemoveLabels<ImageType>(working_image, BG, param->GetLabelsToRemove());
222     working_image = KeepLabels<ImageType>(working_image, 
223                                           BG, FG, 
224                                           param->GetFirstKeep(), 
225                                           param->GetLastKeep(), 
226                                           param->GetUseLastKeep());
227     return working_image;
228   }
229   //--------------------------------------------------------------------
230
231
232   //--------------------------------------------------------------------
233   template<class MaskImageType>
234   typename MaskImageType::Pointer
235   SliceBySliceRelativePosition(const MaskImageType * input,
236                                const MaskImageType * object,
237                                int direction, 
238                                double threshold, 
239                                std::string orientation, 
240                                bool uniqueConnectedComponent, 
241                                double spacing, 
242                                bool autocropFlag, 
243                                bool singleObjectCCL) 
244   {
245     typedef clitk::SliceBySliceRelativePositionFilter<MaskImageType> SliceRelPosFilterType;
246     typename SliceRelPosFilterType::Pointer sliceRelPosFilter = SliceRelPosFilterType::New();
247     sliceRelPosFilter->VerboseStepFlagOff();
248     sliceRelPosFilter->WriteStepFlagOff();
249     sliceRelPosFilter->SetInput(input);
250     sliceRelPosFilter->SetInputObject(object);
251     sliceRelPosFilter->SetDirection(direction);
252     sliceRelPosFilter->SetFuzzyThreshold(threshold);
253     sliceRelPosFilter->AddOrientationTypeString(orientation);
254     sliceRelPosFilter->SetIntermediateSpacingFlag((spacing != -1));
255     sliceRelPosFilter->SetIntermediateSpacing(spacing);
256     sliceRelPosFilter->SetUniqueConnectedComponentBySliceFlag(uniqueConnectedComponent);
257     sliceRelPosFilter->ObjectCCLSelectionFlagOff();
258     sliceRelPosFilter->SetUseTheLargestObjectCCLFlag(singleObjectCCL);
259     //    sliceRelPosFilter->SetInverseOrientationFlag(inverseflag); 
260     sliceRelPosFilter->SetAutoCropFlag(autocropFlag); 
261     sliceRelPosFilter->IgnoreEmptySliceObjectFlagOn();
262     sliceRelPosFilter->Update();
263     return sliceRelPosFilter->GetOutput();
264   }
265   //--------------------------------------------------------------------
266
267
268   //--------------------------------------------------------------------
269   template<class MaskImageType>
270   typename MaskImageType::Pointer
271   SliceBySliceRelativePosition(const MaskImageType * input,
272                                const MaskImageType * object,
273                                int direction, 
274                                double threshold, 
275                                double angle,
276                                bool inverseflag,
277                                bool uniqueConnectedComponent, 
278                                double spacing, 
279                                bool autocropFlag, 
280                                bool singleObjectCCL) 
281   {
282     typedef clitk::SliceBySliceRelativePositionFilter<MaskImageType> SliceRelPosFilterType;
283     typename SliceRelPosFilterType::Pointer sliceRelPosFilter = SliceRelPosFilterType::New();
284     sliceRelPosFilter->VerboseStepFlagOff();
285     sliceRelPosFilter->WriteStepFlagOff();
286     sliceRelPosFilter->SetInput(input);
287     sliceRelPosFilter->SetInputObject(object);
288     sliceRelPosFilter->SetDirection(direction);
289     sliceRelPosFilter->SetFuzzyThreshold(threshold);
290     //    sliceRelPosFilter->AddOrientationTypeString(orientation);
291     sliceRelPosFilter->AddAnglesInRad(angle, 0.0);
292     sliceRelPosFilter->SetIntermediateSpacingFlag((spacing != -1));
293     sliceRelPosFilter->SetIntermediateSpacing(spacing);
294     sliceRelPosFilter->SetUniqueConnectedComponentBySliceFlag(uniqueConnectedComponent);
295     sliceRelPosFilter->ObjectCCLSelectionFlagOff();
296     sliceRelPosFilter->SetUseTheLargestObjectCCLFlag(singleObjectCCL);
297     sliceRelPosFilter->SetInverseOrientationFlag(inverseflag); 
298     sliceRelPosFilter->SetAutoCropFlag(autocropFlag); 
299     sliceRelPosFilter->IgnoreEmptySliceObjectFlagOn();
300     sliceRelPosFilter->Update();
301     return sliceRelPosFilter->GetOutput();
302   }
303   //--------------------------------------------------------------------
304
305
306   //--------------------------------------------------------------------
307   template<class ImageType>
308   bool
309   FindExtremaPointInAGivenDirection(const ImageType * input, 
310                                     typename ImageType::PixelType bg, 
311                                     int direction, bool opposite, 
312                                     typename ImageType::PointType & point)
313   {
314     typename ImageType::PointType dummy;
315     return FindExtremaPointInAGivenDirection(input, bg, direction, 
316                                              opposite, dummy, 0, point);
317   }
318   //--------------------------------------------------------------------
319
320
321   //--------------------------------------------------------------------
322   template<class ImageType>
323   bool
324   FindExtremaPointInAGivenDirection(const ImageType * input, 
325                                     typename ImageType::PixelType bg, 
326                                     int direction, bool opposite, 
327                                     typename ImageType::PointType refpoint,
328                                     double distanceMax, 
329                                     typename ImageType::PointType & point)
330   {
331     /*
332       loop over input pixels, store the index in the fg that is max
333       according to the given direction. 
334     */    
335     typedef itk::ImageRegionConstIteratorWithIndex<ImageType> IteratorType;
336     IteratorType iter(input, input->GetLargestPossibleRegion());
337     iter.GoToBegin();
338     typename ImageType::IndexType max = input->GetLargestPossibleRegion().GetIndex();
339     if (opposite) max = max+input->GetLargestPossibleRegion().GetSize();
340     bool found=false;
341     while (!iter.IsAtEnd()) {
342       if (iter.Get() != bg) {
343         bool test = iter.GetIndex()[direction] >  max[direction];
344         if (opposite) test = !test;
345         if (test) {
346           typename ImageType::PointType p;
347           input->TransformIndexToPhysicalPoint(iter.GetIndex(), p);
348           if ((distanceMax==0) || (p.EuclideanDistanceTo(refpoint) < distanceMax)) {
349             max = iter.GetIndex();
350             found = true;
351           }
352         }
353       }
354       ++iter;
355     }
356     if (!found) return false;
357     input->TransformIndexToPhysicalPoint(max, point); // half of the pixel
358     return true;
359   }
360   //--------------------------------------------------------------------
361
362
363   //--------------------------------------------------------------------
364   template<class ImageType>
365   typename ImageType::Pointer
366   CropImageRemoveGreaterThan(const ImageType * image, 
367                  int dim, double min, bool autoCrop,
368                  typename ImageType::PixelType BG) 
369   {
370     return CropImageAlongOneAxis<ImageType>(image, dim, 
371                                             image->GetOrigin()[dim], 
372                                             min,
373                                             autoCrop, BG);
374   }
375   //--------------------------------------------------------------------
376
377
378   //--------------------------------------------------------------------
379   template<class ImageType>
380   typename ImageType::Pointer
381   CropImageRemoveLowerThan(const ImageType * image, 
382                  int dim, double max, bool autoCrop,
383                  typename ImageType::PixelType BG) 
384   {
385     typename ImageType::PointType p; 
386     
387     image->TransformIndexToPhysicalPoint(image->GetLargestPossibleRegion().GetIndex()+
388                                          image->GetLargestPossibleRegion().GetSize(), p);
389
390     return CropImageAlongOneAxis<ImageType>(image, dim, max, p[dim], autoCrop, BG);
391   }
392   //--------------------------------------------------------------------
393
394
395   //--------------------------------------------------------------------
396   template<class ImageType>
397   typename ImageType::Pointer
398   CropImageAlongOneAxis(const ImageType * image, 
399                         int dim, double min, double max, 
400                         bool autoCrop, typename ImageType::PixelType BG) 
401   {
402     // Compute region size
403     typename ImageType::RegionType region;
404     typename ImageType::SizeType size = image->GetLargestPossibleRegion().GetSize();
405     
406     // Starting index
407     typename ImageType::PointType p = image->GetOrigin(); // not at pixel center !
408     if (min > p[dim]) p[dim] = min; // Check if not outside the image
409     typename ImageType::IndexType start;
410     image->TransformPhysicalPointToIndex(p, start);
411
412     // Size of the region
413     // -1 because last point is size -1
414     double m = image->GetOrigin()[dim] + (size[dim]-1)*image->GetSpacing()[dim];
415     if (max > m) p[dim] = m; // Check if not outside the image
416     else p[dim] = max;
417
418     typename ImageType::IndexType end;
419     image->TransformPhysicalPointToIndex(p, end);
420     size[dim] = abs(end[dim]-start[dim])+1;// +1 because we want to include the point. 
421     
422     // Set region
423     region.SetIndex(start);
424     region.SetSize(size);
425   
426     // Perform Crop
427     typedef itk::RegionOfInterestImageFilter<ImageType, ImageType> CropFilterType;
428     typename CropFilterType::Pointer cropFilter = CropFilterType::New();
429     cropFilter->SetInput(image);
430     cropFilter->SetRegionOfInterest(region);
431     cropFilter->Update();
432     typename ImageType::Pointer result = cropFilter->GetOutput();
433   
434     // Auto Crop
435     if (autoCrop) {
436       result = AutoCrop<ImageType>(result, BG);
437     }
438     return result;
439   }
440   //--------------------------------------------------------------------
441
442
443   //--------------------------------------------------------------------
444   template<class ImageType>
445   void
446   ComputeCentroids(const ImageType * image, 
447                    typename ImageType::PixelType BG, 
448                    std::vector<typename ImageType::PointType> & centroids) 
449   {
450     typedef long LabelType;
451     static const unsigned int Dim = ImageType::ImageDimension;
452     typedef itk::ShapeLabelObject< LabelType, Dim > LabelObjectType;
453     typedef itk::LabelMap< LabelObjectType > LabelMapType;
454     typedef itk::LabelImageToLabelMapFilter<ImageType, LabelMapType> ImageToMapFilterType;
455     typename ImageToMapFilterType::Pointer imageToLabelFilter = ImageToMapFilterType::New(); 
456     typedef itk::ShapeLabelMapFilter<LabelMapType, ImageType> ShapeFilterType; 
457     typename ShapeFilterType::Pointer statFilter = ShapeFilterType::New();
458     imageToLabelFilter->SetBackgroundValue(BG);
459     imageToLabelFilter->SetInput(image);
460     statFilter->SetInput(imageToLabelFilter->GetOutput());
461     statFilter->Update();
462     typename LabelMapType::Pointer labelMap = statFilter->GetOutput();
463
464     centroids.clear();
465     typename ImageType::PointType dummy;
466     centroids.push_back(dummy); // label 0 -> no centroid, use dummy point for BG 
467     //DS FIXME (not useful ! to change ..)
468     for(uint i=0; i<labelMap->GetNumberOfLabelObjects(); i++) {
469       int label = labelMap->GetLabels()[i];
470       centroids.push_back(labelMap->GetLabelObject(label)->GetCentroid());
471     } 
472   }
473   //--------------------------------------------------------------------
474
475
476   //--------------------------------------------------------------------
477   template<class ImageType, class LabelType>
478   typename itk::LabelMap< itk::ShapeLabelObject<LabelType, ImageType::ImageDimension> >::Pointer
479   ComputeLabelMap(const ImageType * image, 
480                   typename ImageType::PixelType BG, 
481                   bool computePerimeterFlag) 
482   {
483     static const unsigned int Dim = ImageType::ImageDimension;
484     typedef itk::ShapeLabelObject< LabelType, Dim > LabelObjectType;
485     typedef itk::LabelMap< LabelObjectType > LabelMapType;
486     typedef itk::LabelImageToLabelMapFilter<ImageType, LabelMapType> ImageToMapFilterType;
487     typename ImageToMapFilterType::Pointer imageToLabelFilter = ImageToMapFilterType::New(); 
488     typedef itk::ShapeLabelMapFilter<LabelMapType, ImageType> ShapeFilterType; 
489     typename ShapeFilterType::Pointer statFilter = ShapeFilterType::New();
490     imageToLabelFilter->SetBackgroundValue(BG);
491     imageToLabelFilter->SetInput(image);
492     statFilter->SetInput(imageToLabelFilter->GetOutput());
493     statFilter->SetComputePerimeter(computePerimeterFlag);
494     statFilter->Update();
495     return statFilter->GetOutput();
496   }
497   //--------------------------------------------------------------------
498
499
500   //--------------------------------------------------------------------
501   template<class ImageType>
502   void
503   ComputeCentroids2(const ImageType * image, 
504                    typename ImageType::PixelType BG, 
505                    std::vector<typename ImageType::PointType> & centroids) 
506   {
507     typedef long LabelType;
508     static const unsigned int Dim = ImageType::ImageDimension;
509     typedef itk::ShapeLabelObject< LabelType, Dim > LabelObjectType;
510     typedef itk::LabelMap< LabelObjectType > LabelMapType;
511     typedef itk::LabelImageToLabelMapFilter<ImageType, LabelMapType> ImageToMapFilterType;
512     typename ImageToMapFilterType::Pointer imageToLabelFilter = ImageToMapFilterType::New(); 
513     typedef itk::ShapeLabelMapFilter<LabelMapType, ImageType> ShapeFilterType; 
514     typename ShapeFilterType::Pointer statFilter = ShapeFilterType::New();
515     imageToLabelFilter->SetBackgroundValue(BG);
516     imageToLabelFilter->SetInput(image);
517     statFilter->SetInput(imageToLabelFilter->GetOutput());
518     statFilter->Update();
519     typename LabelMapType::Pointer labelMap = statFilter->GetOutput();
520
521     centroids.clear();
522     typename ImageType::PointType dummy;
523     centroids.push_back(dummy); // label 0 -> no centroid, use dummy point
524     for(uint i=1; i<labelMap->GetNumberOfLabelObjects()+1; i++) {
525       centroids.push_back(labelMap->GetLabelObject(i)->GetCentroid());
526     } 
527     
528     for(uint i=1; i<labelMap->GetNumberOfLabelObjects()+1; i++) {
529       DD(labelMap->GetLabelObject(i)->GetBinaryPrincipalAxes());
530       DD(labelMap->GetLabelObject(i)->GetBinaryFlatness());
531       DD(labelMap->GetLabelObject(i)->GetRoundness ());      
532
533       // search for the point on the boundary alog PA
534
535     }
536
537   }
538   //--------------------------------------------------------------------
539
540
541   //--------------------------------------------------------------------
542   template<class ImageType>
543   void
544   PointsUtils<ImageType>::Convert2DTo3D(const PointType2D & p2D, 
545                                         const ImageType * image, 
546                                         const int slice, 
547                                         PointType3D & p3D)  
548   {
549     IndexType3D index3D;
550     index3D[0] = index3D[1] = 0;
551     index3D[2] = image->GetLargestPossibleRegion().GetIndex()[2]+slice;
552     image->TransformIndexToPhysicalPoint(index3D, p3D);
553     p3D[0] = p2D[0]; 
554     p3D[1] = p2D[1];
555     //  p3D[2] = p[2];//(image->GetLargestPossibleRegion().GetIndex()[2]+slice)*image->GetSpacing()[2] 
556     //    + image->GetOrigin()[2];
557   }
558   //--------------------------------------------------------------------
559
560
561   //--------------------------------------------------------------------
562   template<class ImageType>
563   void 
564   PointsUtils<ImageType>::Convert2DMapTo3DList(const MapPoint2DType & map, 
565                                             const ImageType * image, 
566                                             VectorPoint3DType & list)
567   {
568     typename MapPoint2DType::const_iterator iter = map.begin();
569     while (iter != map.end()) {
570       PointType3D p;
571       Convert2DTo3D(iter->second, image, iter->first, p);
572       list.push_back(p);
573       ++iter;
574     }
575   }
576   //--------------------------------------------------------------------
577
578
579   //--------------------------------------------------------------------
580   template<class ImageType>
581   void 
582   PointsUtils<ImageType>::Convert2DListTo3DList(const VectorPoint2DType & p2D, 
583                                                 int slice,
584                                                 const ImageType * image, 
585                                                 VectorPoint3DType & list) 
586   {
587     for(uint i=0; i<p2D.size(); i++) {
588       PointType3D p;
589       Convert2DTo3D(p2D[i], image, slice, p);
590       list.push_back(p);
591     }
592   }
593   //--------------------------------------------------------------------
594
595
596   //--------------------------------------------------------------------
597   template<class ImageType>
598   void 
599   WriteListOfLandmarks(std::vector<typename ImageType::PointType> points, 
600                        std::string filename)
601   {
602     std::ofstream os; 
603     openFileForWriting(os, filename); 
604     os << "LANDMARKS1" << std::endl;  
605     for(uint i=0; i<points.size(); i++) {
606       const typename ImageType::PointType & p = points[i];
607       // Write it in the file
608       os << i << " " << p[0] << " " << p[1] << " " << p[2] << " 0 0 " << std::endl;
609     }
610     os.close();
611   }
612   //--------------------------------------------------------------------
613
614
615   //--------------------------------------------------------------------
616   template<class ImageType>
617   typename ImageType::Pointer 
618   Dilate(const ImageType * image, double radiusInMM,               
619          typename ImageType::PixelType BG,
620          typename ImageType::PixelType FG,  
621          bool extendSupport)
622   {
623     typename ImageType::SizeType r;
624     for(uint i=0; i<ImageType::ImageDimension; i++) 
625       r[i] = (uint)lrint(radiusInMM/image->GetSpacing()[i]);
626     return Dilate<ImageType>(image, r, BG, FG, extendSupport);
627   }
628   //--------------------------------------------------------------------
629
630
631   //--------------------------------------------------------------------
632   template<class ImageType>
633   typename ImageType::Pointer 
634   Dilate(const ImageType * image, typename ImageType::PointType radiusInMM, 
635          typename ImageType::PixelType BG, 
636          typename ImageType::PixelType FG, 
637          bool extendSupport)
638   {
639     typename ImageType::SizeType r;
640     for(uint i=0; i<ImageType::ImageDimension; i++) 
641       r[i] = (uint)lrint(radiusInMM[i]/image->GetSpacing()[i]);
642     return Dilate<ImageType>(image, r, BG, FG, extendSupport);
643   }
644   //--------------------------------------------------------------------
645
646
647   //--------------------------------------------------------------------
648   template<class ImageType>
649   typename ImageType::Pointer 
650   Dilate(const ImageType * image, typename ImageType::SizeType radius, 
651          typename ImageType::PixelType BG, 
652          typename ImageType::PixelType FG, 
653          bool extendSupport)
654   {
655     // Create kernel for dilatation
656     typedef itk::BinaryBallStructuringElement<typename ImageType::PixelType, 
657                                               ImageType::ImageDimension> KernelType;
658     KernelType structuringElement;
659     structuringElement.SetRadius(radius);
660     structuringElement.CreateStructuringElement();
661
662     typename ImageType::Pointer output;
663     if (extendSupport) {
664       typedef itk::ConstantPadImageFilter<ImageType, ImageType> PadFilterType;
665       typename PadFilterType::Pointer padFilter = PadFilterType::New();
666       padFilter->SetInput(image);
667       typename ImageType::SizeType lower;
668       typename ImageType::SizeType upper;
669       for(uint i=0; i<3; i++) {
670         lower[i] = upper[i] = 2*(radius[i]+1);
671       }
672       padFilter->SetPadLowerBound(lower);
673       padFilter->SetPadUpperBound(upper);
674       padFilter->Update();
675       output = padFilter->GetOutput();
676     }
677
678     // Dilate  filter
679     typedef itk::BinaryDilateImageFilter<ImageType, ImageType , KernelType> DilateFilterType;
680     typename DilateFilterType::Pointer dilateFilter = DilateFilterType::New();
681     dilateFilter->SetBackgroundValue(BG);
682     dilateFilter->SetForegroundValue(FG);
683     dilateFilter->SetBoundaryToForeground(false);
684     dilateFilter->SetKernel(structuringElement);
685     if (extendSupport) dilateFilter->SetInput(output);
686     else dilateFilter->SetInput(image);
687     dilateFilter->Update();
688     return dilateFilter->GetOutput();
689   }
690   //--------------------------------------------------------------------
691
692
693   //--------------------------------------------------------------------
694   template<class ImageType>
695   typename ImageType::Pointer 
696   Opening(const ImageType * image, typename ImageType::SizeType radius,
697          typename ImageType::PixelType BG,
698          typename ImageType::PixelType FG)
699   {
700     // Kernel 
701     typedef itk::BinaryBallStructuringElement<typename ImageType::PixelType, 
702                                               ImageType::ImageDimension> KernelType;    
703     KernelType structuringElement;
704     structuringElement.SetRadius(radius);
705     structuringElement.CreateStructuringElement();
706     
707     // Filter
708     typedef itk::BinaryMorphologicalOpeningImageFilter<ImageType, ImageType , KernelType> OpeningFilterType;
709     typename OpeningFilterType::Pointer open = OpeningFilterType::New();
710     open->SetInput(image);
711     open->SetBackgroundValue(BG);
712     open->SetForegroundValue(FG);
713     open->SetKernel(structuringElement);
714     open->Update();
715     return open->GetOutput();
716   }
717   //--------------------------------------------------------------------
718
719
720
721   //--------------------------------------------------------------------
722   template<class ValueType, class VectorType>
723   void ConvertOption(std::string optionName, uint given, 
724                      ValueType * values, VectorType & p, 
725                      uint dim, bool required) 
726   {
727     if (required && (given == 0)) {
728       clitkExceptionMacro("The option --" << optionName << " must be set and have 1 or " 
729                           << dim << " values.");
730     }
731     if (given == 1) {
732       for(uint i=0; i<dim; i++) p[i] = values[0];
733       return;
734     }
735     if (given == dim) {
736       for(uint i=0; i<dim; i++) p[i] = values[i];
737       return;
738     }
739     if (given == 0) return;
740     clitkExceptionMacro("The option --" << optionName << " must have 1 or " 
741                         << dim << " values.");
742   }
743   //--------------------------------------------------------------------
744
745
746   //--------------------------------------------------------------------
747   /*
748     http://www.gamedev.net/community/forums/topic.asp?topic_id=542870
749     Assuming the points are (Ax,Ay) (Bx,By) and (Cx,Cy), you need to compute:
750     (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax)
751     This will equal zero if the point C is on the line formed by
752     points A and B, and will have a different sign depending on the
753     side. Which side this is depends on the orientation of your (x,y)
754     coordinates, but you can plug test values for A,B and C into this
755     formula to determine whether negative values are to the left or to
756     the right.
757     => to accelerate, start with formula, when change sign -> stop and fill
758
759     offsetToKeep = is used to determine which side of the line we
760     keep. The point along the mainDirection but 'offsetToKeep' mm away
761     is kept.
762   
763   */
764   template<class ImageType>
765   void 
766   SliceBySliceSetBackgroundFromLineSeparation(ImageType * input, 
767                                               std::vector<typename ImageType::PointType> & lA, 
768                                               std::vector<typename ImageType::PointType> & lB, 
769                                               typename ImageType::PixelType BG, 
770                                               int mainDirection, 
771                                               double offsetToKeep)
772   {
773     assert((mainDirection==0) || (mainDirection==1));
774     typedef itk::ImageSliceIteratorWithIndex<ImageType> SliceIteratorType;
775     SliceIteratorType siter = SliceIteratorType(input, input->GetLargestPossibleRegion());
776     siter.SetFirstDirection(0);
777     siter.SetSecondDirection(1);
778     siter.GoToBegin();
779     uint i=0;
780     typename ImageType::PointType A;
781     typename ImageType::PointType B;
782     typename ImageType::PointType C;
783     assert(lA.size() == lB.size());
784     while ((i<lA.size()) && (!siter.IsAtEnd())) {
785       // Check that the current slice correspond to the current point
786       input->TransformIndexToPhysicalPoint(siter.GetIndex(), C);
787       if ((fabs(C[2] - lA[i][2]))>0.01) { // is !equal with a tolerance of 0.01 mm
788       }
789       else {
790         // Define A,B,C points
791         A = lA[i];
792         B = lB[i];
793         C = A;
794         // Check that the line is not a point (A=B)
795         bool p = (A[0] == B[0]) && (A[1] == B[1]);
796       
797         if (!p) {
798           C[mainDirection] += offsetToKeep; // I know I must keep this point
799           double s = (B[0] - A[0]) * (C[1] - A[1]) - (B[1] - A[1]) * (C[0] - A[0]);
800           bool isPositive = s<0;
801           while (!siter.IsAtEndOfSlice()) {
802             while (!siter.IsAtEndOfLine()) {
803               // Very slow, I know ... but image should be very small
804               input->TransformIndexToPhysicalPoint(siter.GetIndex(), C);
805               double s = (B[0] - A[0]) * (C[1] - A[1]) - (B[1] - A[1]) * (C[0] - A[0]);
806               if (s == 0) siter.Set(BG); // on the line, we decide to remove
807               if (isPositive) {
808                 if (s > 0) siter.Set(BG);
809               }
810               else {
811                 if (s < 0) siter.Set(BG); 
812               }
813               ++siter;
814             }
815             siter.NextLine();
816           } // end loop slice
817         }      
818
819         ++i;
820       } // End of current slice
821       siter.NextSlice();
822     }
823   }                                                   
824   //--------------------------------------------------------------------
825
826
827   //--------------------------------------------------------------------
828   template<class ImageType>
829   void 
830   AndNot(ImageType * input, 
831          const ImageType * object, 
832          typename ImageType::PixelType BG)
833   {
834     typename ImageType::Pointer o;
835     bool resized=false;
836     if (!clitk::HaveSameSizeAndSpacing<ImageType, ImageType>(input, object)) {
837       o = clitk::ResizeImageLike<ImageType>(object, input, BG);
838       resized = true;
839     }
840
841     typedef clitk::BooleanOperatorLabelImageFilter<ImageType> BoolFilterType;
842     typename BoolFilterType::Pointer boolFilter = BoolFilterType::New(); 
843     boolFilter->InPlaceOn();
844     boolFilter->SetInput1(input);
845     if (resized) boolFilter->SetInput2(o);  
846     else boolFilter->SetInput2(object);
847     boolFilter->SetBackgroundValue1(BG);
848     boolFilter->SetBackgroundValue2(BG);
849     boolFilter->SetOperationType(BoolFilterType::AndNot);
850     boolFilter->Update();
851   }
852   //--------------------------------------------------------------------
853
854
855   //--------------------------------------------------------------------
856   template<class ImageType>
857   void 
858   And(ImageType * input, 
859       const ImageType * object, 
860       typename ImageType::PixelType BG)
861   {
862     typename ImageType::Pointer o;
863     bool resized=false;
864     if (!clitk::HaveSameSizeAndSpacing<ImageType, ImageType>(input, object)) {
865       o = clitk::ResizeImageLike<ImageType>(object, input, BG);
866       resized = true;
867     }
868
869     typedef clitk::BooleanOperatorLabelImageFilter<ImageType> BoolFilterType;
870     typename BoolFilterType::Pointer boolFilter = BoolFilterType::New(); 
871     boolFilter->InPlaceOn();
872     boolFilter->SetInput1(input);
873     if (resized) boolFilter->SetInput2(o);  
874     else boolFilter->SetInput2(object);
875     boolFilter->SetBackgroundValue1(BG);
876     boolFilter->SetBackgroundValue2(BG);
877     boolFilter->SetOperationType(BoolFilterType::And);
878     boolFilter->Update();
879   }
880   //--------------------------------------------------------------------
881
882
883   //--------------------------------------------------------------------
884   template<class ImageType>
885   void 
886   Or(ImageType * input, 
887      const ImageType * object, 
888      typename ImageType::PixelType BG)
889   {
890     typename ImageType::Pointer o;
891     bool resized=false;
892     if (!clitk::HaveSameSizeAndSpacing<ImageType, ImageType>(input, object)) {
893       o = clitk::ResizeImageLike<ImageType>(object, input, BG);
894       resized = true;
895     }
896
897     typedef clitk::BooleanOperatorLabelImageFilter<ImageType> BoolFilterType;
898     typename BoolFilterType::Pointer boolFilter = BoolFilterType::New(); 
899     boolFilter->InPlaceOn();
900     boolFilter->SetInput1(input);
901     if (resized) boolFilter->SetInput2(o);  
902     else boolFilter->SetInput2(object);
903     boolFilter->SetBackgroundValue1(BG);
904     boolFilter->SetBackgroundValue2(BG);
905     boolFilter->SetOperationType(BoolFilterType::Or);
906     boolFilter->Update();
907   }
908   //--------------------------------------------------------------------
909
910
911   //--------------------------------------------------------------------
912   template<class ImageType>
913   typename ImageType::Pointer
914   Binarize(const ImageType * input, 
915            typename ImageType::PixelType lower, 
916            typename ImageType::PixelType upper, 
917            typename ImageType::PixelType BG,
918            typename ImageType::PixelType FG) 
919   {
920     typedef itk::BinaryThresholdImageFilter<ImageType, ImageType> BinaryThresholdFilterType;
921     typename BinaryThresholdFilterType::Pointer binarizeFilter = BinaryThresholdFilterType::New();
922     binarizeFilter->SetInput(input);
923     binarizeFilter->InPlaceOff();
924     binarizeFilter->SetLowerThreshold(lower);
925     binarizeFilter->SetUpperThreshold(upper);
926     binarizeFilter->SetInsideValue(FG);
927     binarizeFilter->SetOutsideValue(BG);
928     binarizeFilter->Update();
929     return binarizeFilter->GetOutput();
930   }
931   //--------------------------------------------------------------------
932
933
934   //--------------------------------------------------------------------
935   template<class ImageType>
936   void
937   GetMinMaxPointPosition(const ImageType * input, 
938                          typename ImageType::PointType & min,
939                          typename ImageType::PointType & max) 
940   {
941     typename ImageType::IndexType index = input->GetLargestPossibleRegion().GetIndex();
942     input->TransformIndexToPhysicalPoint(index, min);
943     index = index+input->GetLargestPossibleRegion().GetSize();
944     input->TransformIndexToPhysicalPoint(index, max);
945   }
946   //--------------------------------------------------------------------
947
948
949   //--------------------------------------------------------------------
950   template<class ImageType>
951   typename ImageType::PointType
952   FindExtremaPointInAGivenLine(const ImageType * input, 
953                                int dimension, 
954                                bool inverse, 
955                                typename ImageType::PointType p, 
956                                typename ImageType::PixelType BG, 
957                                double distanceMax) 
958   {
959     // Which direction ?  Increasing or decreasing.
960     int d=1;
961     if (inverse) d=-1;
962   
963     // Transform to pixel index
964     typename ImageType::IndexType index;
965     input->TransformPhysicalPointToIndex(p, index);
966
967     // Loop while inside the mask;
968     while (input->GetPixel(index) != BG) {
969       index[dimension] += d;
970     }
971
972     // Transform back to Physical Units
973     typename ImageType::PointType result;
974     input->TransformIndexToPhysicalPoint(index, result);
975
976     // Check that is is not too far away
977     double distance = p.EuclideanDistanceTo(result);
978     if (distance > distanceMax) {
979       result = p; // Get back to initial value
980     }
981
982     return result;
983   }
984   //--------------------------------------------------------------------
985
986
987   //--------------------------------------------------------------------
988   template<class PointType>
989   bool
990   IsOnTheSameLineSide(PointType C, PointType A, PointType B, PointType like) 
991   {
992     // Look at the position of point 'like' according to the AB line
993     double s = (B[0] - A[0]) * (like[1] - A[1]) - (B[1] - A[1]) * (like[0] - A[0]);
994     bool negative = s<0;
995   
996     // Look the C position
997     s = (B[0] - A[0]) * (C[1] - A[1]) - (B[1] - A[1]) * (C[0] - A[0]);
998
999     if (negative && (s<=0)) return true;
1000     if (!negative && (s>=0)) return true;
1001     return false;
1002   }
1003   //--------------------------------------------------------------------
1004
1005
1006   //--------------------------------------------------------------------
1007   /* Consider an input object, for each slice, find the extrema
1008      position according to a given direction and build a line segment
1009      passing throught this point in a given direction.  Output is a
1010      vector of line (from point A to B), for each slice;
1011    */
1012   template<class ImageType>
1013   void 
1014   SliceBySliceBuildLineSegmentAccordingToExtremaPosition(const ImageType * input, 
1015                                                          typename ImageType::PixelType BG, 
1016                                                          int sliceDimension, 
1017                                                          int extremaDirection, 
1018                                                          bool extremaOppositeFlag, 
1019                                                          int lineDirection,
1020                                                          double margin,
1021                                                          std::vector<typename ImageType::PointType> & A, 
1022                                                          std::vector<typename ImageType::PointType> & B)
1023   {
1024     // Type of a slice
1025     typedef typename itk::Image<typename ImageType::PixelType, ImageType::ImageDimension-1> SliceType;
1026     
1027     // Build the list of slices
1028     std::vector<typename SliceType::Pointer> slices;
1029     clitk::ExtractSlices<ImageType>(input, sliceDimension, slices);
1030
1031     // Build the list of 2D points
1032     std::map<int, typename SliceType::PointType> position2D;
1033     for(uint i=0; i<slices.size(); i++) {
1034       typename SliceType::PointType p;
1035       bool found = 
1036         clitk::FindExtremaPointInAGivenDirection<SliceType>(slices[i], BG, 
1037                                                             extremaDirection, extremaOppositeFlag, p);
1038       if (found) {
1039         position2D[i] = p;
1040       }
1041     }
1042     
1043     // Convert 2D points in slice into 3D points
1044     clitk::PointsUtils<ImageType>::Convert2DMapTo3DList(position2D, input, A);
1045     
1046     // Create additional point just right to the previous ones, on the
1047     // given lineDirection, in order to create a horizontal/vertical line.
1048     for(uint i=0; i<A.size(); i++) {
1049       typename ImageType::PointType p = A[i];
1050       p[lineDirection] += 10;
1051       B.push_back(p);
1052       // Margins ?
1053       A[i][extremaDirection] += margin;
1054       B[i][extremaDirection] += margin;
1055     }
1056
1057   }
1058   //--------------------------------------------------------------------
1059
1060
1061   //--------------------------------------------------------------------
1062   template<class ImageType>
1063   typename ImageType::Pointer
1064   SliceBySliceKeepMainCCL(const ImageType * input, 
1065                           typename ImageType::PixelType BG,
1066                           typename ImageType::PixelType FG)  {
1067     
1068     // Extract slices
1069     const int d = ImageType::ImageDimension-1;
1070     typedef typename itk::Image<typename ImageType::PixelType, d> SliceType;
1071     std::vector<typename SliceType::Pointer> slices;
1072     clitk::ExtractSlices<ImageType>(input, d, slices);
1073     
1074     // Labelize and keep the main one
1075     std::vector<typename SliceType::Pointer> o;
1076     for(uint i=0; i<slices.size(); i++) {
1077       o.push_back(clitk::Labelize<SliceType>(slices[i], BG, false, 1));
1078       o[i] = clitk::KeepLabels<SliceType>(o[i], BG, FG, 1, 1, true);
1079     }
1080     
1081     // Join slices
1082     typename ImageType::Pointer output;
1083     output = clitk::JoinSlices<ImageType>(o, input, d);
1084     return output;
1085   }
1086   //--------------------------------------------------------------------
1087
1088
1089   //--------------------------------------------------------------------
1090   template<class ImageType>
1091   typename ImageType::Pointer
1092   Clone(const ImageType * input) {
1093     typedef itk::ImageDuplicator<ImageType> DuplicatorType;
1094     typename DuplicatorType::Pointer duplicator = DuplicatorType::New();
1095     duplicator->SetInputImage(input);
1096     duplicator->Update();
1097     return duplicator->GetOutput();
1098   }
1099   //--------------------------------------------------------------------
1100
1101
1102   //--------------------------------------------------------------------
1103   /* Consider an input object, start at A, for each slice (dim1): 
1104      - compute the intersection between the AB line and the current slice
1105      - remove what is at lower or greater according to dim2 of this point
1106      - stop at B
1107   */
1108   template<class ImageType>
1109   typename ImageType::Pointer
1110   SliceBySliceSetBackgroundFromSingleLine(const ImageType * input, 
1111                                           typename ImageType::PixelType BG, 
1112                                           typename ImageType::PointType & A, 
1113                                           typename ImageType::PointType & B, 
1114                                           int dim1, int dim2, bool removeLowerPartFlag)
1115     
1116   {
1117     // Extract slices
1118     typedef typename itk::Image<typename ImageType::PixelType, ImageType::ImageDimension-1> SliceType;
1119     typedef typename SliceType::Pointer SlicePointer;
1120     std::vector<SlicePointer> slices;
1121     clitk::ExtractSlices<ImageType>(input, dim1, slices);
1122
1123     // Start at slice that contains A, and stop at B
1124     typename ImageType::IndexType Ap;
1125     typename ImageType::IndexType Bp;
1126     input->TransformPhysicalPointToIndex(A, Ap);
1127     input->TransformPhysicalPointToIndex(B, Bp);
1128     
1129     // Determine slice largest region
1130     typename SliceType::RegionType region = slices[0]->GetLargestPossibleRegion();
1131     typename SliceType::SizeType size = region.GetSize();
1132     typename SliceType::IndexType index = region.GetIndex();
1133
1134     // Line slope
1135     double a = (Bp[dim2]-Ap[dim2])/(Bp[dim1]-Ap[dim1]);
1136     double b = Ap[dim2];
1137
1138     // Loop from slice A to slice B
1139     for(uint i=0; i<(Bp[dim1]-Ap[dim1]); i++) {
1140       // Compute intersection between line AB and current slice for the dim2
1141       double p = a*i+b;
1142       // Change region (lower than dim2)
1143       if (removeLowerPartFlag) {
1144         size[dim2] = p-Ap[dim2];
1145       }
1146       else {
1147         size[dim2] = slices[0]->GetLargestPossibleRegion().GetSize()[dim2]-p;
1148         index[dim2] = p;
1149       }
1150       region.SetSize(size);
1151       region.SetIndex(index);
1152       // Fill region with BG (simple region iterator)
1153       FillRegionWithValue<SliceType>(slices[i+Ap[dim1]], BG, region);
1154       /*
1155       typedef itk::ImageRegionIterator<SliceType> IteratorType;
1156       IteratorType iter(slices[i+Ap[dim1]], region);
1157       iter.GoToBegin();
1158       while (!iter.IsAtEnd()) {
1159         iter.Set(BG);
1160         ++iter;
1161       }
1162       */
1163       // Loop
1164     }
1165     
1166     // Merge slices
1167     typename ImageType::Pointer output;
1168     output = clitk::JoinSlices<ImageType>(slices, input, dim1);
1169     return output;
1170   }
1171   //--------------------------------------------------------------------
1172
1173   //--------------------------------------------------------------------
1174   /* Consider an input object, slice by slice, use the point A and set
1175      pixel to BG according to their position relatively to A
1176   */
1177   template<class ImageType>
1178   typename ImageType::Pointer
1179   SliceBySliceSetBackgroundFromPoints(const ImageType * input, 
1180                                       typename ImageType::PixelType BG, 
1181                                       int sliceDim,
1182                                       std::vector<typename ImageType::PointType> & A, 
1183                                       bool removeGreaterThanXFlag,
1184                                       bool removeGreaterThanYFlag)
1185     
1186   {
1187     // Extract slices
1188     typedef typename itk::Image<typename ImageType::PixelType, ImageType::ImageDimension-1> SliceType;
1189     typedef typename SliceType::Pointer SlicePointer;
1190     std::vector<SlicePointer> slices;
1191     clitk::ExtractSlices<ImageType>(input, sliceDim, slices);
1192
1193     // Start at slice that contains A
1194     typename ImageType::IndexType Ap;
1195     
1196     // Determine slice largest region
1197     typename SliceType::RegionType region = slices[0]->GetLargestPossibleRegion();
1198     typename SliceType::SizeType size = region.GetSize();
1199     typename SliceType::IndexType index = region.GetIndex();
1200
1201     // Loop from slice A to slice B
1202     for(uint i=0; i<A.size(); i++) {
1203       input->TransformPhysicalPointToIndex(A[i], Ap);
1204       uint sliceIndex = Ap[2] - input->GetLargestPossibleRegion().GetIndex()[2];
1205       if ((sliceIndex < 0) || (sliceIndex >= slices.size())) {
1206         continue; // do not consider this slice
1207       }
1208       
1209       // Compute region for BG
1210       if (removeGreaterThanXFlag) {
1211         index[0] = Ap[0];
1212         size[0] = region.GetSize()[0]-(index[0]-region.GetIndex()[0]);
1213       }
1214       else {
1215         index[0] = region.GetIndex()[0];
1216         size[0] = Ap[0] - index[0];
1217       }
1218
1219       if (removeGreaterThanYFlag) {
1220         index[1] = Ap[1];
1221         size[1] = region.GetSize()[1]-(index[1]-region.GetIndex()[1]);
1222       }
1223       else {
1224         index[1] = region.GetIndex()[1];
1225         size[1] = Ap[1] - index[1];
1226       }
1227
1228       // Set region
1229       region.SetSize(size);
1230       region.SetIndex(index);
1231
1232       // Fill region with BG (simple region iterator)
1233       FillRegionWithValue<SliceType>(slices[sliceIndex], BG, region);
1234       // Loop
1235     }
1236     
1237     // Merge slices
1238     typename ImageType::Pointer output;
1239     output = clitk::JoinSlices<ImageType>(slices, input, sliceDim);
1240     return output;
1241   }
1242   //--------------------------------------------------------------------
1243
1244
1245   //--------------------------------------------------------------------
1246   template<class ImageType>
1247   void
1248   FillRegionWithValue(ImageType * input, typename ImageType::PixelType value, typename ImageType::RegionType & region)
1249   {
1250     typedef itk::ImageRegionIterator<ImageType> IteratorType;
1251     IteratorType iter(input, region);
1252     iter.GoToBegin();
1253     while (!iter.IsAtEnd()) {
1254       iter.Set(value);
1255       ++iter;
1256     }    
1257   }
1258   //--------------------------------------------------------------------
1259
1260
1261   //--------------------------------------------------------------------
1262   template<class ImageType>
1263   void
1264   GetMinMaxBoundary(ImageType * input, typename ImageType::PointType & min, 
1265                     typename ImageType::PointType & max)
1266   {
1267     typedef typename ImageType::PointType PointType;
1268     typedef typename ImageType::IndexType IndexType;
1269     IndexType min_i, max_i;
1270     min_i = input->GetLargestPossibleRegion().GetIndex();
1271     for(uint i=0; i<ImageType::ImageDimension; i++)
1272       max_i[i] = input->GetLargestPossibleRegion().GetSize()[i] + min_i[i];
1273     input->TransformIndexToPhysicalPoint(min_i, min);
1274     input->TransformIndexToPhysicalPoint(max_i, max);  
1275   }
1276   //--------------------------------------------------------------------
1277
1278
1279   //--------------------------------------------------------------------
1280   template<class ImageType>
1281   typename itk::Image<float, ImageType::ImageDimension>::Pointer
1282   DistanceMap(const ImageType * input, typename ImageType::PixelType BG)//, 
1283   //              typename itk::Image<float, ImageType::ImageDimension>::Pointer dmap) 
1284   {
1285     typedef itk::Image<float,ImageType::ImageDimension> FloatImageType;
1286     typedef itk::SignedMaurerDistanceMapImageFilter<ImageType, FloatImageType> DistanceMapFilterType;
1287     typename DistanceMapFilterType::Pointer filter = DistanceMapFilterType::New();
1288     filter->SetInput(input);
1289     filter->SetUseImageSpacing(true);
1290     filter->SquaredDistanceOff();
1291     filter->SetBackgroundValue(BG);
1292     filter->Update();
1293     return filter->GetOutput();
1294   }
1295   //--------------------------------------------------------------------
1296
1297
1298   //--------------------------------------------------------------------
1299   template<class ImageType>
1300   void 
1301   SliceBySliceBuildLineSegmentAccordingToMinimalDistanceBetweenStructures(const ImageType * S1, 
1302                                                                           const ImageType * S2, 
1303                                                                           typename ImageType::PixelType BG, 
1304                                                                           int sliceDimension, 
1305                                                                           std::vector<typename ImageType::PointType> & A, 
1306                                                                           std::vector<typename ImageType::PointType> & B)
1307   {
1308     // Extract slices
1309     typedef typename itk::Image<typename ImageType::PixelType, 2> SliceType;
1310     typedef typename SliceType::Pointer SlicePointer;
1311     std::vector<SlicePointer> slices_s1;
1312     std::vector<SlicePointer> slices_s2;
1313     clitk::ExtractSlices<ImageType>(S1, sliceDimension, slices_s1);
1314     clitk::ExtractSlices<ImageType>(S2, sliceDimension, slices_s2);
1315
1316     assert(slices_s1.size() == slices_s2.size());
1317
1318     // Prepare dmap
1319     typedef itk::Image<float,2> FloatImageType;
1320     typedef itk::SignedMaurerDistanceMapImageFilter<SliceType, FloatImageType> DistanceMapFilterType;
1321     std::vector<typename FloatImageType::Pointer> dmaps1;
1322     std::vector<typename FloatImageType::Pointer> dmaps2;
1323     typename FloatImageType::Pointer dmap;
1324
1325     // loop on slices
1326     for(uint i=0; i<slices_s1.size(); i++) {
1327       // Compute dmap for S1 *TO PUT IN FONCTION*
1328       dmap = clitk::DistanceMap<SliceType>(slices_s1[i], BG);
1329       dmaps1.push_back(dmap);
1330       //writeImage<FloatImageType>(dmap, "dmap1.mha");
1331       // Compute dmap for S2
1332       dmap = clitk::DistanceMap<SliceType>(slices_s2[i], BG);
1333       dmaps2.push_back(dmap);
1334       //writeImage<FloatImageType>(dmap, "dmap2.mha");
1335       
1336       // Look in S2 for the point the closest to S1
1337       typename SliceType::PointType p = ComputeClosestPoint<SliceType>(slices_s1[i], dmaps2[i], BG);
1338       typename ImageType::PointType p3D;
1339       clitk::PointsUtils<ImageType>::Convert2DTo3D(p, S1, i, p3D);
1340       A.push_back(p3D);
1341
1342       // Look in S2 for the point the closest to S1
1343       p = ComputeClosestPoint<SliceType>(slices_s2[i], dmaps1[i], BG);
1344       clitk::PointsUtils<ImageType>::Convert2DTo3D(p, S2, i, p3D);
1345       B.push_back(p3D);
1346
1347     }
1348
1349     // Debug dmap
1350     /*
1351       typedef itk::Image<float,3> FT;
1352       FT::Pointer f = FT::New();
1353       typename FT::Pointer d1 = clitk::JoinSlices<FT>(dmaps1, S1, 2);
1354       typename FT::Pointer d2 = clitk::JoinSlices<FT>(dmaps2, S2, 2);
1355       writeImage<FT>(d1, "d1.mha");
1356       writeImage<FT>(d2, "d2.mha");
1357     */
1358   }
1359   //--------------------------------------------------------------------
1360
1361
1362   //--------------------------------------------------------------------
1363   template<class ImageType>
1364   typename ImageType::PointType
1365   ComputeClosestPoint(const ImageType * input, 
1366                       const itk::Image<float, ImageType::ImageDimension> * dmap, 
1367                       typename ImageType::PixelType & BG) 
1368   {
1369     // Loop dmap + S2, if FG, get min
1370     typedef itk::Image<float,ImageType::ImageDimension> FloatImageType;
1371     typedef itk::ImageRegionConstIteratorWithIndex<ImageType> ImageIteratorType;
1372     typedef itk::ImageRegionConstIterator<FloatImageType> DMapIteratorType;
1373     ImageIteratorType iter1(input, input->GetLargestPossibleRegion());
1374     DMapIteratorType iter2(dmap, dmap->GetLargestPossibleRegion());
1375     
1376     iter1.GoToBegin();
1377     iter2.GoToBegin();
1378     double dmin = 100000.0;
1379     typename ImageType::IndexType indexmin;
1380     indexmin.Fill(0);
1381     while (!iter1.IsAtEnd()) {
1382       if (iter1.Get() != BG) {
1383         double d = iter2.Get();
1384         if (d<dmin) {
1385           indexmin = iter1.GetIndex();
1386           dmin = d;
1387         }
1388       }
1389       ++iter1;
1390       ++iter2;
1391     }
1392     
1393     // Convert in Point
1394     typename ImageType::PointType p;
1395     input->TransformIndexToPhysicalPoint(indexmin, p);
1396     return p;
1397   }
1398   //--------------------------------------------------------------------
1399      
1400
1401   //--------------------------------------------------------------------
1402   template<class ImageType>
1403   typename ImageType::Pointer
1404   RemoveNegativeIndexFromRegion(ImageType * input) {
1405     typedef itk::ChangeInformationImageFilter< ImageType > InfoFilterType; 
1406     typename InfoFilterType::Pointer indexChangeFilter = InfoFilterType::New(); 
1407     indexChangeFilter->ChangeRegionOn(); 
1408     // The next line is commented because not exist in itk 3
1409     // typename InfoFilterType::OutputImageOffsetValueType indexShift[3];
1410     long indexShift[3];
1411     typename ImageType::IndexType index = input->GetLargestPossibleRegion().GetIndex();
1412     for(uint i=0;i<ImageType::ImageDimension; i++)
1413       indexShift[i] = (index[i]<0 ? -index[i]:0);
1414     typename ImageType::PointType origin;
1415     for(uint i=0;i<ImageType::ImageDimension; i++)
1416     origin[i] = input->GetOrigin()[i] - indexShift[i]*input->GetSpacing()[i];
1417     indexChangeFilter->SetOutputOffset( indexShift ); 
1418     indexChangeFilter->SetInput(input); 
1419     indexChangeFilter->SetOutputOrigin(origin);
1420     indexChangeFilter->ChangeOriginOn();
1421     indexChangeFilter->Update();
1422     return indexChangeFilter->GetOutput();
1423   }
1424   //--------------------------------------------------------------------
1425
1426
1427 } // end of namespace
1428