]> Creatis software - clitk.git/blob - itk/clitkSegmentationUtils.txx
add lineseparation
[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://oncora1.lyon.fnclcc.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
36 //--------------------------------------------------------------------
37 template<class ImageType>
38 void clitk::ComputeBBFromImageRegion(typename ImageType::Pointer image, 
39                                      typename ImageType::RegionType region,
40                                      typename itk::BoundingBox<unsigned long, 
41                                                                ImageType::ImageDimension>::Pointer bb) {
42   typedef typename ImageType::IndexType IndexType;
43   IndexType firstIndex;
44   IndexType lastIndex;
45   for(unsigned int i=0; i<image->GetImageDimension(); i++) {
46     firstIndex[i] = region.GetIndex()[i];
47     lastIndex[i] = firstIndex[i]+region.GetSize()[i];
48   }
49
50   typedef itk::BoundingBox<unsigned long, 
51                            ImageType::ImageDimension> BBType;
52   typedef typename BBType::PointType PointType;
53   PointType lastPoint;
54   PointType firstPoint;
55   image->TransformIndexToPhysicalPoint(firstIndex, firstPoint);
56   image->TransformIndexToPhysicalPoint(lastIndex, lastPoint);
57
58   bb->SetMaximum(lastPoint);
59   bb->SetMinimum(firstPoint);
60 }
61 //--------------------------------------------------------------------
62
63
64 //--------------------------------------------------------------------
65 template<int Dimension>
66 void clitk::ComputeBBIntersection(typename itk::BoundingBox<unsigned long, Dimension>::Pointer bbo, 
67                                   typename itk::BoundingBox<unsigned long, Dimension>::Pointer bbi1, 
68                                   typename itk::BoundingBox<unsigned long, Dimension>::Pointer bbi2) {
69
70   typedef itk::BoundingBox<unsigned long, Dimension> BBType;
71   typedef typename BBType::PointType PointType;
72   PointType lastPoint;
73   PointType firstPoint;
74
75   for(unsigned int i=0; i<Dimension; i++) {
76     firstPoint[i] = std::max(bbi1->GetMinimum()[i], 
77                              bbi2->GetMinimum()[i]);
78     lastPoint[i] = std::min(bbi1->GetMaximum()[i], 
79                             bbi2->GetMaximum()[i]);
80   }
81
82   bbo->SetMaximum(lastPoint);
83   bbo->SetMinimum(firstPoint);
84 }
85 //--------------------------------------------------------------------
86
87
88 //--------------------------------------------------------------------
89 template<class ImageType>
90 void clitk::ComputeRegionFromBB(typename ImageType::Pointer image, 
91                                 const typename itk::BoundingBox<unsigned long, 
92                                 ImageType::ImageDimension>::Pointer bb, 
93                                 typename ImageType::RegionType & region) {
94   // Types
95   typedef typename ImageType::IndexType  IndexType;
96   typedef typename ImageType::PointType  PointType;
97   typedef typename ImageType::RegionType RegionType;
98   typedef typename ImageType::SizeType   SizeType;
99
100   // Region starting point
101   IndexType regionStart;
102   PointType start = bb->GetMinimum();
103   image->TransformPhysicalPointToIndex(start, regionStart);
104     
105   // Region size
106   SizeType regionSize;
107   PointType maxs = bb->GetMaximum();
108   PointType mins = bb->GetMinimum();
109   for(unsigned int i=0; i<ImageType::ImageDimension; i++) {
110     // DD(maxs[i]);
111     // DD(mins[i]);
112     // DD((maxs[i] - mins[i])/image->GetSpacing()[i]);
113     regionSize[i] = lrint((maxs[i] - mins[i])/image->GetSpacing()[i]);
114     // DD(regionSize[i]);
115   }
116    
117   // Create region
118   region.SetIndex(regionStart);
119   region.SetSize(regionSize);
120 }
121 //--------------------------------------------------------------------
122
123 //--------------------------------------------------------------------
124 template<class ImageType, class TMaskImageType>
125 typename ImageType::Pointer
126 clitk::SetBackground(const ImageType * input, 
127                      const TMaskImageType * mask, 
128                      typename TMaskImageType::PixelType maskBG,
129                      typename ImageType::PixelType outValue, 
130                      bool inPlace) {
131   typedef clitk::SetBackgroundImageFilter<ImageType, TMaskImageType, ImageType> 
132     SetBackgroundImageFilterType;
133   typename SetBackgroundImageFilterType::Pointer setBackgroundFilter 
134     = SetBackgroundImageFilterType::New();
135   //  if (inPlace) setBackgroundFilter->ReleaseDataFlagOn(); // No seg fault
136   setBackgroundFilter->SetInPlace(inPlace); // This is important to keep memory low
137   setBackgroundFilter->SetInput(input);
138   setBackgroundFilter->SetInput2(mask);
139   setBackgroundFilter->SetMaskValue(maskBG);
140   setBackgroundFilter->SetOutsideValue(outValue);
141   setBackgroundFilter->Update();
142   return setBackgroundFilter->GetOutput();
143 }
144 //--------------------------------------------------------------------
145
146
147 //--------------------------------------------------------------------
148 template<class ImageType>
149 int clitk::GetNumberOfConnectedComponentLabels(typename ImageType::Pointer input, 
150                                                typename ImageType::PixelType BG, 
151                                                bool isFullyConnected) {
152   // Connected Component label 
153   typedef itk::ConnectedComponentImageFilter<ImageType, ImageType> ConnectFilterType;
154   typename ConnectFilterType::Pointer connectFilter = ConnectFilterType::New();
155   connectFilter->SetInput(input);
156   connectFilter->SetBackgroundValue(BG);
157   connectFilter->SetFullyConnected(isFullyConnected);
158   connectFilter->Update();
159   
160   // Return result
161   return connectFilter->GetObjectCount();
162 }
163 //--------------------------------------------------------------------
164
165 //--------------------------------------------------------------------
166 /*
167   Warning : in this cas, we consider outputType like inputType, not
168   InternalImageType. Be sure it fits.
169  */
170 template<class ImageType>
171 typename ImageType::Pointer
172 clitk::Labelize(const ImageType * input, 
173                 typename ImageType::PixelType BG, 
174                 bool isFullyConnected, 
175                 int minimalComponentSize) {
176   // InternalImageType for storing large number of component
177   typedef itk::Image<int, ImageType::ImageDimension> InternalImageType;
178   
179   // Connected Component label 
180   typedef itk::ConnectedComponentImageFilter<ImageType, InternalImageType> ConnectFilterType;
181   typename ConnectFilterType::Pointer connectFilter = ConnectFilterType::New();
182   //  connectFilter->ReleaseDataFlagOn(); 
183   connectFilter->SetInput(input);
184   connectFilter->SetBackgroundValue(BG);
185   connectFilter->SetFullyConnected(isFullyConnected);
186   
187   // Sort by size and remove too small area.
188   typedef itk::RelabelComponentImageFilter<InternalImageType, ImageType> RelabelFilterType;
189   typename RelabelFilterType::Pointer relabelFilter = RelabelFilterType::New();
190   //  relabelFilter->ReleaseDataFlagOn(); // if yes, fail when ExplosionControlledThresholdConnectedImageFilter ???
191   relabelFilter->SetInput(connectFilter->GetOutput());
192   relabelFilter->SetMinimumObjectSize(minimalComponentSize);
193   relabelFilter->Update();
194
195   // Return result
196   typename ImageType::Pointer output = relabelFilter->GetOutput();
197   return output;
198 }
199 //--------------------------------------------------------------------
200
201
202 //--------------------------------------------------------------------
203 template<class ImageType>
204 typename ImageType::Pointer
205 clitk::RemoveLabels(typename ImageType::Pointer input, 
206                     typename ImageType::PixelType BG,
207                     std::vector<typename ImageType::PixelType> & labelsToRemove) {
208   typename ImageType::Pointer working_image = input;
209   for (unsigned int i=0; i <labelsToRemove.size(); i++) {
210     typedef clitk::SetBackgroundImageFilter<ImageType, ImageType> SetBackgroundImageFilterType;
211     typename SetBackgroundImageFilterType::Pointer setBackgroundFilter = SetBackgroundImageFilterType::New();
212     setBackgroundFilter->SetInput(input);
213     setBackgroundFilter->SetInput2(input);
214     setBackgroundFilter->SetMaskValue(labelsToRemove[i]);
215     setBackgroundFilter->SetOutsideValue(BG);
216     setBackgroundFilter->Update();
217     working_image = setBackgroundFilter->GetOutput();
218   }
219   return working_image;
220 }
221 //--------------------------------------------------------------------
222
223
224 //--------------------------------------------------------------------
225 template<class ImageType>
226 typename ImageType::Pointer
227 clitk::KeepLabels(const ImageType * input, 
228                   typename ImageType::PixelType BG, 
229                   typename ImageType::PixelType FG, 
230                   typename ImageType::PixelType firstKeep, 
231                   typename ImageType::PixelType lastKeep, 
232                   bool useLastKeep) {
233   typedef itk::BinaryThresholdImageFilter<ImageType, ImageType> BinarizeFilterType; 
234   typename BinarizeFilterType::Pointer binarizeFilter = BinarizeFilterType::New();
235   binarizeFilter->SetInput(input);
236   binarizeFilter->SetLowerThreshold(firstKeep);
237   if (useLastKeep) binarizeFilter->SetUpperThreshold(lastKeep);
238   binarizeFilter->SetInsideValue(FG);
239   binarizeFilter->SetOutsideValue(BG);
240   binarizeFilter->Update();
241   return binarizeFilter->GetOutput();
242 }
243 //--------------------------------------------------------------------
244
245
246 //--------------------------------------------------------------------
247 template<class ImageType>
248 typename ImageType::Pointer
249 clitk::LabelizeAndSelectLabels(typename ImageType::Pointer input,
250                                typename ImageType::PixelType BG, 
251                                typename ImageType::PixelType FG, 
252                                bool isFullyConnected,
253                                int minimalComponentSize,
254                                LabelizeParameters<typename ImageType::PixelType> * param)
255 {
256   typename ImageType::Pointer working_image;
257   working_image = Labelize<ImageType>(input, BG, isFullyConnected, minimalComponentSize);
258   working_image = RemoveLabels<ImageType>(working_image, BG, param->GetLabelsToRemove());
259   working_image = KeepLabels<ImageType>(working_image, 
260                                         BG, FG, 
261                                         param->GetFirstKeep(), 
262                                         param->GetLastKeep(), 
263                                         param->GetUseLastKeep());
264   return working_image;
265 }
266 //--------------------------------------------------------------------
267
268
269 //--------------------------------------------------------------------
270 template<class ImageType>
271 typename ImageType::Pointer
272 clitk::ResizeImageLike(typename ImageType::Pointer input,
273                        typename ImageType::Pointer like, 
274                        typename ImageType::PixelType backgroundValue) 
275 {
276   typedef clitk::CropLikeImageFilter<ImageType> CropFilterType;
277   typename CropFilterType::Pointer cropFilter = CropFilterType::New();
278   cropFilter->SetInput(input);
279   cropFilter->SetCropLikeImage(like);
280   cropFilter->SetBackgroundValue(backgroundValue);
281   cropFilter->Update();
282   return cropFilter->GetOutput();  
283 }
284 //--------------------------------------------------------------------
285
286
287 //--------------------------------------------------------------------
288 template<class MaskImageType>
289 typename MaskImageType::Pointer
290 clitk::SliceBySliceRelativePosition(const MaskImageType * input,
291                                     const MaskImageType * object,
292                                     int direction, 
293                                     double threshold, 
294                                     std::string orientation, 
295                                     bool uniqueConnectedComponent, 
296                                     double spacing, 
297                                     bool inverseflag) 
298 {
299   typedef clitk::SliceBySliceRelativePositionFilter<MaskImageType> SliceRelPosFilterType;
300   typename SliceRelPosFilterType::Pointer sliceRelPosFilter = SliceRelPosFilterType::New();
301   sliceRelPosFilter->VerboseStepFlagOff();
302   sliceRelPosFilter->WriteStepFlagOff();
303   sliceRelPosFilter->SetInput(input);
304   sliceRelPosFilter->SetInputObject(object);
305   sliceRelPosFilter->SetDirection(direction);
306   sliceRelPosFilter->SetFuzzyThreshold(threshold);
307   sliceRelPosFilter->AddOrientationTypeString(orientation);
308   sliceRelPosFilter->SetResampleBeforeRelativePositionFilter((spacing != -1));
309   sliceRelPosFilter->SetIntermediateSpacing(spacing);
310   sliceRelPosFilter->SetUniqueConnectedComponentBySlice(uniqueConnectedComponent);
311   sliceRelPosFilter->SetInverseOrientationFlag(inverseflag);
312   //  sliceRelPosFilter->SetAutoCropFlag(true); ??
313   sliceRelPosFilter->Update();
314   return sliceRelPosFilter->GetOutput();
315 }
316 //--------------------------------------------------------------------
317
318 //--------------------------------------------------------------------
319 template<class ImageType>
320 bool
321 clitk::FindExtremaPointInAGivenDirection(const ImageType * input, 
322                                          typename ImageType::PixelType bg, 
323                                          int direction, bool opposite, 
324                                          typename ImageType::PointType & point)
325 {
326   typename ImageType::PointType dummy;
327   return clitk::FindExtremaPointInAGivenDirection(input, bg, direction, 
328                                                   opposite, dummy, 0, point);
329 }
330 //--------------------------------------------------------------------
331
332 //--------------------------------------------------------------------
333 template<class ImageType>
334 bool
335 clitk::FindExtremaPointInAGivenDirection(const ImageType * input, 
336                                          typename ImageType::PixelType bg, 
337                                          int direction, bool opposite, 
338                                          typename ImageType::PointType refpoint,
339                                          double distanceMax, 
340                                          typename ImageType::PointType & point)
341 {
342   /*
343     loop over input pixels, store the index in the fg that is max
344     according to the given direction. 
345   */
346   typedef itk::ImageRegionConstIteratorWithIndex<ImageType> IteratorType;
347   IteratorType iter(input, input->GetLargestPossibleRegion());
348   iter.GoToBegin();
349   typename ImageType::IndexType max = input->GetLargestPossibleRegion().GetIndex();
350   if (opposite) max = max+input->GetLargestPossibleRegion().GetSize();
351   bool found=false;
352   while (!iter.IsAtEnd()) {
353     if (iter.Get() != bg) {
354       bool test = iter.GetIndex()[direction] >  max[direction];
355       if (opposite) test = !test;
356       if (test) {
357         typename ImageType::PointType p;
358         input->TransformIndexToPhysicalPoint(iter.GetIndex(), p);
359         if ((distanceMax==0) || (p.EuclideanDistanceTo(refpoint) < distanceMax)) {
360           max = iter.GetIndex();
361           found = true;
362         }
363       }
364     }
365     ++iter;
366   }
367   if (!found) return false;
368   input->TransformIndexToPhysicalPoint(max, point);
369   return true;
370 }
371 //--------------------------------------------------------------------
372
373
374 //--------------------------------------------------------------------
375 template<class ImageType>
376 typename ImageType::Pointer
377 clitk::CropImageAbove(typename ImageType::Pointer image, 
378                       int dim, double min, 
379                       bool autoCrop,
380                       typename ImageType::PixelType BG) 
381 {
382   return clitk::CropImageAlongOneAxis<ImageType>(image, dim, 
383                                                  image->GetOrigin()[dim], 
384                                                  min,
385                                                  autoCrop, BG);
386 }
387 //--------------------------------------------------------------------
388
389
390 //--------------------------------------------------------------------
391 template<class ImageType>
392 typename ImageType::Pointer
393 clitk::CropImageBelow(typename ImageType::Pointer image, 
394                       int dim, double max, 
395                       bool autoCrop,
396                       typename ImageType::PixelType BG) 
397 {
398   typename ImageType::PointType p;
399   image->TransformIndexToPhysicalPoint(image->GetLargestPossibleRegion().GetIndex()+
400                                        image->GetLargestPossibleRegion().GetSize(), p);
401   return clitk::CropImageAlongOneAxis<ImageType>(image, dim, max, p[dim], autoCrop, BG);
402 }
403 //--------------------------------------------------------------------
404
405
406 //--------------------------------------------------------------------
407 template<class ImageType>
408 typename ImageType::Pointer
409 clitk::CropImageAlongOneAxis(typename ImageType::Pointer image, 
410                              int dim, double min, double max, 
411                              bool autoCrop,
412                              typename ImageType::PixelType BG) 
413 {
414   // Compute region size
415   typename ImageType::RegionType region;
416   typename ImageType::SizeType size = image->GetLargestPossibleRegion().GetSize();
417   typename ImageType::PointType p = image->GetOrigin();
418   p[dim] = min;
419   typename ImageType::IndexType start;
420   image->TransformPhysicalPointToIndex(p, start);
421   p[dim] = max;
422   typename ImageType::IndexType end;
423   image->TransformPhysicalPointToIndex(p, end);
424   size[dim] = fabs(end[dim]-start[dim]);
425   region.SetIndex(start);
426   region.SetSize(size);
427   
428   // Perform Crop
429   typedef itk::RegionOfInterestImageFilter<ImageType, ImageType> CropFilterType;
430   typename CropFilterType::Pointer cropFilter = CropFilterType::New();
431   cropFilter->SetInput(image);
432   cropFilter->SetRegionOfInterest(region);
433   cropFilter->Update();
434   typename ImageType::Pointer result = cropFilter->GetOutput();
435   
436   // Auto Crop
437   if (autoCrop) {
438     result = clitk::AutoCrop<ImageType>(result, BG);
439   }
440   return result;
441 }
442 //--------------------------------------------------------------------
443
444
445 //--------------------------------------------------------------------
446 template<class ImageType>
447 void
448 clitk::ComputeCentroids(typename ImageType::Pointer image, 
449                         typename ImageType::PixelType BG, 
450                         std::vector<typename ImageType::PointType> & centroids) 
451 {
452   typedef long LabelType;
453   static const unsigned int Dim = ImageType::ImageDimension;
454   typedef itk::ShapeLabelObject< LabelType, Dim > LabelObjectType;
455   typedef itk::LabelMap< LabelObjectType > LabelMapType;
456   typedef itk::LabelImageToLabelMapFilter<ImageType, LabelMapType> ImageToMapFilterType;
457   typename ImageToMapFilterType::Pointer imageToLabelFilter = ImageToMapFilterType::New(); 
458   typedef itk::ShapeLabelMapFilter<LabelMapType, ImageType> ShapeFilterType; 
459   typename ShapeFilterType::Pointer statFilter = ShapeFilterType::New();
460   imageToLabelFilter->SetBackgroundValue(BG);
461   imageToLabelFilter->SetInput(image);
462   statFilter->SetInput(imageToLabelFilter->GetOutput());
463   statFilter->Update();
464   typename LabelMapType::Pointer labelMap = statFilter->GetOutput();
465
466   centroids.clear();
467   typename ImageType::PointType dummy;
468   centroids.push_back(dummy); // label 0 -> no centroid, use dummy point
469   for(uint i=1; i<labelMap->GetNumberOfLabelObjects()+1; i++) {
470     centroids.push_back(labelMap->GetLabelObject(i)->GetCentroid());
471   } 
472 }
473 //--------------------------------------------------------------------
474
475
476 //--------------------------------------------------------------------
477 template<class ImageType>
478 void
479 clitk::ExtractSlices(typename ImageType::Pointer image, 
480                      int direction, 
481                      std::vector<typename itk::Image<typename ImageType::PixelType, 
482                      ImageType::ImageDimension-1>::Pointer > & slices) 
483 {
484   typedef clitk::ExtractSliceFilter<ImageType> ExtractSliceFilterType;
485   typedef typename ExtractSliceFilterType::SliceType SliceType;
486   typename ExtractSliceFilterType::Pointer 
487     extractSliceFilter = ExtractSliceFilterType::New();
488   extractSliceFilter->SetInput(image);
489   extractSliceFilter->SetDirection(direction);
490   extractSliceFilter->Update();
491   extractSliceFilter->GetOutputSlices(slices);
492 }
493 //--------------------------------------------------------------------
494
495
496 //--------------------------------------------------------------------
497 template<class ImageType>
498 typename ImageType::Pointer
499 clitk::JoinSlices(std::vector<typename itk::Image<typename ImageType::PixelType, 
500                   ImageType::ImageDimension-1>::Pointer > & slices, 
501                   typename ImageType::Pointer input, 
502                   int direction) {
503   typedef typename itk::Image<typename ImageType::PixelType, ImageType::ImageDimension-1> SliceType;
504   typedef itk::JoinSeriesImageFilter<SliceType, ImageType> JoinSeriesFilterType;
505   typename JoinSeriesFilterType::Pointer joinFilter = JoinSeriesFilterType::New();
506   joinFilter->SetOrigin(input->GetOrigin()[direction]);
507   joinFilter->SetSpacing(input->GetSpacing()[direction]);
508   for(unsigned int i=0; i<slices.size(); i++) {
509     joinFilter->PushBackInput(slices[i]);
510   }
511   joinFilter->Update();
512   return joinFilter->GetOutput();
513 }
514 //--------------------------------------------------------------------
515
516
517 //--------------------------------------------------------------------
518 template<class ImageType>
519 void
520 clitk::PointsUtils<ImageType>::Convert2DTo3D(const PointType2D & p, 
521                                              ImagePointer image, 
522                                              const int slice, 
523                                              PointType3D & p3D)  
524 {
525   p3D[0] = p[0]; 
526   p3D[1] = p[1];
527   p3D[2] = (image->GetLargestPossibleRegion().GetIndex()[2]+slice)*image->GetSpacing()[2] 
528     + image->GetOrigin()[2];
529 }
530 //--------------------------------------------------------------------
531
532
533 //--------------------------------------------------------------------
534 template<class ImageType>
535 void 
536 clitk::PointsUtils<ImageType>::Convert2DTo3DList(const MapPoint2DType & map, 
537                                                  ImagePointer image, 
538                                                  VectorPoint3DType & list)
539 {
540   typename MapPoint2DType::const_iterator iter = map.begin();
541   while (iter != map.end()) {
542     PointType3D p;
543     Convert2DTo3D(iter->second, image, iter->first, p);
544     list.push_back(p);
545     ++iter;
546   }
547 }
548 //--------------------------------------------------------------------
549
550 //--------------------------------------------------------------------
551 template<class ImageType>
552 void 
553 clitk::WriteListOfLandmarks(std::vector<typename ImageType::PointType> points, 
554                             std::string filename)
555 {
556   std::ofstream os; 
557   openFileForWriting(os, filename); 
558   os << "LANDMARKS1" << std::endl;  
559   for(uint i=0; i<points.size(); i++) {
560     const typename ImageType::PointType & p = points[i];
561     // Write it in the file
562     os << i << " " << p[0] << " " << p[1] << " " << p[2] << " 0 0 " << std::endl;
563   }
564   os.close();
565 }
566 //--------------------------------------------------------------------
567
568
569 //--------------------------------------------------------------------
570 template<class ImageType>
571 typename ImageType::Pointer 
572 clitk::Dilate(typename ImageType::Pointer image, 
573               double radiusInMM,               
574               typename ImageType::PixelType BG,
575               typename ImageType::PixelType FG,  
576               bool extendSupport)
577 {
578   typename ImageType::SizeType r;
579   for(uint i=0; i<ImageType::ImageDimension; i++) 
580     r[i] = (uint)lrint(radiusInMM/image->GetSpacing()[i]);
581   return clitk::Dilate<ImageType>(image, r, BG, FG, extendSupport);
582 }
583 //--------------------------------------------------------------------
584
585
586 //--------------------------------------------------------------------
587 template<class ImageType>
588 typename ImageType::Pointer 
589 clitk::Dilate(typename ImageType::Pointer image, 
590               typename ImageType::PointType radiusInMM, 
591               typename ImageType::PixelType BG, 
592               typename ImageType::PixelType FG, 
593               bool extendSupport)
594 {
595   typename ImageType::SizeType r;
596   for(uint i=0; i<ImageType::ImageDimension; i++) 
597     r[i] = (uint)lrint(radiusInMM[i]/image->GetSpacing()[i]);
598   return clitk::Dilate<ImageType>(image, r, BG, FG, extendSupport);
599 }
600 //--------------------------------------------------------------------
601
602
603 //--------------------------------------------------------------------
604 template<class ImageType>
605 typename ImageType::Pointer 
606 clitk::Dilate(typename ImageType::Pointer image, 
607               typename ImageType::SizeType radius, 
608               typename ImageType::PixelType BG, 
609               typename ImageType::PixelType FG, 
610               bool extendSupport)
611 {
612   // Create kernel for dilatation
613   typedef itk::BinaryBallStructuringElement<typename ImageType::PixelType, 
614                                             ImageType::ImageDimension> KernelType;
615   KernelType structuringElement;
616   structuringElement.SetRadius(radius);
617   structuringElement.CreateStructuringElement();
618
619   if (extendSupport) {
620     typedef itk::ConstantPadImageFilter<ImageType, ImageType> PadFilterType;
621     typename PadFilterType::Pointer padFilter = PadFilterType::New();
622     padFilter->SetInput(image);
623     typename ImageType::SizeType lower;
624     typename ImageType::SizeType upper;
625     for(uint i=0; i<3; i++) {
626       lower[i] = upper[i] = 2*(radius[i]+1);
627     }
628     padFilter->SetPadLowerBound(lower);
629     padFilter->SetPadUpperBound(upper);
630     padFilter->Update();
631     image = padFilter->GetOutput();
632   }
633
634   // Dilate  filter
635   typedef itk::BinaryDilateImageFilter<ImageType, ImageType , KernelType> DilateFilterType;
636   typename DilateFilterType::Pointer dilateFilter = DilateFilterType::New();
637   dilateFilter->SetBackgroundValue(BG);
638   dilateFilter->SetForegroundValue(FG);
639   dilateFilter->SetBoundaryToForeground(false);
640   dilateFilter->SetKernel(structuringElement);
641   dilateFilter->SetInput(image);
642   dilateFilter->Update();
643   return image = dilateFilter->GetOutput();
644 }
645 //--------------------------------------------------------------------
646
647
648 //--------------------------------------------------------------------
649 template<class ValueType, class VectorType>
650 void clitk::ConvertOption(std::string optionName, uint given, 
651                           ValueType * values, VectorType & p, 
652                           uint dim, bool required) 
653 {
654   if (required && (given == 0)) {
655     clitkExceptionMacro("The option --" << optionName << " must be set and have 1 or " 
656                         << dim << " values.");
657   }
658   if (given == 1) {
659     for(uint i=0; i<dim; i++) p[i] = values[0];
660     return;
661   }
662   if (given == dim) {
663     for(uint i=0; i<dim; i++) p[i] = values[i];
664     return;
665   }
666   if (given == 0) return;
667   clitkExceptionMacro("The option --" << optionName << " must have 1 or " 
668                       << dim << " values.");
669 }
670 //--------------------------------------------------------------------
671
672
673 //--------------------------------------------------------------------
674 /*
675   http://www.gamedev.net/community/forums/topic.asp?topic_id=542870
676   Assuming the points are (Ax,Ay) (Bx,By) and (Cx,Cy), you need to compute:
677   (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax)
678   This will equal zero if the point C is on the line formed by
679   points A and B, and will have a different sign depending on the
680   side. Which side this is depends on the orientation of your (x,y)
681   coordinates, but you can plug test values for A,B and C into this
682   formula to determine whether negative values are to the left or to
683   the right.
684   => to accelerate, start with formula, when change sign -> stop and fill
685 */
686 template<class ImageType>
687 void 
688 clitk::SliceBySliceSetBackgroundFromLineSeparation(typename ImageType::Pointer input, 
689                                                    std::vector<typename ImageType::PointType> & lA, 
690                                                    std::vector<typename ImageType::PointType> & lB, 
691                                                    typename ImageType::PixelType BG, 
692                                                    int mainDirection, 
693                                                    double offsetToKeep)
694 {
695   
696   typedef itk::ImageSliceIteratorWithIndex<ImageType> SliceIteratorType;
697   SliceIteratorType siter = SliceIteratorType(input, 
698                                               input->GetLargestPossibleRegion());
699   siter.SetFirstDirection(0);
700   siter.SetSecondDirection(1);
701   siter.GoToBegin();
702   uint i=0;
703   typename ImageType::PointType A;
704   typename ImageType::PointType B;
705   typename ImageType::PointType C;
706   assert(lA.size() == B.size());
707   //  DD(lA.size());
708   //DD(input->GetLargestPossibleRegion().GetSize());
709   while ((i<lA.size()) && (!siter.IsAtEnd())) {
710     // Check that the current slice correspond to the current point
711     input->TransformIndexToPhysicalPoint(siter.GetIndex(), C);
712     if (C[2] != lA[i][2]) {
713       // DD(C);
714       // DD(lA[i]);
715     }
716     else {
717       // Define A,B,C points
718       A = lA[i];
719       B = lB[i];
720       C = A;
721       C[mainDirection] += offsetToKeep; // I know I must keep this point
722       double s = (B[0] - A[0]) * (C[1] - A[1]) - (B[1] - A[1]) * (C[0] - A[0]);
723       bool isPositive = s<0;
724       while (!siter.IsAtEndOfSlice()) {
725         while (!siter.IsAtEndOfLine()) {
726           // Very slow, I know ... but image should be very small
727           input->TransformIndexToPhysicalPoint(siter.GetIndex(), C);
728           double s = (B[0] - A[0]) * (C[1] - A[1]) - (B[1] - A[1]) * (C[0] - A[0]);
729           if (s == 0) siter.Set(BG); // on the line, we decide to remove
730           if (isPositive) {
731             if (s > 0) siter.Set(BG);
732           }
733           else {
734             if (s < 0) siter.Set(BG); 
735           }
736           ++siter;
737         }
738         siter.NextLine();
739       }
740       ++i;
741     }
742     siter.NextSlice();
743   }
744 }                                                   
745 //--------------------------------------------------------------------