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, itk::ThreadIdType 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, itk::ThreadIdType threadId )
118 // std::cout << "HelperClass1::ThreadedGenerateData - IN " << threadId << 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 typename OutputImageType::SizeType size = outputPtr->GetLargestPossibleRegion().GetSize();
143 //define some temp variables
144 signed long baseIndex[ImageDimension];
145 double distance[ImageDimension];
146 unsigned int dim, counter, upper;
147 double totalOverlap,overlap;
148 typename OutputImageType::IndexType neighIndex;
150 //Find the number of neighbors
151 unsigned int neighbors = 1 << ImageDimension;
153 //==================================================================================================
154 //Loop over the output region and add the intensities from the input to the output and the weight to the weights
155 //==================================================================================================
156 while( !inputIt.IsAtEnd() ) {
157 // get the input image index
158 index = inputIt.GetIndex();
159 inputPtr->TransformIndexToPhysicalPoint( index,ipoint );
161 // get the required displacement
162 displacement = inputIt.Get();
164 // compute the required output image point
165 for(unsigned int j = 0; j < ImageDimension; j++ ) opoint[j] = ipoint[j] + (double)displacement[j];
167 // Update the output and the weights
168 if(outputPtr->TransformPhysicalPointToContinuousIndex(opoint, contIndex ) ) {
169 for(dim = 0; dim < ImageDimension; dim++) {
170 // The following block is equivalent to the following line without
171 // having to call floor. (Only for positive inputs, we already now that is in the image)
172 // baseIndex[dim] = (long) vcl_floor(contIndex[dim] );
174 baseIndex[dim] = (long) contIndex[dim];
175 distance[dim] = contIndex[dim] - double( baseIndex[dim] );
178 //Add contribution for each neighbor
179 totalOverlap = itk::NumericTraits<double>::Zero;
180 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 < ImageDimension; dim++ ) {
187 neighIndex[dim] = baseIndex[dim] + 1;
188 overlap *= distance[dim];
190 neighIndex[dim] = baseIndex[dim];
191 overlap *= 1.0 - distance[dim];
195 if (neighIndex[dim] >= size[dim])
196 neighIndex[dim] = size[dim] - 1;
200 //Set neighbor value only if overlap is not zero
201 if( (overlap>0.0)) // &&
202 // (static_cast<unsigned int>(neighIndex[0])<size[0]) &&
203 // (static_cast<unsigned int>(neighIndex[1])<size[1]) &&
204 // (static_cast<unsigned int>(neighIndex[2])<size[2]) &&
205 // (neighIndex[0]>=0) &&
206 // (neighIndex[1]>=0) &&
207 // (neighIndex[2]>=0) )
209 //what to store? the original displacement vector?
210 if (! m_ThreadSafe) {
211 //Set the pixel and weight at neighIndex
212 outputPtr->SetPixel(neighIndex, outputPtr->GetPixel(neighIndex) - (displacement*overlap));
213 m_Weights->SetPixel(neighIndex, m_Weights->GetPixel(neighIndex) + overlap);
217 //Entering critilal section: shared memory
218 m_MutexImage->GetPixel(neighIndex).Lock();
220 //Set the pixel and weight at neighIndex
221 outputPtr->SetPixel(neighIndex, outputPtr->GetPixel(neighIndex) - (displacement*overlap));
222 m_Weights->SetPixel(neighIndex, m_Weights->GetPixel(neighIndex) + overlap);
225 m_MutexImage->GetPixel(neighIndex).Unlock();
228 //Add to total overlap
229 totalOverlap += overlap;
232 if( totalOverlap == 1.0 ) {
242 // std::cout << "HelperClass1::ThreadedGenerateData - OUT " << threadId << std::endl;
247 //=========================================================================================================================
248 //helper class 2 to allow a threaded execution of normalisation by the weights
249 //=========================================================================================================================
250 template<class InputImageType, class OutputImageType> class HelperClass2 : public itk::ImageToImageFilter<InputImageType, OutputImageType>
254 /** Standard class typedefs. */
255 typedef HelperClass2 Self;
256 typedef itk::ImageToImageFilter<InputImageType,OutputImageType> Superclass;
257 typedef itk::SmartPointer<Self> Pointer;
258 typedef itk::SmartPointer<const Self> ConstPointer;
260 /** Method for creation through the object factory. */
263 /** Run-time type information (and related methods) */
264 itkTypeMacro( HelperClass2, ImageToImageFilter );
266 /** Constants for the image dimensions */
267 itkStaticConstMacro(ImageDimension, unsigned int,InputImageType::ImageDimension);
270 typedef typename OutputImageType::PixelType PixelType;
271 typedef itk::Image<double,ImageDimension> WeightsImageType;
274 void SetWeights(const typename WeightsImageType::Pointer input) {
278 void SetEdgePaddingValue(PixelType value) {
279 m_EdgePaddingValue = value;
283 /** Typedef to describe the output image region type. */
284 typedef typename OutputImageType::RegionType OutputImageRegionType;
291 //the actual processing
292 void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, itk::ThreadIdType threadId );
295 typename WeightsImageType::Pointer m_Weights;
296 PixelType m_EdgePaddingValue;
302 //=========================================================================================================================
303 //Member functions of the helper class 2
304 //=========================================================================================================================
307 //=========================================================================================================================
309 template<class InputImageType, class OutputImageType > HelperClass2<InputImageType, OutputImageType>::HelperClass2()
311 m_EdgePaddingValue=itk::NumericTraits<PixelType>::Zero;
315 //=========================================================================================================================
316 //update the output for the outputRegionForThread
317 template<class InputImageType, class OutputImageType > void HelperClass2<InputImageType, OutputImageType>::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, itk::ThreadIdType threadId )
319 // std::cout << "HelperClass2::ThreadedGenerateData - IN " << threadId << std::endl;
321 //Get pointer to the input
322 typename InputImageType::ConstPointer inputPtr = this->GetInput();
324 //Get pointer to the output
325 typename OutputImageType::Pointer outputPtr = this->GetOutput();
327 //Iterators over input, weigths and output
328 typedef itk::ImageRegionConstIterator<InputImageType> InputImageIteratorType;
329 typedef itk::ImageRegionIterator<OutputImageType> OutputImageIteratorType;
330 typedef itk::ImageRegionIterator<WeightsImageType> WeightsImageIteratorType;
332 //define them over the outputRegionForThread
333 OutputImageIteratorType outputIt(outputPtr, outputRegionForThread);
334 InputImageIteratorType inputIt(inputPtr, outputRegionForThread);
335 WeightsImageIteratorType weightsIt(m_Weights, outputRegionForThread);
338 //==================================================================================================
339 //loop over the output and normalize the input, remove holes
340 PixelType neighValue;
341 double zero = itk::NumericTraits<double>::Zero;
342 while (!outputIt.IsAtEnd()) {
343 //the weight is not zero
344 if (weightsIt.Get() != zero) {
345 //divide by the weight
346 outputIt.Set(static_cast<PixelType>(inputIt.Get()/weightsIt.Get()));
349 //copy the value of the neighbour that was just processed
351 if(!outputIt.IsAtBegin()) {
355 //Neighbour cannot have zero weight because it should be filled already
356 neighValue=outputIt.Get();
358 outputIt.Set(neighValue);
361 //DD("is at begin, setting edgepadding value");
362 outputIt.Set(m_EdgePaddingValue);
371 // std::cout << "HelperClass2::ThreadedGenerateData - OUT " << threadId << std::endl;
376 }//end nameless namespace
383 //=========================================================================================================================
384 // The rest is the InvertVFFilter
385 //=========================================================================================================================
387 //=========================================================================================================================
389 template <class InputImageType, class OutputImageType>
390 InvertVFFilter<InputImageType, OutputImageType>::InvertVFFilter()
392 m_EdgePaddingValue=itk::NumericTraits<PixelType>::Zero; //no other reasonable value?
397 //=========================================================================================================================
399 template <class InputImageType, class OutputImageType> void InvertVFFilter<InputImageType, OutputImageType>::GenerateData()
401 // std::cout << "InvertVFFilter::GenerateData - IN" << std::endl;
403 //Get the properties of the input
404 typename InputImageType::ConstPointer inputPtr=this->GetInput();
405 typename WeightsImageType::RegionType region = inputPtr->GetLargestPossibleRegion();
407 //Allocate the weights
408 typename WeightsImageType::Pointer weights=WeightsImageType::New();
409 weights->SetOrigin(inputPtr->GetOrigin());
410 weights->SetRegions(region);
412 weights->SetSpacing(inputPtr->GetSpacing());
414 //===========================================================================
415 //Inversion is divided in in two loops, for each we will call a threaded helper class
416 //1. add contribution of input to output and update weights
417 //2. normalize the output by the weight and remove holes
418 //===========================================================================
421 //===========================================================================
422 //1. add contribution of input to output and update weights
424 //Define an internal image type
426 typedef itk::Image<itk::Vector<double,ImageDimension>, ImageDimension > InternalImageType;
428 //Call threaded helper class 1
429 typedef HelperClass1<InputImageType, InternalImageType > HelperClass1Type;
430 typename HelperClass1Type::Pointer helper1=HelperClass1Type::New();
433 if(m_NumberOfThreadsIsGiven)helper1->SetNumberOfThreads(m_NumberOfThreads);
434 helper1->SetInput(inputPtr);
435 helper1->SetWeights(weights);
439 //Allocate the mutex image
440 typename MutexImageType::Pointer mutex=InvertVFFilter::MutexImageType::New();
441 mutex->SetRegions(region);
443 mutex->SetSpacing(inputPtr->GetSpacing());
444 helper1->SetMutexImage(mutex);
445 if (m_Verbose) std::cout <<"Inverting using a thread-safe algorithm" <<std::endl;
446 } else if(m_Verbose)std::cout <<"Inverting using a thread-unsafe algorithm" <<std::endl;
448 //Execute helper class
452 typename InternalImageType::Pointer temp= helper1->GetOutput();
453 weights=helper1->GetWeights();
456 //===========================================================================
457 //2. Normalize the output by the weights and remove holes
458 //Call threaded helper class
459 typedef HelperClass2<InternalImageType, OutputImageType> HelperClass2Type;
460 typename HelperClass2Type::Pointer helper2=HelperClass2Type::New();
462 //Set temporary output as input
463 if(m_NumberOfThreadsIsGiven)helper2->SetNumberOfThreads(m_NumberOfThreads);
464 helper2->SetInput(temp);
465 helper2->SetWeights(weights);
466 helper2->SetEdgePaddingValue(m_EdgePaddingValue);
468 //Execute helper class
469 if (m_Verbose) std::cout << "Normalizing the output VF..."<<std::endl;
473 this->SetNthOutput(0, helper2->GetOutput());
475 //std::cout << "InvertVFFilter::GenerateData - OUT" << std::endl;