]> Creatis software - clitk.git/blob - itk/clitkSegmentationUtils.txx
8fe69a0b13cdfaad0a98819090d35d0ba765a731
[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->AddAngles(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);
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     image->TransformIndexToPhysicalPoint(image->GetLargestPossibleRegion().GetIndex()+
387                                          image->GetLargestPossibleRegion().GetSize(), p);
388     return CropImageAlongOneAxis<ImageType>(image, dim, max, p[dim], autoCrop, BG);
389   }
390   //--------------------------------------------------------------------
391
392
393   //--------------------------------------------------------------------
394   template<class ImageType>
395   typename ImageType::Pointer
396   CropImageAlongOneAxis(const ImageType * image, 
397                         int dim, double min, double max, 
398                         bool autoCrop, typename ImageType::PixelType BG) 
399   {
400     // Compute region size
401     typename ImageType::RegionType region;
402     typename ImageType::SizeType size = image->GetLargestPossibleRegion().GetSize();
403     typename ImageType::PointType p = image->GetOrigin();
404     if (min > p[dim]) p[dim] = min; // Check if not outside the image
405     typename ImageType::IndexType start;
406     image->TransformPhysicalPointToIndex(p, start);
407     double m = image->GetOrigin()[dim] + size[dim]*image->GetSpacing()[dim];
408     if (max > m) p[dim] = m; // Check if not outside the image
409     else p[dim] = max;
410     typename ImageType::IndexType end;
411     image->TransformPhysicalPointToIndex(p, end);
412     size[dim] = abs(end[dim]-start[dim]);
413     region.SetIndex(start);
414     region.SetSize(size);
415   
416     // Perform Crop
417     typedef itk::RegionOfInterestImageFilter<ImageType, ImageType> CropFilterType;
418     typename CropFilterType::Pointer cropFilter = CropFilterType::New();
419     cropFilter->SetInput(image);
420     cropFilter->SetRegionOfInterest(region);
421     cropFilter->Update();
422     typename ImageType::Pointer result = cropFilter->GetOutput();
423   
424     // Auto Crop
425     if (autoCrop) {
426       result = AutoCrop<ImageType>(result, BG);
427     }
428     return result;
429   }
430   //--------------------------------------------------------------------
431
432
433   //--------------------------------------------------------------------
434   template<class ImageType>
435   void
436   ComputeCentroids(const ImageType * image, 
437                    typename ImageType::PixelType BG, 
438                    std::vector<typename ImageType::PointType> & centroids) 
439   {
440     typedef long LabelType;
441     static const unsigned int Dim = ImageType::ImageDimension;
442     typedef itk::ShapeLabelObject< LabelType, Dim > LabelObjectType;
443     typedef itk::LabelMap< LabelObjectType > LabelMapType;
444     typedef itk::LabelImageToLabelMapFilter<ImageType, LabelMapType> ImageToMapFilterType;
445     typename ImageToMapFilterType::Pointer imageToLabelFilter = ImageToMapFilterType::New(); 
446     typedef itk::ShapeLabelMapFilter<LabelMapType, ImageType> ShapeFilterType; 
447     typename ShapeFilterType::Pointer statFilter = ShapeFilterType::New();
448     imageToLabelFilter->SetBackgroundValue(BG);
449     imageToLabelFilter->SetInput(image);
450     statFilter->SetInput(imageToLabelFilter->GetOutput());
451     statFilter->Update();
452     typename LabelMapType::Pointer labelMap = statFilter->GetOutput();
453
454     centroids.clear();
455     typename ImageType::PointType dummy;
456     centroids.push_back(dummy); // label 0 -> no centroid, use dummy point for BG 
457     //DS FIXME (not useful ! to change ..)
458     for(uint i=0; i<labelMap->GetNumberOfLabelObjects(); i++) {
459       int label = labelMap->GetLabels()[i];
460       centroids.push_back(labelMap->GetLabelObject(label)->GetCentroid());
461     } 
462   }
463   //--------------------------------------------------------------------
464
465
466   //--------------------------------------------------------------------
467   template<class ImageType, class LabelType>
468   typename itk::LabelMap< itk::ShapeLabelObject<LabelType, ImageType::ImageDimension> >::Pointer
469   ComputeLabelMap(const ImageType * image, 
470                   typename ImageType::PixelType BG, 
471                   bool computePerimeterFlag) 
472   {
473     static const unsigned int Dim = ImageType::ImageDimension;
474     typedef itk::ShapeLabelObject< LabelType, Dim > LabelObjectType;
475     typedef itk::LabelMap< LabelObjectType > LabelMapType;
476     typedef itk::LabelImageToLabelMapFilter<ImageType, LabelMapType> ImageToMapFilterType;
477     typename ImageToMapFilterType::Pointer imageToLabelFilter = ImageToMapFilterType::New(); 
478     typedef itk::ShapeLabelMapFilter<LabelMapType, ImageType> ShapeFilterType; 
479     typename ShapeFilterType::Pointer statFilter = ShapeFilterType::New();
480     imageToLabelFilter->SetBackgroundValue(BG);
481     imageToLabelFilter->SetInput(image);
482     statFilter->SetInput(imageToLabelFilter->GetOutput());
483     statFilter->SetComputePerimeter(computePerimeterFlag);
484     statFilter->Update();
485     return statFilter->GetOutput();
486   }
487   //--------------------------------------------------------------------
488
489
490   //--------------------------------------------------------------------
491   template<class ImageType>
492   void
493   ComputeCentroids2(const ImageType * image, 
494                    typename ImageType::PixelType BG, 
495                    std::vector<typename ImageType::PointType> & centroids) 
496   {
497     typedef long LabelType;
498     static const unsigned int Dim = ImageType::ImageDimension;
499     typedef itk::ShapeLabelObject< LabelType, Dim > LabelObjectType;
500     typedef itk::LabelMap< LabelObjectType > LabelMapType;
501     typedef itk::LabelImageToLabelMapFilter<ImageType, LabelMapType> ImageToMapFilterType;
502     typename ImageToMapFilterType::Pointer imageToLabelFilter = ImageToMapFilterType::New(); 
503     typedef itk::ShapeLabelMapFilter<LabelMapType, ImageType> ShapeFilterType; 
504     typename ShapeFilterType::Pointer statFilter = ShapeFilterType::New();
505     imageToLabelFilter->SetBackgroundValue(BG);
506     imageToLabelFilter->SetInput(image);
507     statFilter->SetInput(imageToLabelFilter->GetOutput());
508     statFilter->Update();
509     typename LabelMapType::Pointer labelMap = statFilter->GetOutput();
510
511     centroids.clear();
512     typename ImageType::PointType dummy;
513     centroids.push_back(dummy); // label 0 -> no centroid, use dummy point
514     for(uint i=1; i<labelMap->GetNumberOfLabelObjects()+1; i++) {
515       centroids.push_back(labelMap->GetLabelObject(i)->GetCentroid());
516     } 
517     
518     for(uint i=1; i<labelMap->GetNumberOfLabelObjects()+1; i++) {
519       DD(labelMap->GetLabelObject(i)->GetBinaryPrincipalAxes());
520       DD(labelMap->GetLabelObject(i)->GetBinaryFlatness());
521       DD(labelMap->GetLabelObject(i)->GetRoundness ());      
522
523       // search for the point on the boundary alog PA
524
525     }
526
527   }
528   //--------------------------------------------------------------------
529
530
531   //--------------------------------------------------------------------
532   template<class ImageType>
533   void
534   PointsUtils<ImageType>::Convert2DTo3D(const PointType2D & p2D, 
535                                         const ImageType * image, 
536                                         const int slice, 
537                                         PointType3D & p3D)  
538   {
539     IndexType3D index3D;
540     index3D[0] = index3D[1] = 0;
541     index3D[2] = image->GetLargestPossibleRegion().GetIndex()[2]+slice;
542     image->TransformIndexToPhysicalPoint(index3D, p3D);
543     p3D[0] = p2D[0]; 
544     p3D[1] = p2D[1];
545     //  p3D[2] = p[2];//(image->GetLargestPossibleRegion().GetIndex()[2]+slice)*image->GetSpacing()[2] 
546     //    + image->GetOrigin()[2];
547   }
548   //--------------------------------------------------------------------
549
550
551   //--------------------------------------------------------------------
552   template<class ImageType>
553   void 
554   PointsUtils<ImageType>::Convert2DMapTo3DList(const MapPoint2DType & map, 
555                                             const ImageType * image, 
556                                             VectorPoint3DType & list)
557   {
558     typename MapPoint2DType::const_iterator iter = map.begin();
559     while (iter != map.end()) {
560       PointType3D p;
561       Convert2DTo3D(iter->second, image, iter->first, p);
562       list.push_back(p);
563       ++iter;
564     }
565   }
566   //--------------------------------------------------------------------
567
568
569   //--------------------------------------------------------------------
570   template<class ImageType>
571   void 
572   PointsUtils<ImageType>::Convert2DListTo3DList(const VectorPoint2DType & p2D, 
573                                                 int slice,
574                                                 const ImageType * image, 
575                                                 VectorPoint3DType & list) 
576   {
577     for(uint i=0; i<p2D.size(); i++) {
578       PointType3D p;
579       Convert2DTo3D(p2D[i], image, slice, p);
580       list.push_back(p);
581     }
582   }
583   //--------------------------------------------------------------------
584
585
586   //--------------------------------------------------------------------
587   template<class ImageType>
588   void 
589   WriteListOfLandmarks(std::vector<typename ImageType::PointType> points, 
590                        std::string filename)
591   {
592     std::ofstream os; 
593     openFileForWriting(os, filename); 
594     os << "LANDMARKS1" << std::endl;  
595     for(uint i=0; i<points.size(); i++) {
596       const typename ImageType::PointType & p = points[i];
597       // Write it in the file
598       os << i << " " << p[0] << " " << p[1] << " " << p[2] << " 0 0 " << std::endl;
599     }
600     os.close();
601   }
602   //--------------------------------------------------------------------
603
604
605   //--------------------------------------------------------------------
606   template<class ImageType>
607   typename ImageType::Pointer 
608   Dilate(const ImageType * image, double radiusInMM,               
609          typename ImageType::PixelType BG,
610          typename ImageType::PixelType FG,  
611          bool extendSupport)
612   {
613     typename ImageType::SizeType r;
614     for(uint i=0; i<ImageType::ImageDimension; i++) 
615       r[i] = (uint)lrint(radiusInMM/image->GetSpacing()[i]);
616     return Dilate<ImageType>(image, r, BG, FG, extendSupport);
617   }
618   //--------------------------------------------------------------------
619
620
621   //--------------------------------------------------------------------
622   template<class ImageType>
623   typename ImageType::Pointer 
624   Dilate(const ImageType * image, typename ImageType::PointType radiusInMM, 
625          typename ImageType::PixelType BG, 
626          typename ImageType::PixelType FG, 
627          bool extendSupport)
628   {
629     typename ImageType::SizeType r;
630     for(uint i=0; i<ImageType::ImageDimension; i++) 
631       r[i] = (uint)lrint(radiusInMM[i]/image->GetSpacing()[i]);
632     return Dilate<ImageType>(image, r, BG, FG, extendSupport);
633   }
634   //--------------------------------------------------------------------
635
636
637   //--------------------------------------------------------------------
638   template<class ImageType>
639   typename ImageType::Pointer 
640   Dilate(const ImageType * image, typename ImageType::SizeType radius, 
641          typename ImageType::PixelType BG, 
642          typename ImageType::PixelType FG, 
643          bool extendSupport)
644   {
645     // Create kernel for dilatation
646     typedef itk::BinaryBallStructuringElement<typename ImageType::PixelType, 
647                                               ImageType::ImageDimension> KernelType;
648     KernelType structuringElement;
649     structuringElement.SetRadius(radius);
650     structuringElement.CreateStructuringElement();
651
652     typename ImageType::Pointer output;
653     if (extendSupport) {
654       typedef itk::ConstantPadImageFilter<ImageType, ImageType> PadFilterType;
655       typename PadFilterType::Pointer padFilter = PadFilterType::New();
656       padFilter->SetInput(image);
657       typename ImageType::SizeType lower;
658       typename ImageType::SizeType upper;
659       for(uint i=0; i<3; i++) {
660         lower[i] = upper[i] = 2*(radius[i]+1);
661       }
662       padFilter->SetPadLowerBound(lower);
663       padFilter->SetPadUpperBound(upper);
664       padFilter->Update();
665       output = padFilter->GetOutput();
666     }
667
668     // Dilate  filter
669     typedef itk::BinaryDilateImageFilter<ImageType, ImageType , KernelType> DilateFilterType;
670     typename DilateFilterType::Pointer dilateFilter = DilateFilterType::New();
671     dilateFilter->SetBackgroundValue(BG);
672     dilateFilter->SetForegroundValue(FG);
673     dilateFilter->SetBoundaryToForeground(false);
674     dilateFilter->SetKernel(structuringElement);
675     if (extendSupport) dilateFilter->SetInput(output);
676     else dilateFilter->SetInput(image);
677     dilateFilter->Update();
678     return dilateFilter->GetOutput();
679   }
680   //--------------------------------------------------------------------
681
682
683   //--------------------------------------------------------------------
684   template<class ImageType>
685   typename ImageType::Pointer 
686   Opening(const ImageType * image, typename ImageType::SizeType radius,
687          typename ImageType::PixelType BG,
688          typename ImageType::PixelType FG)
689   {
690     // Kernel 
691     typedef itk::BinaryBallStructuringElement<typename ImageType::PixelType, 
692                                               ImageType::ImageDimension> KernelType;    
693     KernelType structuringElement;
694     structuringElement.SetRadius(radius);
695     structuringElement.CreateStructuringElement();
696     
697     // Filter
698     typedef itk::BinaryMorphologicalOpeningImageFilter<ImageType, ImageType , KernelType> OpeningFilterType;
699     typename OpeningFilterType::Pointer open = OpeningFilterType::New();
700     open->SetInput(image);
701     open->SetBackgroundValue(BG);
702     open->SetForegroundValue(FG);
703     open->SetKernel(structuringElement);
704     open->Update();
705     return open->GetOutput();
706   }
707   //--------------------------------------------------------------------
708
709
710
711   //--------------------------------------------------------------------
712   template<class ValueType, class VectorType>
713   void ConvertOption(std::string optionName, uint given, 
714                      ValueType * values, VectorType & p, 
715                      uint dim, bool required) 
716   {
717     if (required && (given == 0)) {
718       clitkExceptionMacro("The option --" << optionName << " must be set and have 1 or " 
719                           << dim << " values.");
720     }
721     if (given == 1) {
722       for(uint i=0; i<dim; i++) p[i] = values[0];
723       return;
724     }
725     if (given == dim) {
726       for(uint i=0; i<dim; i++) p[i] = values[i];
727       return;
728     }
729     if (given == 0) return;
730     clitkExceptionMacro("The option --" << optionName << " must have 1 or " 
731                         << dim << " values.");
732   }
733   //--------------------------------------------------------------------
734
735
736   //--------------------------------------------------------------------
737   /*
738     http://www.gamedev.net/community/forums/topic.asp?topic_id=542870
739     Assuming the points are (Ax,Ay) (Bx,By) and (Cx,Cy), you need to compute:
740     (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax)
741     This will equal zero if the point C is on the line formed by
742     points A and B, and will have a different sign depending on the
743     side. Which side this is depends on the orientation of your (x,y)
744     coordinates, but you can plug test values for A,B and C into this
745     formula to determine whether negative values are to the left or to
746     the right.
747     => to accelerate, start with formula, when change sign -> stop and fill
748
749     offsetToKeep = is used to determine which side of the line we
750     keep. The point along the mainDirection but 'offsetToKeep' mm away
751     is kept.
752   
753   */
754   template<class ImageType>
755   void 
756   SliceBySliceSetBackgroundFromLineSeparation(ImageType * input, 
757                                               std::vector<typename ImageType::PointType> & lA, 
758                                               std::vector<typename ImageType::PointType> & lB, 
759                                               typename ImageType::PixelType BG, 
760                                               int mainDirection, 
761                                               double offsetToKeep)
762   {
763     assert((mainDirection==0) || (mainDirection==1));
764     typedef itk::ImageSliceIteratorWithIndex<ImageType> SliceIteratorType;
765     SliceIteratorType siter = SliceIteratorType(input, 
766                                                 input->GetLargestPossibleRegion());
767     siter.SetFirstDirection(0);
768     siter.SetSecondDirection(1);
769     siter.GoToBegin();
770     uint i=0;
771     typename ImageType::PointType A;
772     typename ImageType::PointType B;
773     typename ImageType::PointType C;
774     assert(lA.size() == lB.size());
775     while ((i<lA.size()) && (!siter.IsAtEnd())) {
776       // Check that the current slice correspond to the current point
777       input->TransformIndexToPhysicalPoint(siter.GetIndex(), C);
778       if ((fabs(C[2] - lA[i][2]))>0.01) { // is !equal with a tolerance of 0.01 mm
779       }
780       else {
781         // Define A,B,C points
782         A = lA[i];
783         B = lB[i];
784         C = A;
785       
786         // Check that the line is not a point (A=B)
787         bool p = (A[0] == B[0]) && (A[1] == B[1]);
788       
789         if (!p) {
790           C[mainDirection] += offsetToKeep; // I know I must keep this point
791           double s = (B[0] - A[0]) * (C[1] - A[1]) - (B[1] - A[1]) * (C[0] - A[0]);
792           bool isPositive = s<0;
793           while (!siter.IsAtEndOfSlice()) {
794             while (!siter.IsAtEndOfLine()) {
795               // Very slow, I know ... but image should be very small
796               input->TransformIndexToPhysicalPoint(siter.GetIndex(), C);
797               double s = (B[0] - A[0]) * (C[1] - A[1]) - (B[1] - A[1]) * (C[0] - A[0]);
798               if (s == 0) siter.Set(BG); // on the line, we decide to remove
799               if (isPositive) {
800                 if (s > 0) siter.Set(BG);
801               }
802               else {
803                 if (s < 0) siter.Set(BG); 
804               }
805               ++siter;
806             }
807             siter.NextLine();
808           } // end loop slice
809         }      
810
811         ++i;
812       } // End of current slice
813       siter.NextSlice();
814     }
815   }                                                   
816   //--------------------------------------------------------------------
817
818
819   //--------------------------------------------------------------------
820   template<class ImageType>
821   void 
822   AndNot(ImageType * input, 
823          const ImageType * object, 
824          typename ImageType::PixelType BG)
825   {
826     typename ImageType::Pointer o;
827     bool resized=false;
828     if (!clitk::HaveSameSizeAndSpacing<ImageType, ImageType>(input, object)) {
829       o = clitk::ResizeImageLike<ImageType>(object, input, BG);
830       resized = true;
831     }
832
833     typedef clitk::BooleanOperatorLabelImageFilter<ImageType> BoolFilterType;
834     typename BoolFilterType::Pointer boolFilter = BoolFilterType::New(); 
835     boolFilter->InPlaceOn();
836     boolFilter->SetInput1(input);
837     if (resized) boolFilter->SetInput2(o);  
838     else boolFilter->SetInput2(object);
839     boolFilter->SetBackgroundValue1(BG);
840     boolFilter->SetBackgroundValue2(BG);
841     boolFilter->SetOperationType(BoolFilterType::AndNot);
842     boolFilter->Update();
843   }
844   //--------------------------------------------------------------------
845
846
847   //--------------------------------------------------------------------
848   template<class ImageType>
849   void 
850   And(ImageType * input, 
851       const ImageType * object, 
852       typename ImageType::PixelType BG)
853   {
854     typename ImageType::Pointer o;
855     bool resized=false;
856     if (!clitk::HaveSameSizeAndSpacing<ImageType, ImageType>(input, object)) {
857       o = clitk::ResizeImageLike<ImageType>(object, input, BG);
858       resized = true;
859     }
860
861     typedef clitk::BooleanOperatorLabelImageFilter<ImageType> BoolFilterType;
862     typename BoolFilterType::Pointer boolFilter = BoolFilterType::New(); 
863     boolFilter->InPlaceOn();
864     boolFilter->SetInput1(input);
865     if (resized) boolFilter->SetInput2(o);  
866     else boolFilter->SetInput2(object);
867     boolFilter->SetBackgroundValue1(BG);
868     boolFilter->SetBackgroundValue2(BG);
869     boolFilter->SetOperationType(BoolFilterType::And);
870     boolFilter->Update();
871   }
872   //--------------------------------------------------------------------
873
874
875   //--------------------------------------------------------------------
876   template<class ImageType>
877   void 
878   Or(ImageType * input, 
879      const ImageType * object, 
880      typename ImageType::PixelType BG)
881   {
882     typename ImageType::Pointer o;
883     bool resized=false;
884     if (!clitk::HaveSameSizeAndSpacing<ImageType, ImageType>(input, object)) {
885       o = clitk::ResizeImageLike<ImageType>(object, input, BG);
886       resized = true;
887     }
888
889     typedef clitk::BooleanOperatorLabelImageFilter<ImageType> BoolFilterType;
890     typename BoolFilterType::Pointer boolFilter = BoolFilterType::New(); 
891     boolFilter->InPlaceOn();
892     boolFilter->SetInput1(input);
893     if (resized) boolFilter->SetInput2(o);  
894     else boolFilter->SetInput2(object);
895     boolFilter->SetBackgroundValue1(BG);
896     boolFilter->SetBackgroundValue2(BG);
897     boolFilter->SetOperationType(BoolFilterType::Or);
898     boolFilter->Update();
899   }
900   //--------------------------------------------------------------------
901
902
903   //--------------------------------------------------------------------
904   template<class ImageType>
905   typename ImageType::Pointer
906   Binarize(const ImageType * input, 
907            typename ImageType::PixelType lower, 
908            typename ImageType::PixelType upper, 
909            typename ImageType::PixelType BG,
910            typename ImageType::PixelType FG) 
911   {
912     typedef itk::BinaryThresholdImageFilter<ImageType, ImageType> BinaryThresholdFilterType;
913     typename BinaryThresholdFilterType::Pointer binarizeFilter = BinaryThresholdFilterType::New();
914     binarizeFilter->SetInput(input);
915     binarizeFilter->InPlaceOff();
916     binarizeFilter->SetLowerThreshold(lower);
917     binarizeFilter->SetUpperThreshold(upper);
918     binarizeFilter->SetInsideValue(FG);
919     binarizeFilter->SetOutsideValue(BG);
920     binarizeFilter->Update();
921     return binarizeFilter->GetOutput();
922   }
923   //--------------------------------------------------------------------
924
925
926   //--------------------------------------------------------------------
927   template<class ImageType>
928   void
929   GetMinMaxPointPosition(const ImageType * input, 
930                          typename ImageType::PointType & min,
931                          typename ImageType::PointType & max) 
932   {
933     typename ImageType::IndexType index = input->GetLargestPossibleRegion().GetIndex();
934     input->TransformIndexToPhysicalPoint(index, min);
935     index = index+input->GetLargestPossibleRegion().GetSize();
936     input->TransformIndexToPhysicalPoint(index, max);
937   }
938   //--------------------------------------------------------------------
939
940
941   //--------------------------------------------------------------------
942   template<class ImageType>
943   typename ImageType::PointType
944   FindExtremaPointInAGivenLine(const ImageType * input, 
945                                int dimension, 
946                                bool inverse, 
947                                typename ImageType::PointType p, 
948                                typename ImageType::PixelType BG, 
949                                double distanceMax) 
950   {
951     // Which direction ?  Increasing or decreasing.
952     int d=1;
953     if (inverse) d=-1;
954   
955     // Transform to pixel index
956     typename ImageType::IndexType index;
957     input->TransformPhysicalPointToIndex(p, index);
958
959     // Loop while inside the mask;
960     while (input->GetPixel(index) != BG) {
961       index[dimension] += d;
962     }
963
964     // Transform back to Physical Units
965     typename ImageType::PointType result;
966     input->TransformIndexToPhysicalPoint(index, result);
967
968     // Check that is is not too far away
969     double distance = p.EuclideanDistanceTo(result);
970     if (distance > distanceMax) {
971       result = p; // Get back to initial value
972     }
973
974     return result;
975   }
976   //--------------------------------------------------------------------
977
978
979   //--------------------------------------------------------------------
980   template<class PointType>
981   bool
982   IsOnTheSameLineSide(PointType C, PointType A, PointType B, PointType like) 
983   {
984     // Look at the position of point 'like' according to the AB line
985     double s = (B[0] - A[0]) * (like[1] - A[1]) - (B[1] - A[1]) * (like[0] - A[0]);
986     bool negative = s<0;
987   
988     // Look the C position
989     s = (B[0] - A[0]) * (C[1] - A[1]) - (B[1] - A[1]) * (C[0] - A[0]);
990
991     if (negative && (s<=0)) return true;
992     if (!negative && (s>=0)) return true;
993     return false;
994   }
995   //--------------------------------------------------------------------
996
997
998   //--------------------------------------------------------------------
999   /* Consider an input object, for each slice, find the extrema
1000      position according to a given direction and build a line segment
1001      passing throught this point in a given direction.  Output is a
1002      vector of line (from point A to B), for each slice;
1003    */
1004   template<class ImageType>
1005   void 
1006   SliceBySliceBuildLineSegmentAccordingToExtremaPosition(const ImageType * input, 
1007                                                          typename ImageType::PixelType BG, 
1008                                                          int sliceDimension, 
1009                                                          int extremaDirection, 
1010                                                          bool extremaOppositeFlag, 
1011                                                          int lineDirection,
1012                                                          double margin,
1013                                                          std::vector<typename ImageType::PointType> & A, 
1014                                                          std::vector<typename ImageType::PointType> & B)
1015   {
1016     // Type of a slice
1017     typedef typename itk::Image<typename ImageType::PixelType, ImageType::ImageDimension-1> SliceType;
1018     
1019     // Build the list of slices
1020     std::vector<typename SliceType::Pointer> slices;
1021     clitk::ExtractSlices<ImageType>(input, sliceDimension, slices);
1022
1023     // Build the list of 2D points
1024     std::map<int, typename SliceType::PointType> position2D;
1025     for(uint i=0; i<slices.size(); i++) {
1026       typename SliceType::PointType p;
1027       bool found = 
1028         clitk::FindExtremaPointInAGivenDirection<SliceType>(slices[i], BG, 
1029                                                             extremaDirection, extremaOppositeFlag, p);
1030       if (found) {
1031         position2D[i] = p;
1032       }
1033     }
1034     
1035     // Convert 2D points in slice into 3D points
1036     clitk::PointsUtils<ImageType>::Convert2DMapTo3DList(position2D, input, A);
1037     
1038     // Create additional point just right to the previous ones, on the
1039     // given lineDirection, in order to create a horizontal/vertical line.
1040     for(uint i=0; i<A.size(); i++) {
1041       typename ImageType::PointType p = A[i];
1042       p[lineDirection] += 10;
1043       B.push_back(p);
1044       // Margins ?
1045       A[i][extremaDirection] += margin;
1046       B[i][extremaDirection] += margin;
1047     }
1048
1049   }
1050   //--------------------------------------------------------------------
1051
1052
1053   //--------------------------------------------------------------------
1054   template<class ImageType>
1055   typename ImageType::Pointer
1056   SliceBySliceKeepMainCCL(const ImageType * input, 
1057                           typename ImageType::PixelType BG,
1058                           typename ImageType::PixelType FG)  {
1059     
1060     // Extract slices
1061     const int d = ImageType::ImageDimension-1;
1062     typedef typename itk::Image<typename ImageType::PixelType, d> SliceType;
1063     std::vector<typename SliceType::Pointer> slices;
1064     clitk::ExtractSlices<ImageType>(input, d, slices);
1065     
1066     // Labelize and keep the main one
1067     std::vector<typename SliceType::Pointer> o;
1068     for(uint i=0; i<slices.size(); i++) {
1069       o.push_back(clitk::Labelize<SliceType>(slices[i], BG, false, 1));
1070       o[i] = clitk::KeepLabels<SliceType>(o[i], BG, FG, 1, 1, true);
1071     }
1072     
1073     // Join slices
1074     typename ImageType::Pointer output;
1075     output = clitk::JoinSlices<ImageType>(o, input, d);
1076     return output;
1077   }
1078   //--------------------------------------------------------------------
1079
1080
1081   //--------------------------------------------------------------------
1082   template<class ImageType>
1083   typename ImageType::Pointer
1084   Clone(const ImageType * input) {
1085     typedef itk::ImageDuplicator<ImageType> DuplicatorType;
1086     typename DuplicatorType::Pointer duplicator = DuplicatorType::New();
1087     duplicator->SetInputImage(input);
1088     duplicator->Update();
1089     return duplicator->GetOutput();
1090   }
1091   //--------------------------------------------------------------------
1092
1093
1094   //--------------------------------------------------------------------
1095   /* Consider an input object, start at A, for each slice (dim1): 
1096      - compute the intersection between the AB line and the current slice
1097      - remove what is at lower or greater according to dim2 of this point
1098      - stop at B
1099   */
1100   template<class ImageType>
1101   typename ImageType::Pointer
1102   SliceBySliceSetBackgroundFromSingleLine(const ImageType * input, 
1103                                           typename ImageType::PixelType BG, 
1104                                           typename ImageType::PointType & A, 
1105                                           typename ImageType::PointType & B, 
1106                                           int dim1, int dim2, bool removeLowerPartFlag)
1107     
1108   {
1109     // Extract slices
1110     typedef typename itk::Image<typename ImageType::PixelType, ImageType::ImageDimension-1> SliceType;
1111     typedef typename SliceType::Pointer SlicePointer;
1112     std::vector<SlicePointer> slices;
1113     clitk::ExtractSlices<ImageType>(input, dim1, slices);
1114
1115     // Start at slice that contains A, and stop at B
1116     typename ImageType::IndexType Ap;
1117     typename ImageType::IndexType Bp;
1118     input->TransformPhysicalPointToIndex(A, Ap);
1119     input->TransformPhysicalPointToIndex(B, Bp);
1120     
1121     // Determine slice largest region
1122     typename SliceType::RegionType region = slices[0]->GetLargestPossibleRegion();
1123     typename SliceType::SizeType size = region.GetSize();
1124     typename SliceType::IndexType index = region.GetIndex();
1125
1126     // Line slope
1127     double a = (Bp[dim2]-Ap[dim2])/(Bp[dim1]-Ap[dim1]);
1128     double b = Ap[dim2];
1129
1130     // Loop from slice A to slice B
1131     for(uint i=0; i<(Bp[dim1]-Ap[dim1]); i++) {
1132       // Compute intersection between line AB and current slice for the dim2
1133       double p = a*i+b;
1134       // Change region (lower than dim2)
1135       if (removeLowerPartFlag) {
1136         size[dim2] = p-Ap[dim2];
1137       }
1138       else {
1139         size[dim2] = slices[0]->GetLargestPossibleRegion().GetSize()[dim2]-p;
1140         index[dim2] = p;
1141       }
1142       region.SetSize(size);
1143       region.SetIndex(index);
1144       // Fill region with BG (simple region iterator)
1145       FillRegionWithValue<SliceType>(slices[i+Ap[dim1]], BG, region);
1146       /*
1147       typedef itk::ImageRegionIterator<SliceType> IteratorType;
1148       IteratorType iter(slices[i+Ap[dim1]], region);
1149       iter.GoToBegin();
1150       while (!iter.IsAtEnd()) {
1151         iter.Set(BG);
1152         ++iter;
1153       }
1154       */
1155       // Loop
1156     }
1157     
1158     // Merge slices
1159     typename ImageType::Pointer output;
1160     output = clitk::JoinSlices<ImageType>(slices, input, dim1);
1161     return output;
1162   }
1163   //--------------------------------------------------------------------
1164
1165   //--------------------------------------------------------------------
1166   /* Consider an input object, slice by slice, use the point A and set
1167      pixel to BG according to their position relatively to A
1168   */
1169   template<class ImageType>
1170   typename ImageType::Pointer
1171   SliceBySliceSetBackgroundFromPoints(const ImageType * input, 
1172                                       typename ImageType::PixelType BG, 
1173                                       int sliceDim,
1174                                       std::vector<typename ImageType::PointType> & A, 
1175                                       bool removeGreaterThanXFlag,
1176                                       bool removeGreaterThanYFlag)
1177     
1178   {
1179     // Extract slices
1180     typedef typename itk::Image<typename ImageType::PixelType, ImageType::ImageDimension-1> SliceType;
1181     typedef typename SliceType::Pointer SlicePointer;
1182     std::vector<SlicePointer> slices;
1183     clitk::ExtractSlices<ImageType>(input, sliceDim, slices);
1184
1185     // Start at slice that contains A
1186     typename ImageType::IndexType Ap;
1187     
1188     // Determine slice largest region
1189     typename SliceType::RegionType region = slices[0]->GetLargestPossibleRegion();
1190     typename SliceType::SizeType size = region.GetSize();
1191     typename SliceType::IndexType index = region.GetIndex();
1192
1193     // Loop from slice A to slice B
1194     for(uint i=0; i<A.size(); i++) {
1195       input->TransformPhysicalPointToIndex(A[i], Ap);
1196       uint sliceIndex = Ap[2] - input->GetLargestPossibleRegion().GetIndex()[2];
1197       if ((sliceIndex < 0) || (sliceIndex >= slices.size())) {
1198         continue; // do not consider this slice
1199       }
1200       
1201       // Compute region for BG
1202       if (removeGreaterThanXFlag) {
1203         index[0] = Ap[0];
1204         size[0] = region.GetSize()[0]-(index[0]-region.GetIndex()[0]);
1205       }
1206       else {
1207         index[0] = region.GetIndex()[0];
1208         size[0] = Ap[0] - index[0];
1209       }
1210
1211       if (removeGreaterThanYFlag) {
1212         index[1] = Ap[1];
1213         size[1] = region.GetSize()[1]-(index[1]-region.GetIndex()[1]);
1214       }
1215       else {
1216         index[1] = region.GetIndex()[1];
1217         size[1] = Ap[1] - index[1];
1218       }
1219
1220       // Set region
1221       region.SetSize(size);
1222       region.SetIndex(index);
1223
1224       // Fill region with BG (simple region iterator)
1225       FillRegionWithValue<SliceType>(slices[sliceIndex], BG, region);
1226       // Loop
1227     }
1228     
1229     // Merge slices
1230     typename ImageType::Pointer output;
1231     output = clitk::JoinSlices<ImageType>(slices, input, sliceDim);
1232     return output;
1233   }
1234   //--------------------------------------------------------------------
1235
1236
1237   //--------------------------------------------------------------------
1238   template<class ImageType>
1239   void
1240   FillRegionWithValue(ImageType * input, typename ImageType::PixelType value, typename ImageType::RegionType & region)
1241   {
1242     typedef itk::ImageRegionIterator<ImageType> IteratorType;
1243     IteratorType iter(input, region);
1244     iter.GoToBegin();
1245     while (!iter.IsAtEnd()) {
1246       iter.Set(value);
1247       ++iter;
1248     }    
1249   }
1250   //--------------------------------------------------------------------
1251
1252
1253   //--------------------------------------------------------------------
1254   template<class ImageType>
1255   void
1256   GetMinMaxBoundary(ImageType * input, typename ImageType::PointType & min, 
1257                     typename ImageType::PointType & max)
1258   {
1259     typedef typename ImageType::PointType PointType;
1260     typedef typename ImageType::IndexType IndexType;
1261     IndexType min_i, max_i;
1262     min_i = input->GetLargestPossibleRegion().GetIndex();
1263     for(uint i=0; i<ImageType::ImageDimension; i++)
1264       max_i[i] = input->GetLargestPossibleRegion().GetSize()[i] + min_i[i];
1265     input->TransformIndexToPhysicalPoint(min_i, min);
1266     input->TransformIndexToPhysicalPoint(max_i, max);  
1267   }
1268   //--------------------------------------------------------------------
1269
1270
1271   //--------------------------------------------------------------------
1272   template<class ImageType>
1273   typename itk::Image<float, ImageType::ImageDimension>::Pointer
1274   DistanceMap(const ImageType * input, typename ImageType::PixelType BG)//, 
1275   //              typename itk::Image<float, ImageType::ImageDimension>::Pointer dmap) 
1276   {
1277     typedef itk::Image<float,ImageType::ImageDimension> FloatImageType;
1278     typedef itk::SignedMaurerDistanceMapImageFilter<ImageType, FloatImageType> DistanceMapFilterType;
1279     typename DistanceMapFilterType::Pointer filter = DistanceMapFilterType::New();
1280     filter->SetInput(input);
1281     filter->SetUseImageSpacing(true);
1282     filter->SquaredDistanceOff();
1283     filter->SetBackgroundValue(BG);
1284     filter->Update();
1285     return filter->GetOutput();
1286   }
1287   //--------------------------------------------------------------------
1288
1289
1290   //--------------------------------------------------------------------
1291   template<class ImageType>
1292   void 
1293   SliceBySliceBuildLineSegmentAccordingToMinimalDistanceBetweenStructures(const ImageType * S1, 
1294                                                                           const ImageType * S2, 
1295                                                                           typename ImageType::PixelType BG, 
1296                                                                           int sliceDimension, 
1297                                                                           std::vector<typename ImageType::PointType> & A, 
1298                                                                           std::vector<typename ImageType::PointType> & B)
1299   {
1300     // Extract slices
1301     typedef typename itk::Image<typename ImageType::PixelType, 2> SliceType;
1302     typedef typename SliceType::Pointer SlicePointer;
1303     std::vector<SlicePointer> slices_s1;
1304     std::vector<SlicePointer> slices_s2;
1305     clitk::ExtractSlices<ImageType>(S1, sliceDimension, slices_s1);
1306     clitk::ExtractSlices<ImageType>(S2, sliceDimension, slices_s2);
1307
1308     assert(slices_s1.size() == slices_s2.size());
1309
1310     // Prepare dmap
1311     typedef itk::Image<float,2> FloatImageType;
1312     typedef itk::SignedMaurerDistanceMapImageFilter<SliceType, FloatImageType> DistanceMapFilterType;
1313     std::vector<typename FloatImageType::Pointer> dmaps1;
1314     std::vector<typename FloatImageType::Pointer> dmaps2;
1315     typename FloatImageType::Pointer dmap;
1316
1317     // loop on slices
1318     for(uint i=0; i<slices_s1.size(); i++) {
1319       // Compute dmap for S1 *TO PUT IN FONCTION*
1320       dmap = clitk::DistanceMap<SliceType>(slices_s1[i], BG);
1321       dmaps1.push_back(dmap);
1322       writeImage<FloatImageType>(dmap, "dmap1.mha");
1323       // Compute dmap for S2
1324       dmap = clitk::DistanceMap<SliceType>(slices_s2[i], BG);
1325       dmaps2.push_back(dmap);
1326       writeImage<FloatImageType>(dmap, "dmap2.mha");
1327       
1328       // Look in S2 for the point the closest to S1
1329       typename SliceType::PointType p = ComputeClosestPoint<SliceType>(slices_s1[i], dmaps2[i], BG);
1330       typename ImageType::PointType p3D;
1331       clitk::PointsUtils<ImageType>::Convert2DTo3D(p, S1, i, p3D);
1332       A.push_back(p3D);
1333
1334       // Look in S2 for the point the closest to S1
1335       p = ComputeClosestPoint<SliceType>(slices_s2[i], dmaps1[i], BG);
1336       clitk::PointsUtils<ImageType>::Convert2DTo3D(p, S2, i, p3D);
1337       B.push_back(p3D);
1338
1339     }
1340
1341     // Debug dmap
1342     /*
1343       typedef itk::Image<float,3> FT;
1344       FT::Pointer f = FT::New();
1345       typename FT::Pointer d1 = clitk::JoinSlices<FT>(dmaps1, S1, 2);
1346       typename FT::Pointer d2 = clitk::JoinSlices<FT>(dmaps2, S2, 2);
1347       writeImage<FT>(d1, "d1.mha");
1348       writeImage<FT>(d2, "d2.mha");
1349     */
1350   }
1351   //--------------------------------------------------------------------
1352
1353
1354   //--------------------------------------------------------------------
1355   template<class ImageType>
1356   typename ImageType::PointType
1357   ComputeClosestPoint(const ImageType * input, 
1358                       const itk::Image<float, ImageType::ImageDimension> * dmap, 
1359                       typename ImageType::PixelType & BG) 
1360   {
1361     // Loop dmap + S2, if FG, get min
1362     typedef itk::Image<float,ImageType::ImageDimension> FloatImageType;
1363     typedef itk::ImageRegionConstIteratorWithIndex<ImageType> ImageIteratorType;
1364     typedef itk::ImageRegionConstIterator<FloatImageType> DMapIteratorType;
1365     ImageIteratorType iter1(input, input->GetLargestPossibleRegion());
1366     DMapIteratorType iter2(dmap, dmap->GetLargestPossibleRegion());
1367     
1368     iter1.GoToBegin();
1369     iter2.GoToBegin();
1370     double dmin = 100000.0;
1371     typename ImageType::IndexType indexmin;
1372     while (!iter1.IsAtEnd()) {
1373       if (iter1.Get() != BG) {
1374         double d = iter2.Get();
1375         if (d<dmin) {
1376           indexmin = iter1.GetIndex();
1377           dmin = d;
1378         }
1379       }
1380       ++iter1;
1381       ++iter2;
1382     }
1383     
1384     // Convert in Point
1385     typename ImageType::PointType p;
1386     input->TransformIndexToPhysicalPoint(indexmin, p);
1387     return p;
1388   }
1389   //--------------------------------------------------------------------
1390      
1391
1392
1393
1394 } // end of namespace
1395