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://www.centreleonberard.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
24 //=========================================================================================================================
25 //helper class 1 to allow a threaded execution: add contributions of input to output and update weights
26 //=========================================================================================================================
27 template<class InputImageType, class OutputImageType> class ITK_EXPORT HelperClass1 : public itk::ImageToImageFilter<InputImageType, OutputImageType>
31 /** Standard class typedefs. */
32 typedef HelperClass1 Self;
33 typedef itk::ImageToImageFilter<InputImageType,OutputImageType> Superclass;
34 typedef itk::SmartPointer<Self> Pointer;
35 typedef itk::SmartPointer<const Self> ConstPointer;
37 /** Method for creation through the object factory. */
40 /** Run-time type information (and related methods) */
41 itkTypeMacro( HelperClass1, ImageToImageFilter );
43 /** Constants for the image dimensions */
44 itkStaticConstMacro(ImageDimension, unsigned int,InputImageType::ImageDimension);
48 typedef typename OutputImageType::PixelType PixelType;
49 typedef itk::Image<double, ImageDimension > WeightsImageType;
50 typedef itk::Image<itk::SimpleFastMutexLock, ImageDimension > MutexImageType;
52 //===================================================================================
54 void SetWeights(const typename WeightsImageType::Pointer input) {
58 void SetMutexImage(const typename MutexImageType::Pointer input) {
65 typename WeightsImageType::Pointer GetWeights() {
69 /** Typedef to describe the output image region type. */
70 typedef typename OutputImageType::RegionType OutputImageRegionType;
76 //the actual processing
77 void BeforeThreadedGenerateData();
78 void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId );
81 typename WeightsImageType::Pointer m_Weights;
82 typename MutexImageType::Pointer m_MutexImage;
89 //=========================================================================================================================
90 //Member functions of the helper class 1
91 //=========================================================================================================================
94 //=========================================================================================================================
96 template<class InputImageType, class OutputImageType >
97 HelperClass1<InputImageType, OutputImageType>::HelperClass1()
102 //=========================================================================================================================
103 //Before threaded data
104 template<class InputImageType, class OutputImageType >
105 void HelperClass1<InputImageType, OutputImageType>::BeforeThreadedGenerateData()
107 //std::cout << "HelperClass1::BeforeThreadedGenerateData - IN" << std::endl;
108 //Since we will add, put to zero!
109 this->GetOutput()->FillBuffer(itk::NumericTraits<double>::Zero);
110 this->GetWeights()->FillBuffer(itk::NumericTraits<double>::Zero);
113 //=========================================================================================================================
114 //update the output for the outputRegionForThread
115 template<class InputImageType, class OutputImageType>
116 void HelperClass1<InputImageType, OutputImageType>::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId )
118 //std::cout << "HelperClass1::ThreadedGenerateData - IN" << std::endl;
119 //Get pointer to the input
120 typename InputImageType::ConstPointer inputPtr = this->GetInput();
122 //Get pointer to the output
123 typename OutputImageType::Pointer outputPtr = this->GetOutput();
124 //typename OutputImageType::SizeType size=outputPtr->GetLargestPossibleRegion().GetSize();
126 //Iterator over input
127 typedef itk::ImageRegionConstIteratorWithIndex<InputImageType> InputImageIteratorType;
129 //define them over the outputRegionForThread
130 InputImageIteratorType inputIt(inputPtr, outputRegionForThread);
133 typename InputImageType::IndexType index;
134 itk::ContinuousIndex<double,ImageDimension> contIndex, inContIndex;
135 typename InputImageType::PointType ipoint;
136 typename OutputImageType::PointType opoint;
137 typedef typename OutputImageType::PixelType DisplacementType;
138 DisplacementType displacement;
141 //define some temp variables
142 signed long baseIndex[ImageDimension];
143 double distance[ImageDimension];
144 unsigned int dim, counter, upper;
145 double totalOverlap,overlap;
146 typename OutputImageType::IndexType neighIndex;
148 //Find the number of neighbors
149 unsigned int neighbors = 1 << ImageDimension;
151 //==================================================================================================
152 //Loop over the output region and add the intensities from the input to the output and the weight to the weights
153 //==================================================================================================
154 while( !inputIt.IsAtEnd() ) {
155 // get the input image index
156 index = inputIt.GetIndex();
157 inputPtr->TransformIndexToPhysicalPoint( index,ipoint );
159 // get the required displacement
160 displacement = inputIt.Get();
162 // compute the required output image point
163 for(unsigned int j = 0; j < ImageDimension; j++ ) opoint[j] = ipoint[j] + (double)displacement[j];
165 // Update the output and the weights
166 if(outputPtr->TransformPhysicalPointToContinuousIndex(opoint, contIndex ) ) {
167 for(dim = 0; dim < ImageDimension; dim++) {
168 // The following block is equivalent to the following line without
169 // having to call floor. (Only for positive inputs, we already now that is in the image)
170 // baseIndex[dim] = (long) vcl_floor(contIndex[dim] );
172 baseIndex[dim] = (long) contIndex[dim];
173 distance[dim] = contIndex[dim] - double( baseIndex[dim] );
176 //Add contribution for each neighbor
177 totalOverlap = itk::NumericTraits<double>::Zero;
178 for( counter = 0; counter < neighbors ; counter++ ) {
179 overlap = 1.0; // fraction overlap
180 upper = counter; // each bit indicates upper/lower neighbour
182 // get neighbor index and overlap fraction
183 for( dim = 0; dim < ImageDimension; dim++ ) {
185 neighIndex[dim] = baseIndex[dim] + 1;
186 overlap *= distance[dim];
188 neighIndex[dim] = baseIndex[dim];
189 overlap *= 1.0 - distance[dim];
196 //Set neighbor value only if overlap is not zero
197 if( (overlap>0.0)) // &&
198 // (static_cast<unsigned int>(neighIndex[0])<size[0]) &&
199 // (static_cast<unsigned int>(neighIndex[1])<size[1]) &&
200 // (static_cast<unsigned int>(neighIndex[2])<size[2]) &&
201 // (neighIndex[0]>=0) &&
202 // (neighIndex[1]>=0) &&
203 // (neighIndex[2]>=0) )
205 //what to store? the original displacement vector?
206 if (! m_ThreadSafe) {
207 //Set the pixel and weight at neighIndex
208 outputPtr->SetPixel(neighIndex, outputPtr->GetPixel(neighIndex) - (displacement*overlap));
209 m_Weights->SetPixel(neighIndex, m_Weights->GetPixel(neighIndex) + overlap);
213 //Entering critilal section: shared memory
214 m_MutexImage->GetPixel(neighIndex).Lock();
216 //Set the pixel and weight at neighIndex
217 outputPtr->SetPixel(neighIndex, outputPtr->GetPixel(neighIndex) - (displacement*overlap));
218 m_Weights->SetPixel(neighIndex, m_Weights->GetPixel(neighIndex) + overlap);
221 m_MutexImage->GetPixel(neighIndex).Unlock();
224 //Add to total overlap
225 totalOverlap += overlap;
228 if( totalOverlap == 1.0 ) {
238 //std::cout << "HelperClass1::ThreadedGenerateData - OUT" << std::endl;
243 //=========================================================================================================================
244 //helper class 2 to allow a threaded execution of normalisation by the weights
245 //=========================================================================================================================
246 template<class InputImageType, class OutputImageType> class HelperClass2 : public itk::ImageToImageFilter<InputImageType, OutputImageType>
250 /** Standard class typedefs. */
251 typedef HelperClass2 Self;
252 typedef itk::ImageToImageFilter<InputImageType,OutputImageType> Superclass;
253 typedef itk::SmartPointer<Self> Pointer;
254 typedef itk::SmartPointer<const Self> ConstPointer;
256 /** Method for creation through the object factory. */
259 /** Run-time type information (and related methods) */
260 itkTypeMacro( HelperClass2, ImageToImageFilter );
262 /** Constants for the image dimensions */
263 itkStaticConstMacro(ImageDimension, unsigned int,InputImageType::ImageDimension);
266 typedef typename OutputImageType::PixelType PixelType;
267 typedef itk::Image<double,ImageDimension> WeightsImageType;
270 void SetWeights(const typename WeightsImageType::Pointer input) {
274 void SetEdgePaddingValue(PixelType value) {
275 m_EdgePaddingValue = value;
279 /** Typedef to describe the output image region type. */
280 typedef typename OutputImageType::RegionType OutputImageRegionType;
287 //the actual processing
288 void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId );
292 typename WeightsImageType::Pointer m_Weights;
293 PixelType m_EdgePaddingValue;
299 //=========================================================================================================================
300 //Member functions of the helper class 2
301 //=========================================================================================================================
304 //=========================================================================================================================
306 template<class InputImageType, class OutputImageType > HelperClass2<InputImageType, OutputImageType>::HelperClass2()
308 m_EdgePaddingValue=itk::NumericTraits<PixelType>::Zero;
312 //=========================================================================================================================
313 //update the output for the outputRegionForThread
314 template<class InputImageType, class OutputImageType > void HelperClass2<InputImageType, OutputImageType>::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId )
316 //std::cout << "HelperClass2::ThreadedGenerateData - IN" << std::endl;
318 //Get pointer to the input
319 typename InputImageType::ConstPointer inputPtr = this->GetInput();
321 //Get pointer to the output
322 typename OutputImageType::Pointer outputPtr = this->GetOutput();
324 //Iterators over input, weigths and output
325 typedef itk::ImageRegionConstIterator<InputImageType> InputImageIteratorType;
326 typedef itk::ImageRegionIterator<OutputImageType> OutputImageIteratorType;
327 typedef itk::ImageRegionIterator<WeightsImageType> WeightsImageIteratorType;
329 //define them over the outputRegionForThread
330 OutputImageIteratorType outputIt(outputPtr, outputRegionForThread);
331 InputImageIteratorType inputIt(inputPtr, outputRegionForThread);
332 WeightsImageIteratorType weightsIt(m_Weights, outputRegionForThread);
335 //==================================================================================================
336 //loop over the output and normalize the input, remove holes
337 PixelType neighValue;
338 double zero = itk::NumericTraits<double>::Zero;
339 while (!outputIt.IsAtEnd()) {
340 //the weight is not zero
341 if (weightsIt.Get() != zero) {
342 //divide by the weight
343 outputIt.Set(static_cast<PixelType>(inputIt.Get()/weightsIt.Get()));
346 //copy the value of the neighbour that was just processed
348 if(!outputIt.IsAtBegin()) {
352 //Neighbour cannot have zero weight because it should be filled already
353 neighValue=outputIt.Get();
355 outputIt.Set(neighValue);
358 //DD("is at begin, setting edgepadding value");
359 outputIt.Set(m_EdgePaddingValue);
368 //std::cout << "HelperClass2::ThreadedGenerateData - OUT" << std::endl;
373 }//end nameless namespace
380 //=========================================================================================================================
381 // The rest is the InvertVFFilter
382 //=========================================================================================================================
384 //=========================================================================================================================
386 template <class InputImageType, class OutputImageType>
387 InvertVFFilter<InputImageType, OutputImageType>::InvertVFFilter()
389 m_EdgePaddingValue=itk::NumericTraits<PixelType>::Zero; //no other reasonable value?
394 //=========================================================================================================================
396 template <class InputImageType, class OutputImageType> void InvertVFFilter<InputImageType, OutputImageType>::GenerateData()
398 //std::cout << "InvertVFFilter::GenerateData - IN" << std::endl;
400 //Get the properties of the input
401 typename InputImageType::ConstPointer inputPtr=this->GetInput();
402 typename WeightsImageType::RegionType region = inputPtr->GetLargestPossibleRegion();
404 //Allocate the weights
405 typename WeightsImageType::Pointer weights=WeightsImageType::New();
406 weights->SetOrigin(inputPtr->GetOrigin());
407 weights->SetRegions(region);
409 weights->SetSpacing(inputPtr->GetSpacing());
411 //===========================================================================
412 //Inversion is divided in in two loops, for each we will call a threaded helper class
413 //1. add contribution of input to output and update weights
414 //2. normalize the output by the weight and remove holes
415 //===========================================================================
418 //===========================================================================
419 //1. add contribution of input to output and update weights
421 //Define an internal image type
423 typedef itk::Image<itk::Vector<double,ImageDimension>, ImageDimension > InternalImageType;
425 //Call threaded helper class 1
426 typedef HelperClass1<InputImageType, InternalImageType > HelperClass1Type;
427 typename HelperClass1Type::Pointer helper1=HelperClass1Type::New();
430 if(m_NumberOfThreadsIsGiven)helper1->SetNumberOfThreads(m_NumberOfThreads);
431 helper1->SetInput(inputPtr);
432 helper1->SetWeights(weights);
436 //Allocate the mutex image
437 typename MutexImageType::Pointer mutex=InvertVFFilter::MutexImageType::New();
438 mutex->SetRegions(region);
440 mutex->SetSpacing(inputPtr->GetSpacing());
441 helper1->SetMutexImage(mutex);
442 if (m_Verbose) std::cout <<"Inverting using a thread-safe algorithm" <<std::endl;
443 } else if(m_Verbose)std::cout <<"Inverting using a thread-unsafe algorithm" <<std::endl;
445 //Execute helper class
449 typename InternalImageType::Pointer temp= helper1->GetOutput();
450 weights=helper1->GetWeights();
453 //===========================================================================
454 //2. Normalize the output by the weights and remove holes
455 //Call threaded helper class
456 typedef HelperClass2<InternalImageType, OutputImageType> HelperClass2Type;
457 typename HelperClass2Type::Pointer helper2=HelperClass2Type::New();
459 //Set temporary output as input
460 helper2->SetInput(temp);
461 helper2->SetWeights(weights);
462 helper2->SetEdgePaddingValue(m_EdgePaddingValue);
464 //Execute helper class
465 if (m_Verbose) std::cout << "Normalizing the output VF..."<<std::endl;
469 this->SetNthOutput(0, helper2->GetOutput());