1 /*=========================================================================
2 Program: vv http://www.creatis.insa-lyon.fr/rio/vv
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
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.
13 It is distributed under dual licence
15 - BSD See included LICENSE.txt file
16 - CeCILL-B http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
17 ======================================================================-====*/
18 #ifndef __clitkInvertVFFilter_txx
19 #define __clitkInvertVFFilter_txx
23 //=========================================================================================================================
24 //helper class 1 to allow a threaded execution: add contributions of input to output and update weights
25 //=========================================================================================================================
26 template<class InputImageType, class OutputImageType> class ITK_EXPORT HelperClass1 : public itk::ImageToImageFilter<InputImageType, OutputImageType>
30 /** Standard class typedefs. */
31 typedef HelperClass1 Self;
32 typedef itk::ImageToImageFilter<InputImageType,OutputImageType> Superclass;
33 typedef itk::SmartPointer<Self> Pointer;
34 typedef itk::SmartPointer<const Self> ConstPointer;
36 /** Method for creation through the object factory. */
39 /** Run-time type information (and related methods) */
40 itkTypeMacro( HelperClass1, ImageToImageFilter );
42 /** Constants for the image dimensions */
43 itkStaticConstMacro(ImageDimension, unsigned int,InputImageType::ImageDimension);
47 typedef typename OutputImageType::PixelType PixelType;
48 typedef itk::Image<double, ImageDimension > WeightsImageType;
49 typedef itk::Image<itk::SimpleFastMutexLock, ImageDimension > MutexImageType;
51 //===================================================================================
53 void SetWeights(const typename WeightsImageType::Pointer input)
58 void SetMutexImage(const typename MutexImageType::Pointer input)
66 typename WeightsImageType::Pointer GetWeights(){return m_Weights;}
68 /** Typedef to describe the output image region type. */
69 typedef typename OutputImageType::RegionType OutputImageRegionType;
75 //the actual processing
76 void BeforeThreadedGenerateData();
77 void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId );
80 typename WeightsImageType::Pointer m_Weights;
81 typename MutexImageType::Pointer m_MutexImage;
88 //=========================================================================================================================
89 //Member functions of the helper class 1
90 //=========================================================================================================================
93 //=========================================================================================================================
95 template<class InputImageType, class OutputImageType >
96 HelperClass1<InputImageType, OutputImageType>::HelperClass1()
101 //=========================================================================================================================
102 //Before threaded data
103 template<class InputImageType, class OutputImageType >
104 void HelperClass1<InputImageType, OutputImageType>::BeforeThreadedGenerateData()
106 //Since we will add, put to zero!
107 this->GetOutput()->FillBuffer(itk::NumericTraits<double>::Zero);
108 this->GetWeights()->FillBuffer(itk::NumericTraits<double>::Zero);
111 //=========================================================================================================================
112 //update the output for the outputRegionForThread
113 template<class InputImageType, class OutputImageType>
114 void HelperClass1<InputImageType, OutputImageType>::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId )
117 //Get pointer to the input
118 typename InputImageType::ConstPointer inputPtr = this->GetInput();
120 //Get pointer to the output
121 typename OutputImageType::Pointer outputPtr = this->GetOutput();
122 typename OutputImageType::SizeType size=outputPtr->GetLargestPossibleRegion().GetSize();
124 //Iterator over input
125 typedef itk::ImageRegionConstIteratorWithIndex<InputImageType> InputImageIteratorType;
127 //define them over the outputRegionForThread
128 InputImageIteratorType inputIt(inputPtr, outputRegionForThread);
131 typename InputImageType::IndexType index;
132 itk::ContinuousIndex<double,ImageDimension> contIndex;
133 typename InputImageType::PointType ipoint;
134 typename OutputImageType::PointType opoint;
135 typedef typename OutputImageType::PixelType DisplacementType;
136 DisplacementType displacement;
139 //define some temp variables
140 signed long baseIndex[ImageDimension];
141 double distance[ImageDimension];
142 unsigned int dim, counter, upper;
143 double totalOverlap,overlap;
144 typename OutputImageType::IndexType neighIndex;
146 //Find the number of neighbors
147 unsigned int neighbors = 1 << ImageDimension;
149 //==================================================================================================
150 //Loop over the region and add the intensities to the output and the weight to the weights
151 //==================================================================================================
152 while( !inputIt.IsAtEnd() )
154 // get the input image index
155 index = inputIt.GetIndex();
156 inputPtr->TransformIndexToPhysicalPoint( index,ipoint );
158 // get the required displacement
159 displacement = inputIt.Get();
161 // compute the required output image point
162 for(unsigned int j = 0; j < ImageDimension; j++ ) opoint[j] = ipoint[j] + (double)displacement[j];
164 // Update the output and the weights
165 if(outputPtr->TransformPhysicalPointToContinuousIndex(opoint, contIndex ) )
167 for(dim = 0; dim < ImageDimension; dim++)
169 // The following block is equivalent to the following line without
170 // having to call floor. (Only for positive inputs, we already now that is in the image)
171 // baseIndex[dim] = (long) vcl_floor(contIndex[dim] );
173 baseIndex[dim] = (long) contIndex[dim];
174 distance[dim] = contIndex[dim] - double( baseIndex[dim] );
177 //Add contribution for each neighbor
178 totalOverlap = itk::NumericTraits<double>::Zero;
179 for( counter = 0; counter < neighbors ; counter++ )
181 overlap = 1.0; // fraction overlap
182 upper = counter; // each bit indicates upper/lower neighbour
184 // get neighbor index and overlap fraction
185 for( dim = 0; dim < 3; dim++ )
189 neighIndex[dim] = baseIndex[dim] + 1;
190 overlap *= distance[dim];
194 neighIndex[dim] = baseIndex[dim];
195 overlap *= 1.0 - distance[dim];
202 //Set neighbor value only if overlap is not zero
203 if( (overlap>0.0)) // &&
204 // (static_cast<unsigned int>(neighIndex[0])<size[0]) &&
205 // (static_cast<unsigned int>(neighIndex[1])<size[1]) &&
206 // (static_cast<unsigned int>(neighIndex[2])<size[2]) &&
207 // (neighIndex[0]>=0) &&
208 // (neighIndex[1]>=0) &&
209 // (neighIndex[2]>=0) )
211 //what to store? the original displacement vector?
214 //Set the pixel and weight at neighIndex
215 outputPtr->SetPixel(neighIndex, outputPtr->GetPixel(neighIndex) - (displacement*overlap));
216 m_Weights->SetPixel(neighIndex, m_Weights->GetPixel(neighIndex) + overlap);
221 //Entering critilal section: shared memory
222 m_MutexImage->GetPixel(neighIndex).Lock();
224 //Set the pixel and weight at neighIndex
225 outputPtr->SetPixel(neighIndex, outputPtr->GetPixel(neighIndex) - (displacement*overlap));
226 m_Weights->SetPixel(neighIndex, m_Weights->GetPixel(neighIndex) + overlap);
229 m_MutexImage->GetPixel(neighIndex).Unlock();
232 //Add to total overlap
233 totalOverlap += overlap;
236 if( totalOverlap == 1.0 )
251 //=========================================================================================================================
252 //helper class 2 to allow a threaded execution of normalisation by the weights
253 //=========================================================================================================================
254 template<class InputImageType, class OutputImageType> class HelperClass2 : public itk::ImageToImageFilter<InputImageType, OutputImageType>
258 /** Standard class typedefs. */
259 typedef HelperClass2 Self;
260 typedef itk::ImageToImageFilter<InputImageType,OutputImageType> Superclass;
261 typedef itk::SmartPointer<Self> Pointer;
262 typedef itk::SmartPointer<const Self> ConstPointer;
264 /** Method for creation through the object factory. */
267 /** Run-time type information (and related methods) */
268 itkTypeMacro( HelperClass2, ImageToImageFilter );
270 /** Constants for the image dimensions */
271 itkStaticConstMacro(ImageDimension, unsigned int,InputImageType::ImageDimension);
274 typedef typename OutputImageType::PixelType PixelType;
275 typedef itk::Image<double,ImageDimension> WeightsImageType;
278 void SetWeights(const typename WeightsImageType::Pointer input)
283 void SetEdgePaddingValue(PixelType value)
285 m_EdgePaddingValue = value;
289 /** Typedef to describe the output image region type. */
290 typedef typename OutputImageType::RegionType OutputImageRegionType;
297 //the actual processing
298 void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId );
302 typename WeightsImageType::Pointer m_Weights;
303 PixelType m_EdgePaddingValue;
309 //=========================================================================================================================
310 //Member functions of the helper class 2
311 //=========================================================================================================================
314 //=========================================================================================================================
316 template<class InputImageType, class OutputImageType > HelperClass2<InputImageType, OutputImageType>::HelperClass2()
318 m_EdgePaddingValue=itk::NumericTraits<PixelType>::Zero;
322 //=========================================================================================================================
323 //update the output for the outputRegionForThread
324 template<class InputImageType, class OutputImageType > void HelperClass2<InputImageType, OutputImageType>::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId )
327 //Get pointer to the input
328 typename InputImageType::ConstPointer inputPtr = this->GetInput();
330 //Get pointer to the output
331 typename OutputImageType::Pointer outputPtr = this->GetOutput();
333 //Iterators over input, weigths and output
334 typedef itk::ImageRegionConstIterator<InputImageType> InputImageIteratorType;
335 typedef itk::ImageRegionIterator<OutputImageType> OutputImageIteratorType;
336 typedef itk::ImageRegionIterator<WeightsImageType> WeightsImageIteratorType;
338 //define them over the outputRegionForThread
339 OutputImageIteratorType outputIt(outputPtr, outputRegionForThread);
340 InputImageIteratorType inputIt(inputPtr, outputRegionForThread);
341 WeightsImageIteratorType weightsIt(m_Weights, outputRegionForThread);
344 //==================================================================================================
345 //loop over the output and normalize the input, remove holes
346 PixelType neighValue;
347 double zero = itk::NumericTraits<double>::Zero;
348 while (!outputIt.IsAtEnd())
350 //the weight is not zero
351 if (weightsIt.Get() != zero)
353 //divide by the weight
354 outputIt.Set(static_cast<PixelType>(inputIt.Get()/weightsIt.Get()));
357 //copy the value of the neighbour that was just processed
360 if(!outputIt.IsAtBegin())
365 //Neighbour cannot have zero weight because it should be filled already
366 neighValue=outputIt.Get();
368 outputIt.Set(neighValue);
372 //DD("is at begin, setting edgepadding value");
373 outputIt.Set(m_EdgePaddingValue);
384 }//end nameless namespace
391 //=========================================================================================================================
392 // The rest is the InvertVFFilter
393 //=========================================================================================================================
395 //=========================================================================================================================
397 template <class InputImageType, class OutputImageType>
398 InvertVFFilter<InputImageType, OutputImageType>::InvertVFFilter()
400 m_EdgePaddingValue=itk::NumericTraits<PixelType>::Zero; //no other reasonable value?
406 //=========================================================================================================================
408 template <class InputImageType, class OutputImageType> void InvertVFFilter<InputImageType, OutputImageType>::GenerateData()
411 //Get the properties of the input
412 typename InputImageType::ConstPointer inputPtr=this->GetInput();
413 typename WeightsImageType::RegionType region;
414 typename WeightsImageType::RegionType::SizeType size=inputPtr->GetLargestPossibleRegion().GetSize();
415 region.SetSize(size);
416 typename OutputImageType::IndexType start;
417 for (unsigned int i=0; i< ImageDimension; i++) start[i]=0;
418 region.SetIndex(start);
419 PixelType zero = itk::NumericTraits<double>::Zero;
422 //Allocate the weights
423 typename WeightsImageType::Pointer weights=WeightsImageType::New();
424 weights->SetRegions(region);
426 weights->SetSpacing(inputPtr->GetSpacing());
428 //===========================================================================
429 //Inversion is divided in in two loops, for each we will call a threaded helper class
430 //1. add contribution of input to output and update weights
431 //2. normalize the output by the weight and remove holes
432 //===========================================================================
435 //===========================================================================
436 //1. add contribution of input to output and update weights
438 //Define an internal image type
440 typedef itk::Image<itk::Vector<double,ImageDimension>, ImageDimension > InternalImageType;
442 //Call threaded helper class 1
443 typedef HelperClass1<InputImageType, InternalImageType > HelperClass1Type;
444 typename HelperClass1Type::Pointer helper1=HelperClass1Type::New();
447 if(m_NumberOfThreadsIsGiven)helper1->SetNumberOfThreads(m_NumberOfThreads);
448 helper1->SetInput(inputPtr);
449 helper1->SetWeights(weights);
454 //Allocate the mutex image
455 typename MutexImageType::Pointer mutex=InvertVFFilter::MutexImageType::New();
456 mutex->SetRegions(region);
458 mutex->SetSpacing(inputPtr->GetSpacing());
459 helper1->SetMutexImage(mutex);
460 if (m_Verbose) std::cout <<"Inverting using a thread-safe algorithm" <<std::endl;
462 else if(m_Verbose)std::cout <<"Inverting using a thread-unsafe algorithm" <<std::endl;
464 //Execute helper class
468 typename InternalImageType::Pointer temp= helper1->GetOutput();
469 weights=helper1->GetWeights();
472 //===========================================================================
473 //2. Normalize the output by the weights and remove holes
474 //Call threaded helper class
475 typedef HelperClass2<InternalImageType, OutputImageType> HelperClass2Type;
476 typename HelperClass2Type::Pointer helper2=HelperClass2Type::New();
478 //Set temporary output as input
479 helper2->SetInput(temp);
480 helper2->SetWeights(weights);
481 helper2->SetEdgePaddingValue(m_EdgePaddingValue);
483 //Execute helper class
484 if (m_Verbose) std::cout << "Normalizing the output VF..."<<std::endl;
488 this->SetNthOutput(0, helper2->GetOutput());