]> Creatis software - clitk.git/blob - itk/clitkRelativePositionAnalyzerFilter.txx
Moved from repository clitk to clitk.private/tests_dav
[clitk.git] / itk / clitkRelativePositionAnalyzerFilter.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 //--------------------------------------------------------------------
20 template <class ImageType>
21 clitk::RelativePositionAnalyzerFilter<ImageType>::
22 RelativePositionAnalyzerFilter():
23   itk::ImageToImageFilter<ImageType, ImageType>()
24 {
25   this->SetNumberOfRequiredInputs(3); // Input : support, object, target
26   SetBackgroundValue(0);
27   SetForegroundValue(1);
28   SetNumberOfBins(100);
29   SetAreaLossTolerance(0.01);
30   SetSupportSize(0);
31   SetTargetSize(0);
32   SetSizeWithThreshold(0);
33   SetSizeWithReverseThreshold(0);
34 }
35 //--------------------------------------------------------------------
36
37
38 //--------------------------------------------------------------------
39 template <class ImageType>
40 void 
41 clitk::RelativePositionAnalyzerFilter<ImageType>::
42 SetInputSupport(const ImageType * image) 
43 {
44   // Process object is not const-correct so the const casting is required.
45   this->SetNthInput(0, const_cast<ImageType *>(image));
46 }
47 //--------------------------------------------------------------------
48   
49
50 //--------------------------------------------------------------------
51 template <class ImageType>
52 void 
53 clitk::RelativePositionAnalyzerFilter<ImageType>::
54 SetInputObject(const ImageType * image) 
55 {
56   // Process object is not const-correct so the const casting is required.
57   this->SetNthInput(1, const_cast<ImageType *>(image));
58 }
59 //--------------------------------------------------------------------
60   
61
62 //--------------------------------------------------------------------
63 template <class ImageType>
64 void 
65 clitk::RelativePositionAnalyzerFilter<ImageType>::
66 SetInputTarget(const ImageType * image) 
67 {
68   // Process object is not const-correct so the const casting is required.
69   this->SetNthInput(2, const_cast<ImageType *>(image));
70 }
71 //--------------------------------------------------------------------
72   
73
74 //--------------------------------------------------------------------
75 template <class ImageType>
76 void 
77 clitk::RelativePositionAnalyzerFilter<ImageType>::
78 PrintOptions() 
79 {
80   DD("TODO");
81 }
82 //--------------------------------------------------------------------
83
84
85 //--------------------------------------------------------------------
86 template <class ImageType>
87 void 
88 clitk::RelativePositionAnalyzerFilter<ImageType>::
89 GenerateOutputInformation() 
90
91   ImagePointer input = dynamic_cast<ImageType*>(itk::ProcessObject::GetInput(0));
92   ImagePointer outputImage = this->GetOutput(0);
93   outputImage->SetRegions(outputImage->GetLargestPossibleRegion());
94 }
95 //--------------------------------------------------------------------
96
97
98 //--------------------------------------------------------------------
99 template <class ImageType>
100 void 
101 clitk::RelativePositionAnalyzerFilter<ImageType>::
102 GenerateData() 
103 {
104   ImagePointer temp = dynamic_cast<ImageType*>(itk::ProcessObject::GetInput(0));
105   m_Object = dynamic_cast<ImageType*>(itk::ProcessObject::GetInput(1));
106   ImagePointer temp2 = dynamic_cast<ImageType*>(itk::ProcessObject::GetInput(2));
107
108   // Remove object from support (keep initial image)
109   m_Support = clitk::Clone<ImageType>(temp);
110   clitk::AndNot<ImageType>(m_Support, m_Object, GetBackgroundValue());
111   
112   // Remove object from target. Important because sometimes, there is
113   // overlap between target and object.
114   m_Target = clitk::Clone<ImageType>(temp2);
115   clitk::AndNot<ImageType>(m_Target, m_Object, GetBackgroundValue());
116   
117   // Define filter to compute statics on mask image
118   typedef itk::LabelStatisticsImageFilter<ImageType, ImageType> StatFilterType;
119   typename StatFilterType::Pointer statFilter = StatFilterType::New();
120
121   // Compute the initial support size
122   statFilter->SetInput(m_Support);
123   statFilter->SetLabelInput(m_Support);
124   statFilter->Update();
125   SetSupportSize(statFilter->GetCount(GetForegroundValue()));
126   // DD(GetSupportSize());
127   
128   // Compute the initial target size
129   ImagePointer s = clitk::ResizeImageLike<ImageType>(m_Support, m_Target, GetBackgroundValue());
130   statFilter->SetInput(s);
131   statFilter->SetLabelInput(m_Target);
132   statFilter->Update();
133   SetTargetSize(statFilter->GetCount(GetForegroundValue()));
134   // DD(GetTargetSize());
135
136   //
137   int bins = GetNumberOfBins();
138   double tolerance = GetAreaLossTolerance();
139
140   // Compute Fuzzy map
141   double angle = GetDirection().angle1;
142   typename FloatImageType::Pointer map = ComputeFuzzyMap(m_Object, m_Target, m_Support, angle);
143   writeImage<FloatImageType>(map, "fuzzy_"+toString(clitk::rad2deg(angle))+".mha");
144
145   // Compute the optimal thresholds (direct and inverse)
146   double mThreshold=0.0;
147   double mReverseThreshold=1.0;
148   ComputeOptimalThresholds(map, m_Target, bins, tolerance, mThreshold, mReverseThreshold);
149
150   // DD(mThreshold);
151   // DD(mReverseThreshold);
152
153   // Use the threshold to compute new support
154   int s1 = GetSupportSize();
155   if (mThreshold > 0.0) {
156     ImagePointer support1 = 
157       clitk::SliceBySliceRelativePosition<ImageType>(m_Support, m_Object, 2, 
158                                                      mThreshold,
159                                                      angle,false, // inverseFlag
160                                                      false,  // uniqueConnectedComponent
161                                                      -1, true, 
162                                                      false);//singleObjectCCL
163     // Compute the new support size
164     statFilter->SetInput(support1);
165     statFilter->SetLabelInput(support1);
166     statFilter->Update();
167     s1 = statFilter->GetCount(GetForegroundValue());
168   }
169   
170   int s2 = GetSupportSize();
171   if (mReverseThreshold < 1.0) {
172     ImagePointer support2 = 
173       clitk::SliceBySliceRelativePosition<ImageType>(m_Support, m_Object, 2, 
174                                                      mReverseThreshold, 
175                                                      angle,true,// inverseFlag
176                                                      false, // uniqueConnectedComponent
177                                                      -1, true, 
178                                                      false); //singleObjectCCL
179     // Compute the new support size
180     statFilter = StatFilterType::New();
181     statFilter->SetInput(support2);
182     statFilter->SetLabelInput(support2);
183     statFilter->Update();
184     s2 = statFilter->GetCount(GetForegroundValue());
185   }
186   
187   // Check threshold, if we gain nothing, we force to max/min thresholds
188   // DD(GetSupportSize());
189   // DD(s1);
190   // DD(s2);
191   if (s1 >= GetSupportSize()) mThreshold = 0.0;
192   if (s2 >= GetSupportSize()) mReverseThreshold = 1.0;
193
194   // Set results values
195   m_Info.threshold = mThreshold;
196   m_Info.sizeAfterThreshold = s1;
197   m_Info.sizeBeforeThreshold = GetSupportSize();
198   m_Info.sizeReference = GetTargetSize();
199   m_InfoReverse.threshold = mReverseThreshold;
200   m_InfoReverse.sizeAfterThreshold = s2;
201   m_InfoReverse.sizeBeforeThreshold = GetSupportSize();
202   m_InfoReverse.sizeReference = GetTargetSize();  
203 }
204 //--------------------------------------------------------------------
205
206
207 //--------------------------------------------------------------------
208 template <class ImageType>
209 typename clitk::RelativePositionAnalyzerFilter<ImageType>::FloatImageType::Pointer
210 clitk::RelativePositionAnalyzerFilter<ImageType>::
211 ComputeFuzzyMap(ImageType * object, ImageType * target, ImageType * support, double angle)
212 {
213   typedef clitk::SliceBySliceRelativePositionFilter<ImageType> SliceRelPosFilterType;
214   typedef typename SliceRelPosFilterType::FloatImageType FloatImageType;
215   typename SliceRelPosFilterType::Pointer sliceRelPosFilter = SliceRelPosFilterType::New();
216   sliceRelPosFilter->VerboseStepFlagOff();
217   sliceRelPosFilter->WriteStepFlagOff();
218   sliceRelPosFilter->SetInput(support);
219   sliceRelPosFilter->SetInputObject(object);
220   sliceRelPosFilter->SetDirection(2);
221   sliceRelPosFilter->SetIntermediateSpacingFlag(false);
222   //sliceRelPosFilter->AddOrientationTypeString(orientation);
223   sliceRelPosFilter->AddAnglesInRad(angle, 0.0);
224   sliceRelPosFilter->FuzzyMapOnlyFlagOn(); // do not threshold, only compute the fuzzy map
225   // sliceRelPosFilter->PrintOptions();
226   sliceRelPosFilter->Update();
227   typename FloatImageType::Pointer map = sliceRelPosFilter->GetFuzzyMap();
228   writeImage<FloatImageType>(map, "fuzzy_0_"+toString(clitk::rad2deg(angle))+".mha");
229
230   // Resize object like map to allow SetBackground
231   ImagePointer temp = clitk::ResizeImageLike<ImageType>(object, map, GetBackgroundValue());
232   //  writeImage<FloatImageType>(map, "fuzzy_1_"+toString(clitk::rad2deg(angle))+".mha");
233   
234   // Remove initial object from the fuzzy map
235   map = clitk::SetBackground<FloatImageType, ImageType>(map, temp, GetForegroundValue(), 0.0, true);
236   writeImage<FloatImageType>(map, "fuzzy_2_"+toString(clitk::rad2deg(angle))+".mha");
237   
238   // Resize the fuzzy map like the target, put 2.0 when outside
239   map = clitk::ResizeImageLike<FloatImageType>(map, target, 2.0);  // Put 2.0 when out of initial map
240   writeImage<FloatImageType>(map, "fuzzy_3_"+toString(clitk::rad2deg(angle))+".mha");
241   
242   // end
243   return map;
244 }
245 //--------------------------------------------------------------------
246
247
248 //--------------------------------------------------------------------
249 template <class ImageType>
250 void
251 clitk::RelativePositionAnalyzerFilter<ImageType>::
252 ComputeOptimalThresholds(FloatImageType * map, ImageType * target, int bins, double tolerance, 
253                          double & threshold, double & reverseThreshold)
254 {
255   // Get the histogram of fuzzy values inside the target image
256   typedef itk::LabelStatisticsImageFilter<FloatImageType, ImageType> FloatStatFilterType;
257   typename FloatStatFilterType::Pointer f = FloatStatFilterType::New();
258   f->SetInput(map);
259   f->SetLabelInput(target);
260   f->UseHistogramsOn();
261   f->SetHistogramParameters(bins, 0.0-(1.0/bins), 1.0+(1.0/bins));
262   f->Update();
263   int count = f->GetCount(GetForegroundValue());
264   // DD(count);
265   typename FloatStatFilterType::HistogramPointer h = f->GetHistogram(GetForegroundValue());
266
267   // Debug : dump histogram
268   static int i=0;
269   std::ofstream histogramFile(std::string("fuzzy_histo_"+toString(i)+".txt").c_str());
270   for(int j=0; j<bins; j++) {
271     histogramFile << h->GetMeasurement(j,0) 
272                   << "\t" << h->GetFrequency(j) 
273                   << "\t" << (double)h->GetFrequency(j)/(double)count << std::endl;
274   }
275   histogramFile.close();  
276   std::ofstream histogramFile2(std::string("fuzzy_histo_R_"+toString(i)+".txt").c_str());
277   for(int j=bins-1; j>=0; j--) {
278     histogramFile2 << h->GetMeasurement(j,0) 
279                   << "\t" << h->GetFrequency(j) 
280                   << "\t" << (double)h->GetFrequency(j)/(double)count << std::endl;
281   }
282   histogramFile2.close();  
283   i++;
284
285   // Analyze the histogram (direct)
286   double sum = 0.0;
287   bool found = false;
288   threshold = 0.0;
289   for(int j=0; j<bins-1; j++) {
290     sum += ((double)h->GetFrequency(j)/(double)count);
291      // DD(j);
292      // DD(sum);
293      // DD(threshold);
294      // DD(h->GetBinMin(0,j));
295      // DD(h->GetBinMax(0,j));
296     if ((!found) && (sum > tolerance)) {
297       // We consider as threshold the laste before current, because 
298       if (j==0) 
299         threshold = h->GetBinMin(0,j);
300       else threshold = h->GetBinMin(0,j-1); // FIXME  ? the last before reaching the threshold
301       // DD(threshold);
302       found = true;
303       j = bins;
304     }
305   }
306
307   // Analyze the histogram (reverse)
308   sum = 0.0;
309   found = false;
310   reverseThreshold = 1.0;
311   for(int j=bins-1; j>0; j--) {
312     sum += ((double)h->GetFrequency(j)/(double)count);
313      // DD(j);
314      // DD(sum);
315      // DD(reverseThreshold);
316      // DD(h->GetBinMin(0,j));
317      // DD(h->GetBinMax(0,j));
318     if ((!found) && (sum > tolerance)) {
319       if (j==bins-1) 
320       reverseThreshold = h->GetBinMax(0,j);
321       else reverseThreshold = h->GetBinMax(0,j-1);// FIXME  ? the last before reaching the threshold
322       // DD(reverseThreshold);
323       found = true;
324       j = -1;
325     }
326   }
327
328 }
329 //--------------------------------------------------------------------
330