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() ITK_OVERRIDE;
78 void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, itk::ThreadIdType threadId ) ITK_OVERRIDE;
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 ) ITK_OVERRIDE;
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()
312 for(unsigned int i=0;i <PixelType::Dimension; i++) zero[i] = 0.0;
313 m_EdgePaddingValue=zero;
314 //m_EdgePaddingValue=itk::NumericTraits<PixelType>::Zero;
318 //=========================================================================================================================
319 //update the output for the outputRegionForThread
320 template<class InputImageType, class OutputImageType > void HelperClass2<InputImageType, OutputImageType>::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, itk::ThreadIdType threadId )
322 // std::cout << "HelperClass2::ThreadedGenerateData - IN " << threadId << std::endl;
324 //Get pointer to the input
325 typename InputImageType::ConstPointer inputPtr = this->GetInput();
327 //Get pointer to the output
328 typename OutputImageType::Pointer outputPtr = this->GetOutput();
330 //Iterators over input, weigths and output
331 typedef itk::ImageRegionConstIterator<InputImageType> InputImageIteratorType;
332 typedef itk::ImageRegionIterator<OutputImageType> OutputImageIteratorType;
333 typedef itk::ImageRegionIterator<WeightsImageType> WeightsImageIteratorType;
335 //define them over the outputRegionForThread
336 OutputImageIteratorType outputIt(outputPtr, outputRegionForThread);
337 InputImageIteratorType inputIt(inputPtr, outputRegionForThread);
338 WeightsImageIteratorType weightsIt(m_Weights, outputRegionForThread);
341 //==================================================================================================
342 //loop over the output and normalize the input, remove holes
343 PixelType neighValue;
344 double zero = itk::NumericTraits<double>::Zero;
345 while (!outputIt.IsAtEnd()) {
346 //the weight is not zero
347 if (weightsIt.Get() != zero) {
348 //divide by the weight
349 outputIt.Set(static_cast<PixelType>(inputIt.Get()/weightsIt.Get()));
352 //copy the value of the neighbour that was just processed
354 if(!outputIt.IsAtBegin()) {
358 //Neighbour cannot have zero weight because it should be filled already
359 neighValue=outputIt.Get();
361 outputIt.Set(neighValue);
364 //DD("is at begin, setting edgepadding value");
365 outputIt.Set(m_EdgePaddingValue);
374 // std::cout << "HelperClass2::ThreadedGenerateData - OUT " << threadId << std::endl;
379 }//end nameless namespace
386 //=========================================================================================================================
387 // The rest is the InvertVFFilter
388 //=========================================================================================================================
390 //=========================================================================================================================
392 template <class InputImageType, class OutputImageType>
393 InvertVFFilter<InputImageType, OutputImageType>::InvertVFFilter()
396 //m_EdgePaddingValue=itk::NumericTraits<PixelType>::Zero; //no other reasonable value?
398 for(unsigned int i=0;i <PixelType::Dimension; i++) zero[i] = 0.0;
399 m_EdgePaddingValue=zero; //no other reasonable value?
405 //=========================================================================================================================
407 template <class InputImageType, class OutputImageType> void InvertVFFilter<InputImageType, OutputImageType>::GenerateData()
409 // std::cout << "InvertVFFilter::GenerateData - IN" << std::endl;
411 //Get the properties of the input
412 typename InputImageType::ConstPointer inputPtr=this->GetInput();
413 typename WeightsImageType::RegionType region = inputPtr->GetLargestPossibleRegion();
415 //Allocate the weights
416 typename WeightsImageType::Pointer weights=WeightsImageType::New();
417 weights->SetOrigin(inputPtr->GetOrigin());
418 weights->SetRegions(region);
420 weights->SetSpacing(inputPtr->GetSpacing());
422 //===========================================================================
423 //Inversion is divided in in two loops, for each we will call a threaded helper class
424 //1. add contribution of input to output and update weights
425 //2. normalize the output by the weight and remove holes
426 //===========================================================================
429 //===========================================================================
430 //1. add contribution of input to output and update weights
432 //Define an internal image type
434 typedef itk::Image<itk::Vector<double,ImageDimension>, ImageDimension > InternalImageType;
436 //Call threaded helper class 1
437 typedef HelperClass1<InputImageType, InternalImageType > HelperClass1Type;
438 typename HelperClass1Type::Pointer helper1=HelperClass1Type::New();
441 if(m_NumberOfThreadsIsGiven) {
442 #if ITK_VERSION_MAJOR <= 4
443 helper1->SetNumberOfThreads(m_NumberOfThreads);
445 helper1->SetNumberOfWorkUnits(m_NumberOfWorkUnits);
448 helper1->SetInput(inputPtr);
449 helper1->SetWeights(weights);
453 //Allocate the mutex image
454 typename MutexImageType::Pointer mutex=InvertVFFilter::MutexImageType::New();
455 mutex->SetRegions(region);
457 mutex->SetSpacing(inputPtr->GetSpacing());
458 helper1->SetMutexImage(mutex);
459 if (m_Verbose) std::cout <<"Inverting using a thread-safe algorithm" <<std::endl;
460 } else if(m_Verbose)std::cout <<"Inverting using a thread-unsafe algorithm" <<std::endl;
462 //Execute helper class
466 typename InternalImageType::Pointer temp= helper1->GetOutput();
467 weights=helper1->GetWeights();
470 //===========================================================================
471 //2. Normalize the output by the weights and remove holes
472 //Call threaded helper class
473 typedef HelperClass2<InternalImageType, OutputImageType> HelperClass2Type;
474 typename HelperClass2Type::Pointer helper2=HelperClass2Type::New();
476 //Set temporary output as input
477 if(m_NumberOfThreadsIsGiven) {
478 #if ITK_VERSION_MAJOR <= 4
479 helper2->SetNumberOfThreads(m_NumberOfThreads);
481 helper2->SetNumberOfWorkUnits(m_NumberOfWorkUnits);
484 helper2->SetInput(temp);
485 helper2->SetWeights(weights);
486 helper2->SetEdgePaddingValue(m_EdgePaddingValue);
488 //Execute helper class
489 if (m_Verbose) std::cout << "Normalizing the output VF..."<<std::endl;
493 this->SetNthOutput(0, helper2->GetOutput());
495 //std::cout << "InvertVFFilter::GenerateData - OUT" << std::endl;