diff --git a/CMakeLists.txt b/CMakeLists.txt index ea2914f4eeedaf64b8ebafbc1c7aead9c948e164..4736606b1df0270aeafef13456571f31e20f8dfb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -575,7 +575,7 @@ ENDIF(OTB_USE_EXTERNAL_GDAL) FIND_PACKAGE(Gettext) IF(GETTEXT_FOUND) SET(OTB_I18N 1) - SET(OTB_LANG "en" CACHE STRING "OTB internationalization (Experimental)")#might want to get the Locale from the system here + SET(OTB_LANG $ENV{LANG} CACHE STRING "OTB internationalization (Experimental)")#might want to get the Locale from the system here SET(OTB_LANG_LOCATION ${CMAKE_CURRENT_BINARY_DIR}/I18n) SUBDIRS(I18n) ELSE(GETTEXT_FOUND) diff --git a/Code/Common/otbI18n.h b/Code/Common/otbI18n.h index dac8beba7c76a24c1885251d38a137867aab20e8..124a406dcbd7a1469f29a6a1f2ae598a8ce95e74 100644 --- a/Code/Common/otbI18n.h +++ b/Code/Common/otbI18n.h @@ -28,7 +28,6 @@ #define _QUOTEME(x) #x #define QUOTEME(x) _QUOTEME(x) - #if defined(OTB_I18N) #define otbI18nMacro() \ setlocale( LC_ALL, QUOTEME(OTB_LANG) );\ diff --git a/Code/Common/otbLabelMapToGISTableFilter.h b/Code/Common/otbLabelMapToGISTableFilter.h index 31dc9324be59b42fecda9591251c009bdc195141..1e8f50bc4f9ee66cccf97ea8b0561dc201568caa 100644 --- a/Code/Common/otbLabelMapToGISTableFilter.h +++ b/Code/Common/otbLabelMapToGISTableFilter.h @@ -23,8 +23,9 @@ #include "otbGISConnectionImplementation.h" #include "otbLabelObjectToPolygonFunctor.h" -#include "otbSimplifyPathFunctor.h" -#include "otbClosePathFunctor.h" +// #include "otbSimplifyPathFunctor.h" +// #include "otbClosePathFunctor.h" +#include "otbCorrectPolygonFunctor.h" #include "itkLabelMap.h" #include <iostream> #include <sstream> @@ -82,6 +83,7 @@ public: typedef otb::Functor::LabelObjectToPolygonFunctor<LabelObjectType,PolygonType> FunctorType; typedef otb::SimplifyPathFunctor<PolygonType,PolygonType> SimplifyFunctorType; typedef ClosePathFunctor <PolygonType,PolygonType> CloseFunctorType; + typedef CorrectPolygonFunctor <PolygonType> CorrectFunctorType; /** ImageDimension constants */ //itkStaticConstMacro(InputImageDimension, unsigned int, // TInputImage::ImageDimension); diff --git a/Code/Common/otbLabelMapToGISTableFilter.txx b/Code/Common/otbLabelMapToGISTableFilter.txx index 18a1d194ca9c969be3f58c6d774ae2949d707f52..145cf62d5849fcc56106cc6af227748517477b86 100644 --- a/Code/Common/otbLabelMapToGISTableFilter.txx +++ b/Code/Common/otbLabelMapToGISTableFilter.txx @@ -134,10 +134,12 @@ LabelMapToGISTableFilter< TLabelMap, TGISTable > output->CreateTable(m_DropExistingGISTable); FunctorType functor; - SimplifyFunctorType simplifyFunctor; - simplifyFunctor.SetTolerance (0.0); +// SimplifyFunctorType simplifyFunctor; +// simplifyFunctor.SetTolerance (0.0); +// +// CloseFunctorType closeFunctor; - CloseFunctorType closeFunctor; + CorrectFunctorType correctFunctor; // Lets begin by declaring the iterator for the objects in the image. typename InputLabelMapType::LabelObjectContainerType::const_iterator it; // And get the object container to reuse it later @@ -157,14 +159,15 @@ LabelMapToGISTableFilter< TLabelMap, TGISTable > //std::cout << "polygon : " << polygon << std::endl; //Simply polygon (erase aligned points) - PolygonPointerType simplifyPolygon = simplifyFunctor(polygon); +// PolygonPointerType simplifyPolygon = simplifyFunctor(polygon); //std::cout << "simplify polygon : " << simplifyPolygon << std::endl; //Close polygon if necessary - PolygonPointerType closePolygon = closeFunctor(simplifyPolygon); +// PolygonPointerType closePolygon = closeFunctor(simplifyPolygon); + PolygonPointerType correctPolygon = correctFunctor(polygon); //std::cout << "simplify polygon : " << closePolygon << std::endl; - this->GetOutput()->InsertPolygons( static_cast<typename TGISTable::PolygonConstPointerType> (closePolygon), static_cast<typename TGISTable::PolygonListConstPointerType> (0), oss.str()); + this->GetOutput()->InsertPolygons( static_cast<typename TGISTable::PolygonConstPointerType> (correctPolygon), static_cast<typename TGISTable::PolygonListConstPointerType> (0), oss.str()); //Add polygon to the gis table } diff --git a/Code/Common/otbLabelMapToVectorDataFilter.h b/Code/Common/otbLabelMapToVectorDataFilter.h index 004d286d8f8960af2eaa0bf0f040d0cc711aa892..1efe0d6f8a932483a2c2df9012485298ca5dcf8c 100644 --- a/Code/Common/otbLabelMapToVectorDataFilter.h +++ b/Code/Common/otbLabelMapToVectorDataFilter.h @@ -20,8 +20,9 @@ #include "otbVectorDataSource.h" #include "itkLabelMap.h" #include "otbLabelObjectToPolygonFunctor.h" -#include "otbSimplifyPathFunctor.h" -#include "otbClosePathFunctor.h" +// #include "otbSimplifyPathFunctor.h" +// #include "otbClosePathFunctor.h" +#include "otbCorrectPolygonFunctor.h" #include "otbDataNode.h" #include <string> @@ -69,8 +70,9 @@ public: typedef typename PolygonType::Pointer PolygonPointerType; /** Some typedefs specific to functors*/ typedef otb::Functor::LabelObjectToPolygonFunctor<LabelObjectType,PolygonType> FunctorType; - typedef otb::SimplifyPathFunctor<PolygonType,PolygonType> SimplifyFunctorType; - typedef ClosePathFunctor <PolygonType,PolygonType> CloseFunctorType; + typedef otb::CorrectPolygonFunctor<PolygonType> CorrectFunctorType; +// typedef otb::SimplifyPathFunctor<PolygonType,PolygonType> SimplifyFunctorType; +// typedef ClosePathFunctor <PolygonType,PolygonType> CloseFunctorType; /** ImageDimension constants */ /** Standard New method. */ diff --git a/Code/Common/otbLabelMapToVectorDataFilter.txx b/Code/Common/otbLabelMapToVectorDataFilter.txx index 38c2ccd40f8bb635b82a20b22e7d5c971187c686..13ae9df7a67ec1a5ed91190e34ea08c170bc41de 100644 --- a/Code/Common/otbLabelMapToVectorDataFilter.txx +++ b/Code/Common/otbLabelMapToVectorDataFilter.txx @@ -104,31 +104,27 @@ void LabelMapToVectorDataFilter<TLabelMap, TVectorData> ::GenerateData() { - +// std::cout << "ICI" << std::endl; /**Allocate the output*/ - this->AllocateOutputs(); - +// this->AllocateOutputs(); +// std::cout << "ICI" << std::endl; OutputVectorDataType * output = this->GetOutput(); const InputLabelMapType * input = this->GetInput(); - /**create functors */ FunctorType functor; - SimplifyFunctorType simplifyFunctor; - CloseFunctorType closeFunctor; - +// SimplifyFunctorType simplifyFunctor; +// CloseFunctorType closeFunctor; + CorrectFunctorType correctFunctor; /**Create usual root elements of the output vectordata*/ DataNodePointerType document = DataNodeType::New(); DataNodePointerType folder1 = DataNodeType::New(); document->SetNodeType(DOCUMENT); folder1->SetNodeType(FOLDER); - DataNodePointerType root = output->GetDataTree()->GetRoot()->Get(); - output->GetDataTree()->Add(document,root); output->GetDataTree()->Add(folder1,document); - // Lets begin by declaring the iterator for the objects in the image. typename InputLabelMapType::LabelObjectContainerType::const_iterator it; // And get the object container to reuse it later @@ -145,12 +141,15 @@ void typename PolygonType::Pointer polygon = functor(labelObject); /** Erase aligned points*/ - PolygonPointerType simplifyPolygon = simplifyFunctor(polygon); - //std::cout << "simplify polygon : " << simplifyPolygon << std::endl; +// PolygonPointerType simplifyPolygon = simplifyFunctor(polygon); + /**Close polygon if necessary*/ - PolygonPointerType closePolygon = closeFunctor(simplifyPolygon); +// PolygonPointerType closePolygon = closeFunctor(simplifyPolygon); + /**correct polygon if necessary*/ + PolygonPointerType correctPolygon = correctFunctor(polygon); +// std::cout << "correct polygon : " << correctPolygon << std::endl; DataNodePointerType node = DataNodeType::New(); node->SetNodeType(otb::FEATURE_POLYGON); @@ -159,7 +158,7 @@ void oss << labelObject->GetLabel(); node->SetNodeId(oss.str()); //TODO hole in the polygon are not handle yet by the functor - node->SetPolygonExteriorRing(closePolygon); + node->SetPolygonExteriorRing(correctPolygon); /**Add the polygon to the VectorData*/ output->GetDataTree()->Add(node,folder1); diff --git a/Code/Common/otbPostGISTable.txx b/Code/Common/otbPostGISTable.txx index c22596b8aa171fb40f22f87485575df82f208900..df470d65748c54183a0ee7e5672f9e8250278b07 100644 --- a/Code/Common/otbPostGISTable.txx +++ b/Code/Common/otbPostGISTable.txx @@ -311,6 +311,7 @@ PostGISTable<TConnectionImplementation, TPrecision, SpatialDimension> if ( !m_TableName.empty() ) { connectionSTR +="tables="; connectionSTR += m_TableName; +// connectionSTR += "' "; } otbGenericMsgDebugMacro(<<"OGR connection string " << connectionSTR); diff --git a/Code/Common/otbVectorDataToGISTableFilter.txx b/Code/Common/otbVectorDataToGISTableFilter.txx index f758f6fb144517440fde6cf283a511ea7cad2a9e..5cafe5fec59e8bf57bea0027459174e3a555f093 100644 --- a/Code/Common/otbVectorDataToGISTableFilter.txx +++ b/Code/Common/otbVectorDataToGISTableFilter.txx @@ -126,8 +126,8 @@ VectorDataToGISTableFilter< TVectorData, TGISTable > output->GetConnection()->ConnectToDB(); /**Name of the table is settedd automaticcaly to "vector_data_to_gis"*/ - output->SetTableName ("vector_data_to_gis"); - +// output->SetTableName ("vector_data_to_gis"); + output->SetTableName (this->GetGISTableName()); /**Create the PostgreSQL table*/ //output->CreateTable(m_DropExistingGISTable); diff --git a/Code/Common/otbVectorDataToLabelMapFilter.txx b/Code/Common/otbVectorDataToLabelMapFilter.txx index 496e413a61568def5fbe852669938ee14064c979..ec37eb11b683278086a25f114cc7ce71b714bc0d 100644 --- a/Code/Common/otbVectorDataToLabelMapFilter.txx +++ b/Code/Common/otbVectorDataToLabelMapFilter.txx @@ -327,7 +327,7 @@ VectorDataToLabelMapFilter< TVectorData, TLabelMap > index[1] = vertex[1] - polygonExtRingBoundReg.GetOrigin(1); // index[0] += this->GetOutput()->GetOrigin()[0]; // index[1] += this->GetOutput()->GetOrigin()[1]; - std::cout << "index " << index << std::endl; +// std::cout << "index " << index << std::endl; if (this->GetOutput()->HasLabel( m_lab ) ) { if (!this->GetOutput()->GetLabelObject( m_lab )->HasIndex( index )) diff --git a/Code/IO/otbImage.h b/Code/IO/otbImage.h index e50ded178b814e1f5c05e1834af33225f8976dcc..360671c92c14f955690c07a0dbaa717f704df2c3 100644 --- a/Code/IO/otbImage.h +++ b/Code/IO/otbImage.h @@ -194,6 +194,7 @@ private: Those method will disappear. Use Default because don't need to know the sensor type*/ typename DefaultImageMetadataInterface::Pointer m_ImageMetadataInterface; + }; diff --git a/Code/IO/otbKMLVectorDataIO.h b/Code/IO/otbKMLVectorDataIO.h index 9dda33e5696440ea25354ff1a37c3c874ad64bf2..daea998129384699f02a64c980847973b84a14c5 100644 --- a/Code/IO/otbKMLVectorDataIO.h +++ b/Code/IO/otbKMLVectorDataIO.h @@ -100,7 +100,7 @@ public: virtual bool CanWriteFile(const char*) const; /** Writes the data to disk from the data structure provided */ - virtual void Write(VectorDataConstPointerType data); + virtual void Write(VectorDataConstPointerType data, char ** papszOptions = NULL); protected: /** Construtor.*/ diff --git a/Code/IO/otbKMLVectorDataIO.txx b/Code/IO/otbKMLVectorDataIO.txx index 67056a635df173f2280d4582ede26ac0667efc21..50df5fb24fb294f8914650fd83e3e83bffcf7d7f 100644 --- a/Code/IO/otbKMLVectorDataIO.txx +++ b/Code/IO/otbKMLVectorDataIO.txx @@ -546,7 +546,7 @@ bool KMLVectorDataIO<TData>::CanWriteFile( const char* filename ) const } template<class TData> -void KMLVectorDataIO<TData>::Write(const VectorDataConstPointerType data) + void KMLVectorDataIO<TData>::Write(const VectorDataConstPointerType data, char ** papszOptions) { itk::TimeProbe chrono; chrono.Start(); diff --git a/Code/IO/otbOGRVectorDataIO.h b/Code/IO/otbOGRVectorDataIO.h index ea9b9a478b41071865d5a093f52c3c784b7eb159..6e57b5790a76603e5657ea205390f6724bab068a 100644 --- a/Code/IO/otbOGRVectorDataIO.h +++ b/Code/IO/otbOGRVectorDataIO.h @@ -99,7 +99,7 @@ public: virtual bool CanWriteFile(const char*) const; /** Writes the data to disk from the memory buffer provided */ - virtual void Write(VectorDataConstPointerType data); + virtual void Write(VectorDataConstPointerType data, char ** papszOptions = NULL); protected: /** Construtor.*/ diff --git a/Code/IO/otbOGRVectorDataIO.txx b/Code/IO/otbOGRVectorDataIO.txx index 0c9f139a2229eddc3a0471015591c23ed8d14707..c630d66329bd9d6df667d88a2bdadbb46d47d25f 100644 --- a/Code/IO/otbOGRVectorDataIO.txx +++ b/Code/IO/otbOGRVectorDataIO.txx @@ -191,7 +191,7 @@ bool OGRVectorDataIO<TData>::CanWriteFile( const char* filename ) const } template<class TData> -void OGRVectorDataIO<TData>::Write(const VectorDataConstPointerType data) + void OGRVectorDataIO<TData>::Write(const VectorDataConstPointerType data, char ** papszOptions) { itk::TimeProbe chrono; chrono.Start(); @@ -225,7 +225,7 @@ void OGRVectorDataIO<TData>::Write(const VectorDataConstPointerType data) // m_DataSource = OGRSFDriverRegistrar::Open(this->m_FileName.c_str(), TRUE); - m_DataSource = ogrDriver->CreateDataSource(this->m_FileName.c_str(),NULL); + m_DataSource = ogrDriver->CreateDataSource(this->m_FileName.c_str(),papszOptions); // check the created data source diff --git a/Code/IO/otbVectorDataIOBase.h b/Code/IO/otbVectorDataIOBase.h index 71c91d318a7683b8d71f4907b43a6665ab777fca..43e1b97098d0e13748a8d34f0d8d7ffbce62d3e7 100644 --- a/Code/IO/otbVectorDataIOBase.h +++ b/Code/IO/otbVectorDataIOBase.h @@ -150,7 +150,7 @@ public: /** Writes the data to disk from the memory buffer provided. Make sure * that the IORegions has been set properly. The buffer is cast to a * pointer to the beginning of the image data. */ - virtual void Write(VectorDataConstPointerType data) = 0; + virtual void Write(VectorDataConstPointerType data, char ** papszOptions = NULL) = 0; protected: diff --git a/Code/MultiScale/otbWaveletFilterBank.txx b/Code/MultiScale/otbWaveletFilterBank.txx index b12eab7f899141fc3b07a5ec2a3954eee1dc0ca2..8e5ad9ed0589a550e13acc982068fa2cbd4c3445 100644 --- a/Code/MultiScale/otbWaveletFilterBank.txx +++ b/Code/MultiScale/otbWaveletFilterBank.txx @@ -9,11 +9,11 @@ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. - Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. + Copyright (c) Institut Telecom / Telecom Bretagne. All rights reserved. See ITCopyright.txt for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ @@ -32,7 +32,7 @@ #include "itkProgressReporter.h" // FIXME -#define __myDebug__ 0 +#define __myDebug__ 0 #include "otbImageFileWriter.h" namespace otb { @@ -55,7 +55,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > { this->SetNthOutput(i,OutputImageType::New()); } - + m_UpSampleFilterFactor = 0; m_SubsampleImageFactor = 1; @@ -73,7 +73,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > return; -#if __myDebug__ +#if __myDebug__ otbGenericMsgDebugMacro( << " down sampling output regions by a factor of " << GetSubsampleImageFactor() ); otbGenericMsgDebugMacro( << "initial region " << this->GetInput()->GetLargestPossibleRegion().GetSize()[0] << "," << this->GetInput()->GetLargestPossibleRegion().GetSize()[1] ); @@ -95,7 +95,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > template < class TInputImage, class TOutputImage, class TWaveletOperator > void WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > -::GenerateInputRequestedRegion () +::GenerateInputRequestedRegion () throw ( itk::InvalidRequestedRegionError ) { Superclass::GenerateInputRequestedRegion(); @@ -146,7 +146,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > // Check the dimension for ( unsigned int i = 0; i < InputImageDimension; i++ ) { - if ( ( m_SubsampleImageFactor + if ( ( m_SubsampleImageFactor * ( this->GetInput()->GetRequestedRegion().GetSize()[i] / m_SubsampleImageFactor ) ) != this->GetInput()->GetRequestedRegion().GetSize()[i] ) { @@ -169,7 +169,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > } OutputImageRegionType intermediateRegion; - this->Superclass::CallCopyInputRegionToOutputRegion( intermediateRegion, + this->Superclass::CallCopyInputRegionToOutputRegion( intermediateRegion, this->GetInput()->GetLargestPossibleRegion() ); AllocateInternalData( intermediateRegion ); @@ -180,14 +180,14 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > template < class TInputImage, class TOutputImage, class TWaveletOperator > void WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > -::AllocateInternalData +::AllocateInternalData ( const OutputImageRegionType& outputRegion ) { OutputImageRegionType smallerRegion, largerRegion = outputRegion; for ( unsigned int direction = 0; direction < InputImageDimension-1; direction++ ) { - this->CallCopyInputRegionToOutputRegion( InputImageDimension-1-direction, + this->CallCopyInputRegionToOutputRegion( InputImageDimension-1-direction, smallerRegion, largerRegion ); for ( unsigned int i = 0; i < m_InternalImages[direction].size(); i++ ) @@ -216,7 +216,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > template < class TInputImage, class TOutputImage, class TWaveletOperator > void WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > -::CallCopyOutputRegionToInputRegion +::CallCopyOutputRegionToInputRegion ( InputImageRegionType & destRegion, const OutputImageRegionType & srcRegion ) { Superclass::CallCopyOutputRegionToInputRegion( destRegion, srcRegion ); @@ -238,7 +238,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > destRegion.SetIndex( destIndex ); destRegion.SetSize( destSize ); -#if 0 +#if 0 // Contrairement a INVERSE, ici ca ne sera a rien apparemment... // Region Padding @@ -261,7 +261,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > for ( unsigned int i = 1; i < InputImageDimension; i++ ) radius[i] = 0; - InputImageRegionType paddedRegion = destRegion; + InputImageRegionType paddedRegion = destRegion; paddedRegion.PadByRadius( radius ); if ( paddedRegion.Crop( this->GetInput()->GetLargestPossibleRegion() ) ) @@ -276,7 +276,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > template < class TInputImage, class TOutputImage, class TWaveletOperator > void WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > -::CallCopyOutputRegionToInputRegion +::CallCopyOutputRegionToInputRegion ( unsigned int direction, InputImageRegionType & destRegion, const OutputImageRegionType & srcRegion ) { @@ -313,7 +313,7 @@ template < class TInputImage, class TOutputImage, class TWaveletOperator > void WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > ::CallCopyInputRegionToOutputRegion -( OutputImageRegionType & destRegion, const InputImageRegionType & srcRegion ) +( OutputImageRegionType & destRegion, const InputImageRegionType & srcRegion ) { Superclass::CallCopyInputRegionToOutputRegion( destRegion, srcRegion ); @@ -341,7 +341,7 @@ void WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > ::CallCopyInputRegionToOutputRegion ( unsigned int direction, - OutputImageRegionType & destRegion, const InputImageRegionType & srcRegion ) + OutputImageRegionType & destRegion, const InputImageRegionType & srcRegion ) { Superclass::CallCopyInputRegionToOutputRegion( destRegion, srcRegion ); @@ -375,7 +375,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > template < class TInputImage, class TOutputImage, class TWaveletOperator > void WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > -::ThreadedGenerateData +::ThreadedGenerateData ( const OutputImageRegionType& outputRegionForThread, int threadId ) { unsigned int dir = InputImageDimension-1; @@ -388,7 +388,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > throw itk::ExceptionObject( __FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION ); } - itk::ProgressReporter reporter ( this, threadId, + itk::ProgressReporter reporter ( this, threadId, outputRegionForThread.GetNumberOfPixels() * this->GetNumberOfOutputs() * 2 ); const InputImageType * input = this->GetInput(); @@ -479,7 +479,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > } if ( dir > 0 ) - { + { // Note that outputImageRegion correspond to the actual region of (local) input ! OutputImageRegionType outputImageRegion; this->CallCopyInputRegionToOutputRegion( dir, outputImageRegion, inputRegionForThread ); @@ -528,7 +528,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > typedef itk::ConstNeighborhoodIterator< OutputImageType > NeighborhoodIteratorType; typedef itk::NeighborhoodInnerProduct< OutputImageType > InnerProductType; typedef itk::ImageRegionIterator< OutputImageType > IteratorType; - typedef typename itk::NeighborhoodAlgorithm + typedef typename itk::NeighborhoodAlgorithm ::ImageBoundaryFacesCalculator< OutputImageType > FaceCalculatorType; typedef typename FaceCalculatorType::FaceListType FaceListType; typedef typename FaceListType::iterator FaceListIterator; @@ -556,7 +556,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > itk::PeriodicBoundaryCondition< OutputImageType > boundaryCondition; //otb::MirrorBoundaryCondition< OutputImageType > boundaryCondition; itHighPass.OverrideBoundaryCondition( &boundaryCondition ); - + IteratorType outHighPass ( outputHighPass, subItHighPass.GenerateOutputInformation() ); outHighPass.GoToBegin(); @@ -600,9 +600,9 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, FORWARD > // Swap input and lowPassOutput itk::ImageRegionConstIterator< OutputImageType > inIt ( outputLowPass, outputImageRegion ); - IteratorType outIt ( ( direction != 0 && m_SubsampleImageFactor > 1 ) ? - static_cast<OutputImageType*>( m_InternalImages[direction-2][idx/(1<<(direction-1))] ) - : this->GetOutput( idx ), + IteratorType outIt ( ( direction != 0 && m_SubsampleImageFactor > 1 ) ? + static_cast<OutputImageType*>( m_InternalImages[direction-2][idx/(1<<(direction-1))] ) + : this->GetOutput( idx ), outputImageRegion ); for ( inIt.GoToBegin(), outIt.GoToBegin(); !inIt.IsAtEnd(); ++inIt, ++outIt ) @@ -649,7 +649,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > if ( this->GetInput(0)->GetLargestPossibleRegion().GetSize()[dim] != this->GetInput(i)->GetLargestPossibleRegion().GetSize()[dim] ) { - throw itk::ExceptionObject( __FILE__, __LINE__, + throw itk::ExceptionObject( __FILE__, __LINE__, "Input images are not of the same dimension", ITK_LOCATION ); } } @@ -659,7 +659,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > #if __myDebug__ otbGenericMsgDebugMacro( << " up sampling output regions by a factor of " << GetSubsampleImageFactor() ); - otbGenericMsgDebugMacro( << "initial region " + otbGenericMsgDebugMacro( << "initial region " << this->GetInput(0)->GetLargestPossibleRegion().GetSize()[0] << "," << this->GetInput(0)->GetLargestPossibleRegion().GetSize()[1] ); #endif @@ -676,7 +676,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > template < class TInputImage, class TOutputImage, class TWaveletOperator > void WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > -::GenerateInputRequestedRegion () +::GenerateInputRequestedRegion () throw ( itk::InvalidRequestedRegionError ) { Superclass::GenerateInputRequestedRegion(); @@ -736,7 +736,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > } OutputImageRegionType intermediateRegion; - Superclass::CallCopyInputRegionToOutputRegion( intermediateRegion, + Superclass::CallCopyInputRegionToOutputRegion( intermediateRegion, this->GetInput(0)->GetLargestPossibleRegion() ); AllocateInternalData( intermediateRegion ); @@ -746,14 +746,14 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > template < class TInputImage, class TOutputImage, class TWaveletOperator > void WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > -::AllocateInternalData +::AllocateInternalData ( const OutputImageRegionType& outputRegion ) { OutputImageRegionType largerRegion, smallerRegion = outputRegion; for ( unsigned int direction = 0; direction < InputImageDimension-1; direction++ ) { - this->CallCopyInputRegionToOutputRegion( direction, + this->CallCopyInputRegionToOutputRegion( direction, largerRegion, smallerRegion ); for ( unsigned int i = 0; i < m_InternalImages[direction].size(); i++ ) @@ -782,7 +782,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > template < class TInputImage, class TOutputImage, class TWaveletOperator > void WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > -::CallCopyOutputRegionToInputRegion +::CallCopyOutputRegionToInputRegion ( InputImageRegionType & destRegion, const OutputImageRegionType & srcRegion ) { Superclass::CallCopyOutputRegionToInputRegion( destRegion, srcRegion ); @@ -811,21 +811,22 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > lowPassOperator.SetUpSampleFactor( this->GetUpSampleFilterFactor() ); lowPassOperator.CreateDirectional(); - unsigned long radius [ InputImageDimension ]; - radius[0] = lowPassOperator.GetRadius()[0]; + long int radius [ InputImageDimension ]; + //radius[0] = lowPassOperator.GetRadius()[0]; HighPassOperatorType highPassOperator; highPassOperator.SetDirection(0); highPassOperator.SetUpSampleFactor( this->GetUpSampleFilterFactor() ); highPassOperator.CreateDirectional(); - if ( radius[0] < highPassOperator.GetRadius()[0] ) - radius[0] = highPassOperator.GetRadius()[0]; - - for ( unsigned int i = 1; i < InputImageDimension; i++ ) - radius[i] = 0; + for ( unsigned int i = 0; i < InputImageDimension; i++ ) + { + radius[i] = lowPassOperator.GetRadius()[0]; + if ( radius[i] < highPassOperator.GetRadius()[0] ) + radius[i] = highPassOperator.GetRadius()[0]; + } - InputImageRegionType paddedRegion = destRegion; + InputImageRegionType paddedRegion = destRegion; paddedRegion.PadByRadius( radius ); if ( paddedRegion.Crop( this->GetInput(0)->GetLargestPossibleRegion() ) ) @@ -840,7 +841,7 @@ template < class TInputImage, class TOutputImage, class TWaveletOperator > void WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > ::CallCopyInputRegionToOutputRegion -( OutputImageRegionType & destRegion, const InputImageRegionType & srcRegion ) +( OutputImageRegionType & destRegion, const InputImageRegionType & srcRegion ) { Superclass::CallCopyInputRegionToOutputRegion( destRegion, srcRegion ); @@ -866,7 +867,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > template < class TInputImage, class TOutputImage, class TWaveletOperator > void WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > -::CallCopyOutputRegionToInputRegion +::CallCopyOutputRegionToInputRegion ( unsigned int direction, InputImageRegionType & destRegion, const OutputImageRegionType & srcRegion ) { @@ -904,7 +905,7 @@ void WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > ::CallCopyInputRegionToOutputRegion ( unsigned int direction, - OutputImageRegionType & destRegion, const InputImageRegionType & srcRegion ) + OutputImageRegionType & destRegion, const InputImageRegionType & srcRegion ) { Superclass::CallCopyInputRegionToOutputRegion( destRegion, srcRegion ); @@ -938,16 +939,16 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > template < class TInputImage, class TOutputImage, class TWaveletOperator > void WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > -::ThreadedGenerateData +::ThreadedGenerateData ( const OutputImageRegionType& outputRegionForThread, int threadId ) { - itk::ProgressReporter reporter ( this, threadId, + itk::ProgressReporter reporter ( this, threadId, outputRegionForThread.GetNumberOfPixels() * this->GetNumberOfInputs() ); InputImageRegionType inputRegionForThread; this->CallCopyOutputRegionToInputRegion( inputRegionForThread, outputRegionForThread ); - - unsigned int dir = 0; + + unsigned int dir = 0; // Low pass part calculation LowPassOperatorType lowPassOperator; @@ -980,7 +981,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > // The multiresolution case requires a SubsampleImageFilter step - if ( m_SubsampleImageFactor > 1 ) + if ( m_SubsampleImageFactor > 1 ) { for ( unsigned int i = 0; i < this->GetNumberOfInputs(); i+=2 ) { @@ -1036,16 +1037,16 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > InnerProductType innerProduct; - itk::ImageRegionIterator< OutputImageType > out + itk::ImageRegionIterator< OutputImageType > out ( outputImage, overSampledLowPass->GetOutput()->GetRequestedRegion() ); - NeighborhoodIteratorType lowIter ( lowPassOperator.GetRadius(), + NeighborhoodIteratorType lowIter ( lowPassOperator.GetRadius(), overSampledLowPass->GetOutput(), overSampledLowPass->GetOutput()->GetRequestedRegion() ); itk::PeriodicBoundaryCondition< OutputImageType > boundaryCondition; //otb::MirrorBoundaryCondition< OutputImageType > boundaryCondition; lowIter.OverrideBoundaryCondition( &boundaryCondition ); - NeighborhoodIteratorType highIter ( highPassOperator.GetRadius(), + NeighborhoodIteratorType highIter ( highPassOperator.GetRadius(), overSampledHighPass->GetOutput(), overSampledHighPass->GetOutput()->GetRequestedRegion() ); highIter.OverrideBoundaryCondition( &boundaryCondition ); @@ -1054,8 +1055,8 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > out.GoToBegin(); while ( !out.IsAtEnd() ) - { - out.Set( innerProduct( lowIter, lowPassOperator ) + { + out.Set( innerProduct( lowIter, lowPassOperator ) + innerProduct( highIter, highPassOperator ) ); ++lowIter; @@ -1079,7 +1080,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > outputImage = m_InternalImages[0][i/2]; } - FaceCalculatorType faceCalculator; + FaceCalculatorType faceCalculator; FaceListType faceList; faceList = faceCalculator( imgLowPass, imgLowPass->GetRequestedRegion(), radiusMax ); @@ -1102,8 +1103,8 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > out.GoToBegin(); while ( !out.IsAtEnd() ) - { - out.Set( ( innerProduct( lowIter, lowPassOperator ) + { + out.Set( ( innerProduct( lowIter, lowPassOperator ) + innerProduct( highIter, highPassOperator ) ) / 2. ); ++lowIter; @@ -1131,7 +1132,7 @@ template < class TInputImage, class TOutputImage, class TWaveletOperator > void WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > ::ThreadedGenerateDataAtDimensionN -( unsigned int direction, +( unsigned int direction, itk::ProgressReporter & reporter, const OutputImageRegionType& outputRegionForThread, int threadId ) { @@ -1168,7 +1169,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > } // The multiresolution case requires a SubsampleImageFilter step - if ( m_SubsampleImageFactor > 1 ) + if ( m_SubsampleImageFactor > 1 ) { for ( unsigned int i = 0; i < m_InternalImages[direction-1].size(); i+=2 ) { @@ -1223,17 +1224,17 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > overSampledHighPass->Update(); InnerProductType innerProduct; - - itk::ImageRegionIterator< OutputImageType > out ( outputImage, + + itk::ImageRegionIterator< OutputImageType > out ( outputImage, overSampledLowPass->GetOutput()->GetRequestedRegion() ); - NeighborhoodIteratorType lowIter ( lowPassOperator.GetRadius(), + NeighborhoodIteratorType lowIter ( lowPassOperator.GetRadius(), overSampledLowPass->GetOutput(), overSampledLowPass->GetOutput()->GetRequestedRegion() ); itk::PeriodicBoundaryCondition< OutputImageType > boundaryCondition; //otb::MirrorBoundaryCondition< OutputImageType > boundaryCondition; lowIter.OverrideBoundaryCondition( &boundaryCondition ); - NeighborhoodIteratorType highIter ( highPassOperator.GetRadius(), + NeighborhoodIteratorType highIter ( highPassOperator.GetRadius(), overSampledHighPass->GetOutput(), overSampledHighPass->GetOutput()->GetRequestedRegion() ); highIter.OverrideBoundaryCondition( &boundaryCondition ); @@ -1242,8 +1243,8 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > out.GoToBegin(); while ( !out.IsAtEnd() ) - { - out.Set( innerProduct( lowIter, lowPassOperator ) + { + out.Set( innerProduct( lowIter, lowPassOperator ) + innerProduct( highIter, highPassOperator ) ); ++lowIter; @@ -1268,7 +1269,7 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > } InnerProductType innerProduct; - FaceCalculatorType faceCalculator; + FaceCalculatorType faceCalculator; FaceListType faceList; faceList = faceCalculator( imgLowPass, imgLowPass->GetRequestedRegion(), radiusMax ); @@ -1289,8 +1290,8 @@ WaveletFilterBank< TInputImage, TOutputImage, TWaveletOperator, INVERSE > out.GoToBegin(); while ( !out.IsAtEnd() ) - { - out.Set( ( innerProduct( lowIter, lowPassOperator ) + { + out.Set( ( innerProduct( lowIter, lowPassOperator ) + innerProduct( highIter, highPassOperator ) ) / 2. ); ++lowIter; diff --git a/Code/Visualization/otbImageLayerRenderingModel.h b/Code/Visualization/otbImageLayerRenderingModel.h index b9a7dfb5905ad31c27227a83fd7e4bf7a47705c4..d9efd9278b14565a56526973ebbe6242dd0ea51d 100644 --- a/Code/Visualization/otbImageLayerRenderingModel.h +++ b/Code/Visualization/otbImageLayerRenderingModel.h @@ -147,7 +147,7 @@ protected: virtual void RasterizeVisibleLayers(void); /** Notify a registered listener */ - virtual void Notify(ListenerType * listener); + virtual void NotifyListener(ListenerType * listener); /** Constrains the given region to the largest possible one. */ virtual RegionType ConstrainRegion(const RegionType & region, const RegionType & largest); diff --git a/Code/Visualization/otbImageLayerRenderingModel.txx b/Code/Visualization/otbImageLayerRenderingModel.txx index fa151e6d733989640d8cfbd9353203bfd9aaa1fe..de2e3237b0635528f2f0b400603e6324cac63435 100644 --- a/Code/Visualization/otbImageLayerRenderingModel.txx +++ b/Code/Visualization/otbImageLayerRenderingModel.txx @@ -243,7 +243,7 @@ ImageLayerRenderingModel<TOutputImage, TLayer> template <class TOutputImage, class TLayer> void ImageLayerRenderingModel<TOutputImage, TLayer> -::Notify(ListenerType * listener) +::NotifyListener(ListenerType * listener) { // Notify the listener otbMsgDevMacro(<<"ImageLayerRenderingModel::Notify(): Notifying listener"); diff --git a/Code/Visualization/otbMVCModel.h b/Code/Visualization/otbMVCModel.h index 2014766ff875d6b8e7dd8ec91e4d0c36226531ed..b8e68b52498409876f40676a31a8fb3e9ff64798 100644 --- a/Code/Visualization/otbMVCModel.h +++ b/Code/Visualization/otbMVCModel.h @@ -70,12 +70,12 @@ public: it!=m_RegisteredListeners.end(); ++it) { - this->Notify(*it); + this->NotifyListener(*it); } } /** Notify changes to a given listerner */ - virtual void Notify(ListenerType * listener) + virtual void NotifyListener(ListenerType * listener) { listener->Notify(); }; diff --git a/Code/Visualization/otbPixelDescriptionModel.h b/Code/Visualization/otbPixelDescriptionModel.h index 7e825368a9b9b6af29612162ca18a52c80e27789..8a38103d90d1423c0ae985faab87fdf7ce8302d0 100644 --- a/Code/Visualization/otbPixelDescriptionModel.h +++ b/Code/Visualization/otbPixelDescriptionModel.h @@ -78,7 +78,7 @@ protected: void PrintSelf(std::ostream& os, itk::Indent indent) const; /** Notify a registered listener */ - void Notify(ListenerType * listener); + void NotifyListener(ListenerType * listener); private: PixelDescriptionModel(const Self&); // purposely not implemented diff --git a/Code/Visualization/otbPixelDescriptionModel.txx b/Code/Visualization/otbPixelDescriptionModel.txx index 932c7768d685598814e08367b6ae8236d49e673d..ab412a67fe66300806df8796881db8da67cbce09 100644 --- a/Code/Visualization/otbPixelDescriptionModel.txx +++ b/Code/Visualization/otbPixelDescriptionModel.txx @@ -79,7 +79,7 @@ PixelDescriptionModel<TOutputImage> template <class TOutputImage> void PixelDescriptionModel<TOutputImage> -::Notify(ListenerType * listener) +::NotifyListener(ListenerType * listener) { listener->Notify(); } diff --git a/I18n/otb-fr.po b/I18n/otb-fr.po index d2cbeed1b7d8ed6badc2f39d432d84f291240068..dc4d96bc1029bf8c91db2cca204885d968de2d6c 100644 --- a/I18n/otb-fr.po +++ b/I18n/otb-fr.po @@ -8,8 +8,8 @@ msgid "" msgstr "" "Project-Id-Version: otb-fr\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2009-09-11 17:45+0800\n" -"PO-Revision-Date: 2009-09-11 17:41+0800\n" +"POT-Creation-Date: 2009-09-16 12:53+0800\n" +"PO-Revision-Date: 2009-09-16 12:52+0800\n" "Last-Translator: Emmanuel Christophe <emmanuel.christophe@orfeo-toolbox." "org>\n" "Language-Team: American English <kde-i18n-doc@kde.org>\n" @@ -17,7 +17,7 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" -"X-Generator: Lokalize 0.3\n" +"X-Generator: Lokalize 1.0\n" #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:65 #: Classification/otbSupervisedClassificationAppliGUI.cxx:107 @@ -43,7 +43,7 @@ msgstr "Charger image a droite" #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:68 msgid "Load SVM model ..." -msgstr "Charger modèle SVM" +msgstr "Charger modele SVM" #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:69 msgid "Import vector data ..." @@ -83,7 +83,7 @@ msgstr "Sauver image resultat" #: UrbanAreaExtraction/otbUrbanAreaExtractionViewGroup.cxx:80 #: ViewerManager/otbImageViewerManagerViewGroup.cxx:313 #: ViewerManager/otbImageViewerManagerViewGroup.cxx:522 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:577 +#: ViewerManager/otbImageViewerManagerViewGroup.cxx:576 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:221 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:493 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:538 @@ -153,17 +153,15 @@ msgstr "Effacer" #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:515 #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:523 #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:531 -#, fuzzy msgid "Clear the entire drawing" msgstr "Effacer tout le dessin" #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:393 msgid "Learn " -msgstr "Apprentisasage" +msgstr "Apprentissage" #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:394 #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:503 -#, fuzzy msgid "Learn the SVM model from the training set" msgstr "Apprentissage du SVM depuis l'ensemble d'entrainement" @@ -173,7 +171,6 @@ msgstr "Classe sans changements" #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:405 #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:427 -#, fuzzy msgid "Choose changed class training set color" msgstr "Choix de la couleur de la classe changements" @@ -182,7 +179,6 @@ msgid "Changed class" msgstr "Changer la classe" #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:416 -#, fuzzy msgid "Toggle changed class training set display" msgstr "Affiche la classe changements" @@ -192,7 +188,6 @@ msgid "Color ..." msgstr "Couleur..." #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:435 -#, fuzzy msgid "Choose unchanged class training set color" msgstr "Choix de la couleur de la classe sans changement" @@ -202,7 +197,6 @@ msgid "Opacity" msgstr "Opacite" #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:443 -#, fuzzy msgid "Set the training set opacity" msgstr "Modifie l'opacite de l'ensemble d'entrainement" @@ -318,23 +312,20 @@ msgstr "" #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:616 #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:665 #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:714 -#, fuzzy msgid "Red channel " -msgstr "Canal rouge:" +msgstr "Canal rouge" #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:623 #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:672 #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:721 -#, fuzzy msgid "Green channel " -msgstr "Canal vert:" +msgstr "Canal vert" #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:630 #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:679 #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:728 -#, fuzzy msgid "Blue channel " -msgstr "Canal bleu:" +msgstr "Canal bleu" #: ChangeDetection/otbInteractiveChangeDetectionGUI.cxx:639 msgid "Right Viewer" @@ -436,6 +427,7 @@ msgstr "" #: ObjectCountingApplication/otbObjectCountingViewGroup.cxx:43 #: OrthoFusion/otbOrthoFusionGUI.cxx:445 OrthoRectif/otbOrthoRectifGUI.cxx:417 #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:253 +#: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:1185 #: RadiometricCalibration/otbRadiometricCalibrationViewGroup.cxx:71 #: RoadExtraction/otbRoadExtractionViewGroup.cxx:169 #: Segmentation/otbSegmentationApplicationViewGroup.cxx:92 @@ -443,9 +435,8 @@ msgstr "" #: UrbanAreaExtraction/otbUrbanAreaExtractionViewGroup.cxx:71 #: ViewerManager/otbImageViewerManagerViewGroup.cxx:273 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:181 -#, fuzzy msgid "Open image" -msgstr "Ouvrir Image" +msgstr "Ouvrir image" #: Classification/otbSupervisedClassificationAppliGUI.cxx:109 msgid "Save result image" @@ -538,7 +529,7 @@ msgstr "" #: ViewerManager/otbImageViewerManagerViewGroup.cxx:504 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:475 msgid "Remove" -msgstr "" +msgstr "Enlever" #: Classification/otbSupervisedClassificationAppliGUI.cxx:434 msgid "Remove the selected class" @@ -808,13 +799,13 @@ msgstr "" #: Classification/otbSupervisedClassificationAppliGUI.cxx:855 #: RadiometricCalibration/otbRadiometricCalibrationViewGroup.cxx:425 +#: RadiometricCalibration/otbRadiometricCalibrationViewGroup.cxx:585 #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:330 #: UrbanAreaExtraction/otbUrbanAreaExtractionViewGroup.cxx:710 #: ViewerManager/otbImageViewerManagerViewGroup.cxx:366 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:330 -#, fuzzy msgid "Channel index" -msgstr "Index du canal rouge" +msgstr "Index du canal" #: Classification/otbSupervisedClassificationAppliGUI.cxx:856 #: RadiometricCalibration/otbRadiometricCalibrationViewGroup.cxx:426 @@ -846,9 +837,8 @@ msgstr "Selectionne la bande a afficher en niveaux de gris" #: UrbanAreaExtraction/otbUrbanAreaExtractionViewGroup.cxx:717 #: ViewerManager/otbImageViewerManagerViewGroup.cxx:373 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:337 -#, fuzzy msgid "Red channel" -msgstr "Canal rouge:" +msgstr "Canal rouge" #: Classification/otbSupervisedClassificationAppliGUI.cxx:864 #: RadiometricCalibration/otbRadiometricCalibrationViewGroup.cxx:434 @@ -896,9 +886,8 @@ msgstr "Selectionne la bande a afficher en vert" #: UrbanAreaExtraction/otbUrbanAreaExtractionViewGroup.cxx:733 #: ViewerManager/otbImageViewerManagerViewGroup.cxx:389 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:353 -#, fuzzy msgid "Blue channel" -msgstr "Canal bleu:" +msgstr "Canal bleu" #: Classification/otbSupervisedClassificationAppliGUI.cxx:882 #: RadiometricCalibration/otbRadiometricCalibrationViewGroup.cxx:452 @@ -938,7 +927,6 @@ msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:397 #: ViewerManager/otbImageViewerManagerViewGroup.cxx:433 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:397 -#, fuzzy msgid "Real channel index" msgstr "Index du canal rouge" @@ -947,22 +935,21 @@ msgstr "Index du canal rouge" #: ViewerManager/otbImageViewerManagerViewGroup.cxx:434 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:398 msgid "Select band for real channel in complex composition" -msgstr "" +msgstr "Selectionne la bande reelle pour la composition complexe" #: Classification/otbSupervisedClassificationAppliGUI.cxx:930 #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:405 #: ViewerManager/otbImageViewerManagerViewGroup.cxx:441 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:405 -#, fuzzy msgid "Imaginary channel index" -msgstr "Index du canal vert" +msgstr "Index du canal imaginaire" #: Classification/otbSupervisedClassificationAppliGUI.cxx:931 #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:406 #: ViewerManager/otbImageViewerManagerViewGroup.cxx:442 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:406 msgid "Select band for imaginary channel in complex composition" -msgstr "" +msgstr "Selectionne la bande imaginaire pour la composition complexe" #: Classification/otbSupervisedClassificationAppliGUI.cxx:939 #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:413 @@ -1410,9 +1397,8 @@ msgid "Profile Size" msgstr "" #: FeatureExtraction/otbFeatureExtractionViewGroup.cxx:886 -#, fuzzy msgid "Step" -msgstr "Configuration" +msgstr "" #: FeatureExtraction/otbFeatureExtractionViewGroup.cxx:897 #: FeatureExtraction/otbFeatureExtractionViewGroup.cxx:929 @@ -1427,9 +1413,8 @@ msgid "Radius along Y" msgstr "" #: FeatureExtraction/otbFeatureExtractionViewGroup.cxx:917 -#, fuzzy msgid "Sigma" -msgstr "Ouvrir Image" +msgstr "Sigma" #: FeatureExtraction/otbFeatureExtractionViewGroup.cxx:945 msgid "Offset along X" @@ -1453,9 +1438,8 @@ msgstr "" #: FeatureExtraction/otbFeatureExtractionViewGroup.cxx:1440 #: FeatureExtraction/otbFeatureExtractionViewGroup.cxx:1489 #: FeatureExtraction/otbFeatureExtractionViewGroup.cxx:1517 -#, fuzzy msgid "NIR channel" -msgstr "Canal rouge:" +msgstr "Canal NIR" #: FeatureExtraction/otbFeatureExtractionViewGroup.cxx:1003 #: FeatureExtraction/otbFeatureExtractionViewGroup.cxx:1113 @@ -1648,7 +1632,7 @@ msgstr "" #: FeatureExtraction/otbFeatureExtractionViewGroup.cxx:1738 msgid "Channels Selection" -msgstr "" +msgstr "Selection des canaux" #: FeatureExtraction/otbFeatureExtractionViewGroup.cxx:1750 msgid "Add feature to list (one per selected channel)" @@ -1755,16 +1739,14 @@ msgstr "" #: FineRegistrationApplication/otbFineRegistrationApplicationViewGroup.cxx:43 #: FineRegistrationApplication/otbFineRegistrationApplicationViewGroup.cxx:396 -#, fuzzy msgid "Open image pair" -msgstr "Ouvrir Image" +msgstr "Ouvrir une pair d'image" #: FineRegistrationApplication/otbFineRegistrationApplicationViewGroup.cxx:44 msgid "Save deformation field" msgstr "" #: FineRegistrationApplication/otbFineRegistrationApplicationViewGroup.cxx:45 -#, fuzzy msgid "Save registered image" msgstr "Sauver l'image recalee" @@ -1773,9 +1755,8 @@ msgid "Fine registration application" msgstr "" #: FineRegistrationApplication/otbFineRegistrationApplicationViewGroup.cxx:174 -#, fuzzy msgid "Images" -msgstr "Ouvrir Image" +msgstr "Images" #: FineRegistrationApplication/otbFineRegistrationApplicationViewGroup.cxx:175 msgid "" @@ -1894,6 +1875,7 @@ msgid "" msgstr "" #: FineRegistrationApplication/otbFineRegistrationApplicationViewGroup.cxx:308 +#: Pireo/PireoViewerGUI.cxx:534 msgid "Fixed" msgstr "" @@ -1902,6 +1884,7 @@ msgid "Show or hide the fixed image in the color composition" msgstr "" #: FineRegistrationApplication/otbFineRegistrationApplicationViewGroup.cxx:320 +#: Pireo/PireoViewerGUI.cxx:556 msgid "Moving" msgstr "" @@ -2045,9 +2028,8 @@ msgstr "" #: ImageToDBRegistration/otbImageToDBRegistrationViewGroup.cxx:292 #: Pireo/PireoViewerGUI.cxx:738 Pireo/PireoViewerGUI.cxx:767 #: StereoscopicApplication/otbStereoscopicApplicationViewGroup.cxx:176 -#, fuzzy msgid "Image" -msgstr "Ouvrir Image" +msgstr "Image" #: ImageToDBRegistration/otbImageToDBRegistrationViewGroup.cxx:302 msgid "Data Base" @@ -2077,9 +2059,8 @@ msgid "ClearAll" msgstr "" #: ImageToDBRegistration/otbImageToDBRegistrationViewGroup.cxx:362 -#, fuzzy msgid "Clear all vector data" -msgstr "Importer donnees vecteur" +msgstr "Effacer toutes les donnees vecteur" #: ImageToDBRegistration/otbImageToDBRegistrationViewGroup.cxx:374 msgid "Transform" @@ -2132,22 +2113,20 @@ msgid "Input Image Name" msgstr "" #: LandCoverMap/otbLandCoverMapView.cxx:69 -#, fuzzy msgid "Open a new input image" -msgstr "Ouvrir Image" +msgstr "Ouvrir une nouvelle image d'entree" #: LandCoverMap/otbLandCoverMapView.cxx:90 msgid "Input Model Name" msgstr "" #: LandCoverMap/otbLandCoverMapView.cxx:100 -#, fuzzy msgid "Load model" -msgstr "Charger modèle SVM" +msgstr "Charger modele" #: LandCoverMap/otbLandCoverMapView.cxx:101 msgid "Open a new input model" -msgstr "" +msgstr "Ouvrir un nouveau modele" #: LandCoverMap/otbLandCoverMapView.cxx:135 msgid "Scroll image" @@ -2182,7 +2161,6 @@ msgid "Shadows" msgstr "" #: ObjectCountingApplication/otbObjectCountingViewGroup.cxx:44 -#, fuzzy msgid "Save label image" msgstr "Sauver image resultat" @@ -2309,7 +2287,7 @@ msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:182 #: ViewerManager/otbImageViewerManagerViewGroup.cxx:274 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:182 -msgid "Open an image in a new image viewer" +msgid "Open an image in a new image viewer" msgstr "" #: OrthoFusion/otbOrthoFusionGUI.cxx:456 OrthoRectif/otbOrthoRectifGUI.cxx:428 @@ -2374,7 +2352,6 @@ msgid "Hide all the viewers" msgstr "" #: OrthoFusion/otbOrthoFusionGUI.cxx:514 -#, fuzzy msgid "Images list" msgstr "Liste d'images" @@ -2394,42 +2371,36 @@ msgid "Preview window" msgstr "" #: OrthoFusion/otbOrthoFusionGUI.cxx:539 -#, fuzzy msgid "Add PAN input image" -msgstr "Ouvrir Image" +msgstr "Ajouter image PAN" #: OrthoFusion/otbOrthoFusionGUI.cxx:545 msgid "Remove selected PAN" msgstr "" #: OrthoFusion/otbOrthoFusionGUI.cxx:551 -#, fuzzy msgid "Add XS input image" -msgstr "Ouvrir Image" +msgstr "Ajouter image XS" #: OrthoFusion/otbOrthoFusionGUI.cxx:557 msgid "Remove Selected XS" msgstr "" #: OrthoFusion/otbOrthoFusionGUI.cxx:562 -#, fuzzy msgid "PAN image" -msgstr "Ouvrir Image" +msgstr "Image PAN" #: OrthoFusion/otbOrthoFusionGUI.cxx:563 -#, fuzzy msgid "Select a PAN image" -msgstr "Sauver image resultat" +msgstr "Choisir image PAN" #: OrthoFusion/otbOrthoFusionGUI.cxx:567 -#, fuzzy msgid "XS image" -msgstr "Ouvrir Image" +msgstr "Image XS" #: OrthoFusion/otbOrthoFusionGUI.cxx:568 -#, fuzzy msgid "Select a XS image" -msgstr "Sauver image resultat" +msgstr "Choisir image XS" #: OrthoFusion/otbOrthoFusionGUI.cxx:578 OrthoRectif/otbOrthoRectifGUI.cxx:516 msgid "Coordinates" @@ -2548,9 +2519,8 @@ msgid "If checked, use the upper left output image pixel coodinates" msgstr "" #: OrthoFusion/otbOrthoFusionGUI.cxx:758 OrthoRectif/otbOrthoRectifGUI.cxx:692 -#, fuzzy msgid "Output image" -msgstr "Ouvrir Image" +msgstr "Image de sortie" #: OrthoFusion/otbOrthoFusionGUI.cxx:764 OrthoRectif/otbOrthoRectifGUI.cxx:699 msgid "Size X" @@ -2595,9 +2565,8 @@ msgid "Select the orthorectif interpolator" msgstr "" #: OrthoFusion/otbOrthoFusionGUI.cxx:809 -#, fuzzy msgid "Interpolator parameters" -msgstr "Sauver l'image recalee" +msgstr "Parametres d'interpolation" #: OrthoFusion/otbOrthoFusionGUI.cxx:853 OrthoRectif/otbOrthoRectifGUI.cxx:788 msgid "DEM" @@ -2613,7 +2582,7 @@ msgstr "" #: OrthoFusion/otbOrthoFusionGUI.cxx:871 OrthoRectif/otbOrthoRectifGUI.cxx:802 msgid "Open a DEM directory" -msgstr "" +msgstr "Ouvrir un repertoire de DEM" #: OrthoFusion/otbOrthoFusionGUI.cxx:887 OrthoRectif/otbOrthoRectifGUI.cxx:818 msgid "Save DEM" @@ -2632,9 +2601,8 @@ msgid "Enter the Average Elevation Value" msgstr "" #: OrthoFusion/otbOrthoFusionGUI.cxx:920 -#, fuzzy msgid "Image extent" -msgstr "Liste d'images" +msgstr "Image extension" #: OrthoFusion/otbOrthoFusionGUI.cxx:933 OrthoRectif/otbOrthoRectifGUI.cxx:868 msgid "Advanced" @@ -2821,14 +2789,12 @@ msgid "&Accept" msgstr "" #: Pireo/PireoViewerGUI.cxx:230 -#, fuzzy msgid "Load fixed image" -msgstr "Ouvrir Image" +msgstr "Ouvrir image fixe" #: Pireo/PireoViewerGUI.cxx:231 -#, fuzzy msgid "Load moving image" -msgstr "Ouvrir Image" +msgstr "Ouvrir image a recaler" #: Pireo/PireoViewerGUI.cxx:234 msgid "Auto Save" @@ -2843,9 +2809,8 @@ msgid "Flip" msgstr "" #: Pireo/PireoViewerGUI.cxx:240 -#, fuzzy msgid "Flip fixed image" -msgstr "Ouvrir Image" +msgstr "Retourner image fixe" #: Pireo/PireoViewerGUI.cxx:241 Pireo/PireoViewerGUI.cxx:245 msgid "Flip X" @@ -2856,9 +2821,8 @@ msgid "Flip Y" msgstr "" #: Pireo/PireoViewerGUI.cxx:244 -#, fuzzy msgid "Flip moving image" -msgstr "Ouvrir Image" +msgstr "Retourner image a recaler" #: Pireo/PireoViewerGUI.cxx:249 msgid "Build" @@ -2921,9 +2885,8 @@ msgid "View loaded image filenames" msgstr "" #: Pireo/PireoViewerGUI.cxx:273 Pireo/PireoViewerGUI.cxx:683 -#, fuzzy msgid "Save Registration parameters" -msgstr "Sauver l'image recalee" +msgstr "Sauver les parametres de recalage" #: Pireo/PireoViewerGUI.cxx:274 msgid "Display Metric values" @@ -2938,19 +2901,16 @@ msgid "Deactivate" msgstr "" #: Pireo/PireoViewerGUI.cxx:443 Pireo/PireoViewerGUI.cxx:465 -#, fuzzy msgid "Filtered fixed image" -msgstr "Ouvrir Image" +msgstr "Image fixe filtree" #: Pireo/PireoViewerGUI.cxx:444 Pireo/PireoViewerGUI.cxx:466 -#, fuzzy msgid "Filtered moving image" -msgstr "Ouvrir Image" +msgstr "Image a recaler filtree" #: Pireo/PireoViewerGUI.cxx:445 Pireo/PireoViewerGUI.cxx:467 -#, fuzzy msgid "Deformed image" -msgstr "Fermer image" +msgstr "Image deformee" #: Pireo/PireoViewerGUI.cxx:446 Pireo/PireoViewerGUI.cxx:468 msgid "Blender (images in transparency)" @@ -2973,21 +2933,8 @@ msgstr "" msgid "VTK Window" msgstr "" -#: Pireo/PireoViewerGUI.cxx:523 -msgid "ZoomFixedImage" -msgstr "" - -#: Pireo/PireoViewerGUI.cxx:534 -#, fuzzy -msgid "FixedImage" -msgstr "Ouvrir Image" - -#: Pireo/PireoViewerGUI.cxx:545 -msgid "ZoomMovingImage" -msgstr "" - -#: Pireo/PireoViewerGUI.cxx:556 -msgid "MovingImage" +#: Pireo/PireoViewerGUI.cxx:523 Pireo/PireoViewerGUI.cxx:545 +msgid "Zoom" msgstr "" #: Pireo/PireoViewerGUI.cxx:581 Pireo/PireoViewerGUI.cxx:630 @@ -3173,9 +3120,8 @@ msgid "Y" msgstr "" #: Pireo/RegistrationParametersGUI.cxx:744 -#, fuzzy msgid "Scale Transform: Parameters" -msgstr "Sauver l'image recalee" +msgstr "" #: Pireo/RegistrationParametersGUI.cxx:761 #: Pireo/RegistrationParametersGUI.cxx:776 @@ -3323,9 +3269,8 @@ msgid "Minimum Step Length" msgstr "" #: Pireo/RegistrationParametersGUI.cxx:1223 -#, fuzzy msgid "Learning rate" -msgstr "Apprentisasage" +msgstr "Taux d'apprentissage" #: Pireo/RegistrationParametersGUI.cxx:1244 msgid "Others" @@ -3467,9 +3412,8 @@ msgstr "" #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:717 #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:838 #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:965 -#, fuzzy msgid "Force co-polarization" -msgstr "Composition coloree" +msgstr "Forcer co-polarization" #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:604 #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:725 @@ -3519,9 +3463,8 @@ msgid "Image file chooser" msgstr "" #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:1057 -#, fuzzy msgid "HH image" -msgstr "Ouvrir Image" +msgstr "Image HH" #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:1058 #, fuzzy @@ -3529,9 +3472,8 @@ msgid "HH input image path" msgstr "Ouvrir Image" #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:1066 -#, fuzzy msgid "HV image" -msgstr "Ouvrir Image" +msgstr "Image HV" #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:1067 #, fuzzy @@ -3539,9 +3481,8 @@ msgid "HV input image path" msgstr "Ouvrir Image" #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:1075 -#, fuzzy msgid "VH image" -msgstr "Ouvrir Image" +msgstr "Image VH" #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:1076 #, fuzzy @@ -3549,9 +3490,8 @@ msgid "VH input image path" msgstr "Ouvrir Image" #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:1084 -#, fuzzy msgid "VV image" -msgstr "Ouvrir Image" +msgstr "Image VV" #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:1085 #, fuzzy @@ -3575,9 +3515,8 @@ msgid "Choose the VV image file name" msgstr "" #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:1133 -#, fuzzy msgid "Vector image" -msgstr "Ouvrir Image" +msgstr "Image vecteur" #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:1134 #, fuzzy @@ -3597,19 +3536,13 @@ msgid "Hide the open images window" msgstr "" #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:1175 -#, fuzzy msgid "Open Vector image" -msgstr "Ouvrir Image" +msgstr "Ouvrir une image vecteur" #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:1176 msgid "Import a polarimetric vector image" msgstr "" -#: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:1185 -#, fuzzy -msgid "Open images" -msgstr "Ouvrir Image" - #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:1186 msgid "Import images corresponding to the HH, HV, VH, VV channels" msgstr "" @@ -3635,14 +3568,12 @@ msgid "Save luminance image" msgstr "" #: RadiometricCalibration/otbRadiometricCalibrationViewGroup.cxx:73 -#, fuzzy msgid "Save reflectance TOA image" -msgstr "Sauver image resultat" +msgstr "Sauver image de reflectance TOA" #: RadiometricCalibration/otbRadiometricCalibrationViewGroup.cxx:74 -#, fuzzy msgid "Save reflectance TOC image" -msgstr "Sauver image resultat" +msgstr "Sauver image reflectance TOC" #: RadiometricCalibration/otbRadiometricCalibrationViewGroup.cxx:75 msgid "Save TOA-TOC diff image" @@ -3799,10 +3730,6 @@ msgstr "" msgid "Radiative Terms" msgstr "" -#: RadiometricCalibration/otbRadiometricCalibrationViewGroup.cxx:585 -msgid "Channel Index" -msgstr "" - #: RadiometricCalibration/otbRadiometricCalibrationViewGroup.cxx:600 msgid "Intrinsic Ref" msgstr "" @@ -3922,7 +3849,7 @@ msgstr "" #: RoadExtraction/otbRoadExtractionViewGroup.cxx:269 #: Segmentation/otbSegmentationApplicationViewGroup.cxx:224 msgid "Channel " -msgstr "" +msgstr "Canal" #: RoadExtraction/otbRoadExtractionViewGroup.cxx:279 msgid "Use spectral angle" @@ -4335,7 +4262,7 @@ msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:258 #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:506 #: ViewerManager/otbImageViewerManagerViewGroup.cxx:323 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:545 +#: ViewerManager/otbImageViewerManagerViewGroup.cxx:544 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:258 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:506 msgid "Slideshow" @@ -4403,7 +4330,7 @@ msgstr "" #: ViewerManager/otbImageViewerManagerViewGroup.cxx:486 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:457 msgid "Apply" -msgstr "" +msgstr "Appliquer" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:458 #: ViewerManager/otbImageViewerManagerViewGroup.cxx:487 @@ -4418,7 +4345,6 @@ msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:466 #: ViewerManager/otbImageViewerManagerViewGroup.cxx:495 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:533 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:466 msgid "List of image viewers already linked with the selected image viewer" msgstr "" @@ -4442,43 +4368,43 @@ msgid "Leave the link set up interface" msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:512 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:551 +#: ViewerManager/otbImageViewerManagerViewGroup.cxx:550 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:512 msgid "Progress" msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:513 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:552 +#: ViewerManager/otbImageViewerManagerViewGroup.cxx:551 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:513 msgid "Position in diaporama" msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:518 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:557 +#: ViewerManager/otbImageViewerManagerViewGroup.cxx:556 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:518 msgid "Previous" msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:519 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:558 +#: ViewerManager/otbImageViewerManagerViewGroup.cxx:557 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:519 msgid "Previous image in diaporama" msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:528 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:567 +#: ViewerManager/otbImageViewerManagerViewGroup.cxx:566 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:528 msgid "Next" msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:529 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:568 +#: ViewerManager/otbImageViewerManagerViewGroup.cxx:567 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:529 msgid "Next image in diaporama" msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:539 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:578 +#: ViewerManager/otbImageViewerManagerViewGroup.cxx:577 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:539 msgid "Leave diaporama mode" msgstr "" @@ -4624,9 +4550,8 @@ msgid "Indices Configuration" msgstr "" #: UrbanAreaExtraction/otbUrbanAreaExtractionViewGroup.cxx:674 -#, fuzzy msgid "NIR channel index" -msgstr "Index du canal rouge" +msgstr "Index du canal NIR" #: UrbanAreaExtraction/otbUrbanAreaExtractionViewGroup.cxx:675 msgid "Select band for NIR channel in RGB composition" @@ -4661,14 +4586,20 @@ msgid "Link Images" msgstr "" #: ViewerManager/otbImageViewerManagerViewGroup.cxx:494 -#, fuzzy msgid "First image" -msgstr "Fermer image" +msgstr "Image 1" #: ViewerManager/otbImageViewerManagerViewGroup.cxx:532 -msgid "SecondImage" +msgid "Second" msgstr "" +#, fuzzy +#~ msgid "FixedImage" +#~ msgstr "Ouvrir Image" + +#~ msgid "Open images" +#~ msgstr "Ouvrir images" + #, fuzzy #~ msgid "Image:" #~ msgstr "Ouvrir Image" diff --git a/I18n/otb.pot b/I18n/otb.pot index 6c13606e0340a3bf2640e9927938f9296a2c6897..c54773171ee897433c76b697b6b78aa513d9cd02 100644 --- a/I18n/otb.pot +++ b/I18n/otb.pot @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: otb 3.1\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2009-09-11 17:45+0800\n" +"POT-Creation-Date: 2009-09-16 12:53+0800\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" @@ -80,7 +80,7 @@ msgstr "" #: UrbanAreaExtraction/otbUrbanAreaExtractionViewGroup.cxx:80 #: ViewerManager/otbImageViewerManagerViewGroup.cxx:313 #: ViewerManager/otbImageViewerManagerViewGroup.cxx:522 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:577 +#: ViewerManager/otbImageViewerManagerViewGroup.cxx:576 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:221 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:493 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:538 @@ -424,6 +424,7 @@ msgstr "" #: ObjectCountingApplication/otbObjectCountingViewGroup.cxx:43 #: OrthoFusion/otbOrthoFusionGUI.cxx:445 OrthoRectif/otbOrthoRectifGUI.cxx:417 #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:253 +#: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:1185 #: RadiometricCalibration/otbRadiometricCalibrationViewGroup.cxx:71 #: RoadExtraction/otbRoadExtractionViewGroup.cxx:169 #: Segmentation/otbSegmentationApplicationViewGroup.cxx:92 @@ -795,6 +796,7 @@ msgstr "" #: Classification/otbSupervisedClassificationAppliGUI.cxx:855 #: RadiometricCalibration/otbRadiometricCalibrationViewGroup.cxx:425 +#: RadiometricCalibration/otbRadiometricCalibrationViewGroup.cxx:585 #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:330 #: UrbanAreaExtraction/otbUrbanAreaExtractionViewGroup.cxx:710 #: ViewerManager/otbImageViewerManagerViewGroup.cxx:366 @@ -1870,6 +1872,7 @@ msgid "" msgstr "" #: FineRegistrationApplication/otbFineRegistrationApplicationViewGroup.cxx:308 +#: Pireo/PireoViewerGUI.cxx:534 msgid "Fixed" msgstr "" @@ -1878,6 +1881,7 @@ msgid "Show or hide the fixed image in the color composition" msgstr "" #: FineRegistrationApplication/otbFineRegistrationApplicationViewGroup.cxx:320 +#: Pireo/PireoViewerGUI.cxx:556 msgid "Moving" msgstr "" @@ -2280,7 +2284,7 @@ msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:182 #: ViewerManager/otbImageViewerManagerViewGroup.cxx:274 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:182 -msgid "Open an image in a new image viewer" +msgid "Open an image in a new image viewer" msgstr "" #: OrthoFusion/otbOrthoFusionGUI.cxx:456 OrthoRectif/otbOrthoRectifGUI.cxx:428 @@ -2926,20 +2930,8 @@ msgstr "" msgid "VTK Window" msgstr "" -#: Pireo/PireoViewerGUI.cxx:523 -msgid "ZoomFixedImage" -msgstr "" - -#: Pireo/PireoViewerGUI.cxx:534 -msgid "FixedImage" -msgstr "" - -#: Pireo/PireoViewerGUI.cxx:545 -msgid "ZoomMovingImage" -msgstr "" - -#: Pireo/PireoViewerGUI.cxx:556 -msgid "MovingImage" +#: Pireo/PireoViewerGUI.cxx:523 Pireo/PireoViewerGUI.cxx:545 +msgid "Zoom" msgstr "" #: Pireo/PireoViewerGUI.cxx:581 Pireo/PireoViewerGUI.cxx:630 @@ -3542,10 +3534,6 @@ msgstr "" msgid "Import a polarimetric vector image" msgstr "" -#: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:1185 -msgid "Open images" -msgstr "" - #: PolarimetricSynthesis/otbPolarimetricSynthesisApplicationViewGroup.cxx:1186 msgid "Import images corresponding to the HH, HV, VH, VV channels" msgstr "" @@ -3733,10 +3721,6 @@ msgstr "" msgid "Radiative Terms" msgstr "" -#: RadiometricCalibration/otbRadiometricCalibrationViewGroup.cxx:585 -msgid "Channel Index" -msgstr "" - #: RadiometricCalibration/otbRadiometricCalibrationViewGroup.cxx:600 msgid "Intrinsic Ref" msgstr "" @@ -4269,7 +4253,7 @@ msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:258 #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:506 #: ViewerManager/otbImageViewerManagerViewGroup.cxx:323 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:545 +#: ViewerManager/otbImageViewerManagerViewGroup.cxx:544 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:258 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:506 msgid "Slideshow" @@ -4352,7 +4336,6 @@ msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:466 #: ViewerManager/otbImageViewerManagerViewGroup.cxx:495 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:533 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:466 msgid "List of image viewers already linked with the selected image viewer" msgstr "" @@ -4376,43 +4359,43 @@ msgid "Leave the link set up interface" msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:512 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:551 +#: ViewerManager/otbImageViewerManagerViewGroup.cxx:550 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:512 msgid "Progress" msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:513 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:552 +#: ViewerManager/otbImageViewerManagerViewGroup.cxx:551 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:513 msgid "Position in diaporama" msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:518 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:557 +#: ViewerManager/otbImageViewerManagerViewGroup.cxx:556 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:518 msgid "Previous" msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:519 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:558 +#: ViewerManager/otbImageViewerManagerViewGroup.cxx:557 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:519 msgid "Previous image in diaporama" msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:528 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:567 +#: ViewerManager/otbImageViewerManagerViewGroup.cxx:566 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:528 msgid "Next" msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:529 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:568 +#: ViewerManager/otbImageViewerManagerViewGroup.cxx:567 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:529 msgid "Next image in diaporama" msgstr "" #: Testing/ViewerManagerOld/otbImageViewerManagerGUI.cxx:539 -#: ViewerManager/otbImageViewerManagerViewGroup.cxx:578 +#: ViewerManager/otbImageViewerManagerViewGroup.cxx:577 #: ViewerManagerOld/otbImageViewerManagerGUI.cxx:539 msgid "Leave diaporama mode" msgstr "" @@ -4598,5 +4581,5 @@ msgid "First image" msgstr "" #: ViewerManager/otbImageViewerManagerViewGroup.cxx:532 -msgid "SecondImage" +msgid "Second" msgstr "" diff --git a/Testing/Code/Common/CMakeLists.txt b/Testing/Code/Common/CMakeLists.txt index 5df5abe2dda6c67d66392f94fc67ea19266f9da5..572d013cc7d1089f121909a41f85a527bcbfe5e6 100755 --- a/Testing/Code/Common/CMakeLists.txt +++ b/Testing/Code/Common/CMakeLists.txt @@ -842,6 +842,26 @@ ADD_TEST(coTuGISTableToVectorDataFilterNew ${COMMON_TESTS10} otbGISTableToVectorDataFilterNew ) +ADD_TEST(coTvLabelMapToGISTableFilter ${COMMON_TESTS10} +otbLabelMapToGISTableFilter +${INPUTDATA}/rcc8_mire1.png +labelmaptogis_test_table +orfeotoolbox_test_user +Bidfeud0 +) + + +#need gdal 1.6 for POSTGIS tables connection via OGR string +ADD_TEST(coTvGISTableToVectorDataFilter ${COMMON_TESTS10} +otbGISTableToVectorDataFilter +${TEMP}/gistabletovectordatafilter.shp +orfeotoolbox_test +labelmaptogis_test_table +orfeotoolbox_test_user +Bidfeud0 +) + + ENDIF(OTB_USE_PQXX) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -878,6 +898,10 @@ ADD_TEST(coTuLabelMapToVectorDataFilterNew ${COMMON_TESTS11} otbLabelMapToVectorDataFilterNew ) +ADD_TEST(coTuVectorDataToLabelMapFilterNew ${COMMON_TESTS11} +otbVectorDataToLabelMapFilterNew +) + ADD_TEST(coTuLabelMapSourceNew ${COMMON_TESTS11} otbLabelMapSourceNew ) @@ -903,6 +927,18 @@ otbUnaryFunctorWithIndexImageFilter ${TEMP}/coTvUnaryFunctorWithIndexImageFilter.tif ) +ADD_TEST(coTvLabelMapToVectorDataFilter ${COMMON_TESTS11} +otbLabelMapToVectorDataFilter + ${INPUTDATA}/rcc8_mire1.png + ${TEMP}/rcc8_mire2_vectorizer.shp +) + +ADD_TEST(coTvVectorDataToLabelMapFilter ${COMMON_TESTS11} +otbLabelMapToVectorDataFilter + ${INPUTDATA}/vectorIOexample_gis_to_vec.shp + ${TEMP}/vectordataToLabelMap.png +) + # ------- Fichiers sources CXX ----------------------------------- SET(BasicCommon_SRCS1 otbCommonTests1.cxx @@ -1039,6 +1075,8 @@ otbVectorDataToGISTableFilterNew.cxx otbLabelMapToGISTableFilterNew.cxx otbGISTableToLabelMapFilterNew.cxx otbGISTableToVectorDataFilterNew.cxx +otbLabelMapToGISTableFilter.cxx +otbGISTableToVectorDataFilter.cxx ) ENDIF(OTB_USE_PQXX) @@ -1051,7 +1089,10 @@ otbShapeAttributesLabelMapFilterNew.cxx otbStatisticsAttributesLabelMapFilterNew.cxx otbAttributesMapOpeningLabelMapFilterNew.cxx otbLabelMapToVectorDataFilterNew.cxx +otbLabelMapToVectorDataFilter.cxx otbLabelMapSourceNew.cxx +otbVectorDataToLabelMapFilterNew.cxx +otbVectorDataToLabelMapFilter.cxx otbUnaryFunctorWithIndexImageFilterNew.cxx otbUnaryFunctorWithIndexImageFilter.cxx otbLabelObjectMapVectorizer.cxx diff --git a/Testing/Code/Common/otbCommonTests10.cxx b/Testing/Code/Common/otbCommonTests10.cxx index 9bbfd4baa164448ca933f8048e4765e4989520f8..bc9ae7b05826f7a67ae56c47d28deaa8c3ec8829 100644 --- a/Testing/Code/Common/otbCommonTests10.cxx +++ b/Testing/Code/Common/otbCommonTests10.cxx @@ -36,4 +36,6 @@ void RegisterTests() REGISTER_TEST(otbLabelMapToGISTableFilterNew); REGISTER_TEST(otbGISTableToVectorDataFilterNew); REGISTER_TEST(otbGISTableToLabelMapFilterNew); + REGISTER_TEST(otbLabelMapToGISTableFilter); + REGISTER_TEST(otbGISTableToVectorDataFilter); } diff --git a/Testing/Code/Common/otbCommonTests11.cxx b/Testing/Code/Common/otbCommonTests11.cxx index 507ecf200742250659e65efe06b674f8ed5a351e..96c60a0477448359e6d58e52f56897a8d21b47f2 100644 --- a/Testing/Code/Common/otbCommonTests11.cxx +++ b/Testing/Code/Common/otbCommonTests11.cxx @@ -34,7 +34,12 @@ void RegisterTests() REGISTER_TEST(otbAttributesMapOpeningLabelMapFilterNew); REGISTER_TEST(otbLabelMapToVectorDataFilterNew); REGISTER_TEST(otbLabelMapSourceNew); + REGISTER_TEST(otbVectorDataToLabelMapFilterNew); + REGISTER_TEST(otbVectorDataToLabelMapFilter); REGISTER_TEST(otbUnaryFunctorWithIndexImageFilterNew); REGISTER_TEST(otbUnaryFunctorWithIndexImageFilter); REGISTER_TEST(otbLabelObjectMapVectorizer); + REGISTER_TEST(otbLabelMapToVectorDataFilter); + + } diff --git a/Testing/Code/Common/otbGISTableToVectorDataFilter.cxx b/Testing/Code/Common/otbGISTableToVectorDataFilter.cxx new file mode 100644 index 0000000000000000000000000000000000000000..e15a66634f916336dd8f76f1f244a7a6879f7936 --- /dev/null +++ b/Testing/Code/Common/otbGISTableToVectorDataFilter.cxx @@ -0,0 +1,90 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "otbVectorDataFileWriter.h" +//#include "otbImageFileWriter.h" +#include "otbVectorData.h" +//#include "otbVectorDataProjectionFilter.h" +//#include "otbVectorDataExtractROI.h" +#include <fstream> +#include <iostream> + +//#include "itkRGBAPixel.h" +#include "otbPostGISTable.h" +#include "otbGISTableToVectorDataFilter.h" +//#include "itkAttributeLabelObject.h" +#include "otbPostGISConnectionImplementation.h" + +int otbGISTableToVectorDataFilter(int argc, char * argv[]) +{ + /** Read a PostGIS table and write it in a VectorData. The Filter is based on the OGR reader/writer factory*/ + if ( argc != 6 ) + { + std::cerr << "Usage: " << argv[0]; + std::cerr << " outputFile(shp) dbName tableName userName userPassword" << std::endl; + return EXIT_FAILURE; + } + + const int dim = 2; + + const std::string dbName = argv[2]; + const std::string tableName = argv[3]; + const std::string userName = argv[4]; + const std::string userPassword = argv[5]; + + + + typedef unsigned char PType; + + typedef otb::VectorData<double, dim> VectorDataType; + + typedef otb::PostGISConnectionImplementation GISConnectionType; + typedef GISConnectionType::Pointer GISConnectionPointerType; + + typedef otb::PostGISTable<GISConnectionType, double, dim> GISTableType; + + //Instantiation + GISTableType::Pointer data = GISTableType::New(); + + GISConnectionPointerType myConnection = GISConnectionType::New(); + + myConnection->SetHost( "localhost" ); + myConnection->SetDBName( dbName ); + myConnection->SetUser( userName ); + myConnection->SetPassword( userPassword ); + + data->SetConnection(myConnection); + data->SetTableName(tableName); + + typedef otb::GISTableToVectorDataFilter< GISTableType , VectorDataType > GISTableToVectorDataFilter; + + GISTableToVectorDataFilter::Pointer MyFilter = GISTableToVectorDataFilter::New(); + std::cout << MyFilter << std::endl; + MyFilter->SetInput(data); + MyFilter->Update(); + typedef otb::VectorDataFileWriter<VectorDataType> WriterType; + + WriterType::Pointer writer = WriterType::New(); + + writer->SetFileName(argv[1]); + writer->SetInput(MyFilter->GetOutput()); + writer->Update(); + //data->itkGetObjectMacro ( ) + + return EXIT_SUCCESS; +} diff --git a/Testing/Code/Common/otbLabelMapToGISTableFilter.cxx b/Testing/Code/Common/otbLabelMapToGISTableFilter.cxx new file mode 100644 index 0000000000000000000000000000000000000000..26481276829740b991f6956683c417fff683ff17 --- /dev/null +++ b/Testing/Code/Common/otbLabelMapToGISTableFilter.cxx @@ -0,0 +1,98 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "otbImageFileReader.h" + +//#include "otbVectorDataExtractROI.h" +#include <fstream> +#include <iostream> + +#include "otbPolygon.h" +#include "otbImage.h" +#include "otbLabelMapToGISTableFilter.h" +#include "otbAttributesMapLabelObject.h" +#include "itkLabelImageToLabelMapFilter.h" +#include "otbPostGISConnectionImplementation.h" +#include "otbPostGISTable.h" + +int otbLabelMapToGISTableFilter(int argc, char * argv[]) +{ + + if ( argc != 6 ) + { + std::cerr << "Usage: " << argv[0]; + std::cerr << " inputLabelImageFile dbName tableName userName userPassword" << std::endl; + return EXIT_FAILURE; + } + + const char * infname = argv[1]; + const std::string dbName = argv[2]; + const std::string tableName = argv[3]; + const std::string userName = argv[4]; + const std::string userPassword = argv[5]; + + // Labeled image type + const unsigned int Dimension = 2; + typedef unsigned short LabelType; + typedef otb::Image<LabelType,Dimension> LabeledImageType; + typedef otb::ImageFileReader<LabeledImageType> LabeledReaderType; + + // Label map typedef + typedef otb::AttributesMapLabelObject<LabelType,Dimension,double> LabelObjectType; + typedef itk::LabelMap<LabelObjectType> LabelMapType; + typedef itk::LabelImageToLabelMapFilter<LabeledImageType,LabelMapType> LabelMapFilterType; + typedef otb::Polygon<double> PolygonType; + typedef otb::Functor::LabelObjectToPolygonFunctor<LabelObjectType,PolygonType> FunctorType; + + typedef otb::PostGISConnectionImplementation BdConnection; + typedef otb::PostGISConnectionImplementation::Pointer BdConnectionPointer; + + BdConnectionPointer myConnection = BdConnection::New(); + myConnection->SetHost( "localhost" ); + myConnection->SetDBName( dbName ); + myConnection->SetUser( userName ); + myConnection->SetPassword( userPassword ); + + typedef otb::PostGISTable<BdConnection, double, 2> PostGISTableType; + + + LabeledReaderType::Pointer lreader = LabeledReaderType::New(); + lreader->SetFileName(infname); + + LabelMapFilterType::Pointer labelMapFilter = LabelMapFilterType::New(); + labelMapFilter->SetInput(lreader->GetOutput()); + labelMapFilter->SetBackgroundValue(itk::NumericTraits<LabelType>::max()); + labelMapFilter->Update(); + + + typedef otb::LabelMapToGISTableFilter< LabelMapType , PostGISTableType > LabelMapToGISTableFilterType; + + LabelMapToGISTableFilterType::Pointer myFilter = LabelMapToGISTableFilterType::New(); + + myFilter->SetInput(labelMapFilter->GetOutput()); + + + myFilter->SetInputGISConnection(myConnection); + myFilter->SetGISTableName(tableName); + myFilter->SetDropExistingGISTable (true); + + myFilter->Update(); + + return EXIT_SUCCESS; + +} diff --git a/Testing/Code/Common/otbLabelMapToVectorDataFilter.cxx b/Testing/Code/Common/otbLabelMapToVectorDataFilter.cxx new file mode 100644 index 0000000000000000000000000000000000000000..657651b7af2099ae86e4a9a2b9a5b0031fe26e74 --- /dev/null +++ b/Testing/Code/Common/otbLabelMapToVectorDataFilter.cxx @@ -0,0 +1,93 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "otbImageFileReader.h" +#include "otbVectorDataFileWriter.h" +#include "otbVectorData.h" +#include "otbVectorDataProjectionFilter.h" +//#include "otbVectorDataExtractROI.h" +#include <fstream> +#include <iostream> + +//#include "itkRGBAPixel.h" +#include "otbImage.h" +#include "otbLabelMapToVectorDataFilter.h" +#include "otbAttributesMapLabelObject.h" +#include "itkLabelImageToLabelMapFilter.h" + +int otbLabelMapToVectorDataFilter(int argc, char * argv[]) +{ + /** Use the labelObjecttopolygon functor (not thread safe) only polygon conversion is available yet*/ + if ( argc != 3 ) + { + std::cerr << "Usage: " << argv[0]; + std::cerr << " inputImageFile outputVectorfile(shp)" << std::endl; + return EXIT_FAILURE; + } + const char * infname = argv[1]; + const char * outfname = argv[2]; + + // Labeled image type + const unsigned int Dimension = 2; + typedef unsigned short LabelType; + typedef otb::Image<LabelType,Dimension> LabeledImageType; + typedef otb::ImageFileReader<LabeledImageType> LabeledReaderType; + + // Label map typedef + typedef otb::AttributesMapLabelObject<LabelType,Dimension,double> LabelObjectType; + typedef itk::LabelMap<LabelObjectType> LabelMapType; + typedef itk::LabelImageToLabelMapFilter<LabeledImageType,LabelMapType> LabelMapFilterType; + typedef otb::Polygon<double> PolygonType; + typedef otb::Functor::LabelObjectToPolygonFunctor<LabelObjectType,PolygonType> FunctorType; + typedef otb::VectorData<double,2> VectorDataType; + typedef VectorDataType::DataNodeType DataNodeType; + typedef otb::VectorDataFileWriter<VectorDataType> WriterType; + typedef otb::VectorDataProjectionFilter<VectorDataType,VectorDataType> VectorDataFilterType; + + + LabeledReaderType::Pointer lreader = LabeledReaderType::New(); + lreader->SetFileName(infname); + + LabelMapFilterType::Pointer labelMapFilter = LabelMapFilterType::New(); + labelMapFilter->SetInput(lreader->GetOutput()); + labelMapFilter->SetBackgroundValue(itk::NumericTraits<LabelType>::max()); + labelMapFilter->Update(); + + WriterType::Pointer writer = WriterType::New(); + + typedef otb::LabelMapToVectorDataFilter< LabelMapType , VectorDataType > LabelMapToVectorDataFilterType; + + LabelMapToVectorDataFilterType::Pointer MyFilter = LabelMapToVectorDataFilterType::New(); + + MyFilter->SetInput(labelMapFilter->GetOutput()); + MyFilter->Update(); + + MyFilter->GetOutput()->SetProjectionRef(lreader->GetOutput()->GetProjectionRef()); + + VectorDataFilterType::Pointer vectorDataProjection = VectorDataFilterType::New(); + vectorDataProjection->SetInputOrigin(lreader->GetOutput()->GetOrigin()); + vectorDataProjection->SetInputSpacing(lreader->GetOutput()->GetSpacing()); + vectorDataProjection->SetInput(MyFilter->GetOutput()); + + writer->SetFileName(outfname); + writer->SetInput(vectorDataProjection->GetOutput()); + writer->Update(); + + return EXIT_SUCCESS; + +} diff --git a/Testing/Code/Common/otbVectorDataToLabelMapFilter.cxx b/Testing/Code/Common/otbVectorDataToLabelMapFilter.cxx new file mode 100644 index 0000000000000000000000000000000000000000..7406bf2742481cb585abbca7d7f41700c326fd4b --- /dev/null +++ b/Testing/Code/Common/otbVectorDataToLabelMapFilter.cxx @@ -0,0 +1,115 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#include "itkExceptionObject.h" +#include "itkLabelMapToLabelImageFilter.h" + +#include "itkTimeProbe.h" +#include "otbMacro.h" +#include "otbImage.h" +//#include "otbImageFileReader.h" +#include "otbImageFileWriter.h" +#include "otbVectorDataToLabelMapFilter.h" + +#include "otbVectorDataFileReader.h" +#include "itkMinimumMaximumImageCalculator.h" +#include "otbAttributesMapLabelObject.h" + +#include "otbVectorDataProperties.h" +#include "itkNumericTraits.h" + +int otbVectorDataToLabelMapFilter(int argc, char * argv[]) +{ + + /** Rasterize vectorData to LabelMap (only available for polygon yet)*/ + if ( argc != 3 ) + { + std::cerr << "Usage: " << argv[0]; + std::cerr << " inputFile(shp) outputLabeledImagefile" << std::endl; + return EXIT_FAILURE; + } + + const char * infname = argv[1]; + const char * outfname = argv[2]; + //const char * outvectorfname = argv[3]; + + // Labeled image type + const unsigned int Dimension = 2; + typedef unsigned short LabelType; + typedef otb::Image<LabelType,Dimension> LabeledImageType; + typedef otb::ImageFileWriter<LabeledImageType> WriterType; + + // Label map typedef + typedef otb::AttributesMapLabelObject<LabelType,Dimension,double> LabelObjectType; + typedef itk::LabelMap<LabelObjectType> LabelMapType; + + typedef otb::VectorData<double,Dimension> VectorDataType; + typedef otb::VectorDataFileReader<VectorDataType> ReaderType; + typedef otb::VectorDataToLabelMapFilter<VectorDataType, LabelMapType> VectorDataToLabelMapFilterType; + + typedef itk::LabelMapToLabelImageFilter<LabelMapType, LabeledImageType> LabelMapToLabelImageFilterType; + + ReaderType::Pointer reader = ReaderType::New(); + reader->SetFileName(infname); + //Update the reader + reader->Update(); + + VectorDataToLabelMapFilterType::Pointer myFilter = VectorDataToLabelMapFilterType::New(); + myFilter->SetInput(reader->GetOutput()); + + + //TODO Simplify the use of the class VectorDataProperties + //VectorDataProperties is needed to compute the ROI of the vectorData + typedef otb::VectorDataProperties <VectorDataType> VectorDataPropertiesType; + VectorDataPropertiesType::Pointer p=VectorDataPropertiesType::New(); + //set the input vectordata to the properties properties + p->SetVectorDataObject(reader->GetOutput()); + typedef VectorDataType::DataNodeType::PolygonType::RegionType RegionType; + RegionType region; + typedef RegionType::IndexType index; + typedef RegionType::SizeType size; + + p->SetBoundingRegion(region); + + //Compute the global bounding box of the vectordata + p->ComputeBoundingRegion(); + + LabelMapType::PointType origin; + + origin[0] = p->GetBoundingRegion().GetImageRegion().GetIndex(0); + origin[1] = p->GetBoundingRegion().GetImageRegion().GetIndex(1); + + //Set size,origin and spacing of the output labelmap + myFilter->SetSize(p->GetBoundingRegion().GetImageRegion().GetSize()); + myFilter->SetOrigin(origin); + myFilter->SetSpacing(reader->GetOutput()->GetSpacing()); + + // Translate the LabelMap in a labeld image + LabelMapToLabelImageFilterType::Pointer labelMapToImageFilter = LabelMapToLabelImageFilterType::New(); + labelMapToImageFilter->SetInput(myFilter->GetOutput()); + + + + //Write the result to an image file + WriterType::Pointer writer = WriterType::New(); + + writer->SetFileName(outfname); + writer->SetInput(labelMapToImageFilter->GetOutput()); + writer->Update(); + + return EXIT_SUCCESS; +} diff --git a/Testing/Code/Common/otbVectorDataToLabelMapFilterNew.cxx b/Testing/Code/Common/otbVectorDataToLabelMapFilterNew.cxx new file mode 100644 index 0000000000000000000000000000000000000000..58372f59f35fb8ffc4087df1a91061d011d8cfc4 --- /dev/null +++ b/Testing/Code/Common/otbVectorDataToLabelMapFilterNew.cxx @@ -0,0 +1,40 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#include "itkExceptionObject.h" +#include "otbMacro.h" + +#include "otbVectorDataToLabelMapFilter.h" +#include "otbAttributesMapLabelObject.h" + +int otbVectorDataToLabelMapFilterNew(int argc, char * argv[]) +{ + typedef unsigned short LabelType; + const unsigned int Dimension = 2; + typedef otb::VectorData<double,Dimension> VectorDataType; + typedef otb::AttributesMapLabelObject<LabelType,Dimension,double> LabelObjectType; + typedef itk::LabelMap<LabelObjectType> OutputLabelMapType; + + typedef otb::VectorDataToLabelMapFilter< VectorDataType , OutputLabelMapType > VectorDataToLabelMapFilterType; + + + + //Instantiation + VectorDataToLabelMapFilterType::Pointer MyFilter = VectorDataToLabelMapFilterType::New(); + + return EXIT_SUCCESS; +} diff --git a/Testing/Code/IO/CMakeLists.txt b/Testing/Code/IO/CMakeLists.txt index 90a8b89f41a30b817a20345a8b29070250967223..9eb0a44ea746df948c89561a2f5ab8051221ab24 100755 --- a/Testing/Code/IO/CMakeLists.txt +++ b/Testing/Code/IO/CMakeLists.txt @@ -1731,6 +1731,36 @@ ADD_TEST(ioTvVectorDataFileGeoReaderWriter2 ${IO_TESTS15} ${TEMP}/ioTvVectorDataFileGeoReaderWriterOutput2.shp ) +# CanRead OGR GML() +ADD_TEST(otbOGRVectorDataIOTestCanRead ${IO_TESTS15} + otbOGRVectorDataIOTestCanRead + ${INPUTDATA}/adressPoint.gml) + +# CanRead OGR MapInfo() +ADD_TEST(otbOGRVectorDataIOTestCanRead ${IO_TESTS15} + otbOGRVectorDataIOTestCanRead + ${INPUTDATA}/LOCALITY_POLYGON.tab) + +# CanRead OGR PostGIS() +ADD_TEST(otbOGRVectorDataIOTestCanRead ${IO_TESTS15} + otbOGRVectorDataIOTestCanRead + PG:"dbname='orfeotoolbox_test' host='localhost' port='5432' user='orfeotoolbox_test_user' password='Bidfeud0'") + +# CanWrite OGR GML() +ADD_TEST(otbOGRVectorDataIOCanWrite ${IO_TESTS15} + otbOGRVectorDataIOCanWrite + ${INPUTDATA}/adressPoint.gml) + +# CanWrite OGR MapInfo() +ADD_TEST(otbOGRVectorDataIOCanWrite ${IO_TESTS15} + otbOGRVectorDataIOCanWrite + ${INPUTDATA}/LOCALITY_POLYGON.tab) + +# Canwrite OGR PostGIS() +ADD_TEST(otbOGRVectorDataIOCanWrite ${IO_TESTS15} + otbOGRVectorDataIOCanWrite + PG:"dbname='orfeotoolbox_test' host='localhost' port='5432' user='orfeotoolbox_test_user' password='Bidfeud0'") + ADD_TEST(ioTuKMLVectorDataIO ${IO_TESTS15} otbKMLVectorDataIONew ) @@ -2194,6 +2224,8 @@ otbVectorDataFileWriterPolygons.cxx otbVectorDataFileReaderWriter.cxx otbVectorDataFileGeoReaderWriter.cxx otbOGRVectorDataIONew.cxx +otbOGRVectorDataIOCanRead.cxx +otbOGRVectorDataIOCanWrite.cxx otbKMLVectorDataIONew.cxx otbKMLVectorDataIOTestCanRead.cxx otbKMLVectorDataIOTestCanWrite.cxx diff --git a/Testing/Code/IO/otbIOTests15.cxx b/Testing/Code/IO/otbIOTests15.cxx index a125de4499774f83978a22d11634b155040577d3..fcf16ddc93460e81ed31a74907b9796b6599ba0b 100644 --- a/Testing/Code/IO/otbIOTests15.cxx +++ b/Testing/Code/IO/otbIOTests15.cxx @@ -38,6 +38,8 @@ void RegisterTests() REGISTER_TEST(otbVectorDataFileGeoReaderWriter); REGISTER_TEST(otbOGRVectorDataIONew); REGISTER_TEST(otbKMLVectorDataIONew); + REGISTER_TEST(otbOGRVectorDataIOTestCanRead); + REGISTER_TEST(otbOGRVectorDataIOCanWrite); REGISTER_TEST(otbKMLVectorDataIOTestCanRead); REGISTER_TEST(otbKMLVectorDataIOTestCanWrite); REGISTER_TEST(otbKMLVectorDataIOTestFileReader); diff --git a/Testing/Code/IO/otbKMLVectorDataIOTestCanWrite.cxx b/Testing/Code/IO/otbKMLVectorDataIOTestCanWrite.cxx index 0af7e228093e3223898b2cd14361a1f0500d09d7..298f78cebdaffb3e14b36e5c26c69a53faeb6885 100644 --- a/Testing/Code/IO/otbKMLVectorDataIOTestCanWrite.cxx +++ b/Testing/Code/IO/otbKMLVectorDataIOTestCanWrite.cxx @@ -25,8 +25,8 @@ int otbKMLVectorDataIOTestCanWrite(int argc, char* argv[]) typedef otb::VectorData<> VectorDataType; typedef otb::KMLVectorDataIO<VectorDataType> KMLVectorDataIOType; KMLVectorDataIOType::Pointer object = KMLVectorDataIOType::New(); - bool lCanRead = object->CanWriteFile(argv[1]); - if ( lCanRead == false) + bool lCanWrite = object->CanWriteFile(argv[1]); + if ( lCanWrite == false) { std::cerr << "Erreur otb::KMLVectorDataIO : impossible to create the file "<<argv[1]<<"."<<std::endl; return EXIT_FAILURE; diff --git a/Testing/Code/IO/otbOGRVectorDataIOCanRead.cxx b/Testing/Code/IO/otbOGRVectorDataIOCanRead.cxx new file mode 100644 index 0000000000000000000000000000000000000000..7aa9b5dd0f9d4d8647b9bc5305a2bbac2ec04e35 --- /dev/null +++ b/Testing/Code/IO/otbOGRVectorDataIOCanRead.cxx @@ -0,0 +1,36 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "otbOGRVectorDataIO.h" +#include "otbVectorData.h" +#include <iostream> + +int otbOGRVectorDataIOTestCanRead(int argc, char* argv[]) +{ + typedef otb::VectorData<> VectorDataType; + typedef otb::OGRVectorDataIO<VectorDataType> OGRVectorDataIOType; + OGRVectorDataIOType::Pointer object = OGRVectorDataIOType::New(); + bool lCanRead = object->CanReadFile(argv[1]); + if ( lCanRead == false) + { + std::cerr << "Erreur otb::OGRVectorDataIO : impossible to open the file "<<argv[1]<<"."<<std::endl; + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} diff --git a/Testing/Code/IO/otbOGRVectorDataIOCanWrite.cxx b/Testing/Code/IO/otbOGRVectorDataIOCanWrite.cxx new file mode 100644 index 0000000000000000000000000000000000000000..11ec1754a5f73a185717a9da9245786d40e5d957 --- /dev/null +++ b/Testing/Code/IO/otbOGRVectorDataIOCanWrite.cxx @@ -0,0 +1,36 @@ +/*========================================================================= + + Program: ORFEO Toolbox + Language: C++ + Date: $Date$ + Version: $Revision$ + + + Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. + See OTBCopyright.txt for details. + + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "otbOGRVectorDataIO.h" +#include "otbVectorData.h" +#include <iostream> + +int otbOGRVectorDataIOCanWrite(int argc, char* argv[]) +{ + typedef otb::VectorData<> VectorDataType; + typedef otb::OGRVectorDataIO<VectorDataType> OGRVectorDataIOType; + OGRVectorDataIOType::Pointer object = OGRVectorDataIOType::New(); + bool lCanWrite = object->CanWriteFile(argv[1]); + if ( lCanWrite == false) + { + std::cerr << "Erreur otb::OGRVectorDataIO : impossible to create the file "<<argv[1]<<"."<<std::endl; + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} diff --git a/Testing/Code/MultiScale/CMakeLists.txt b/Testing/Code/MultiScale/CMakeLists.txt index 777cff7411ecae1d5fe6fecbc6edbfb8fee81ef8..f785610364b848f3bc7753cd812a9af3989ee608 100644 --- a/Testing/Code/MultiScale/CMakeLists.txt +++ b/Testing/Code/MultiScale/CMakeLists.txt @@ -377,7 +377,7 @@ ADD_TEST(msTuWaveletInverseFilterBankNew ${MULTISCALE_TESTS4} otbWaveletInverseFilterBankNew) ADD_TEST(msTvWaveletFilterBank ${MULTISCALE_TESTS4} - --compare-image ${TOL} + --compare-image ${EPSILON6} ${INPUTDATA}/ROI_IKO_PAN_LesHalles.tif ${TEMP}/ROI_IKO_PAN_LesHalles_FilterBank.tif otbWaveletFilterBank diff --git a/Utilities/ITK/CMake/itkSampleBuildTest.cmake.in b/Utilities/ITK/CMake/itkSampleBuildTest.cmake.in index d73c3a35a3d0b5a6ccb55adbe1cca881f2cb322e..8a7df73718283266dad414916412ed221b3adffd 100644 --- a/Utilities/ITK/CMake/itkSampleBuildTest.cmake.in +++ b/Utilities/ITK/CMake/itkSampleBuildTest.cmake.in @@ -111,7 +111,6 @@ BUILD_EXAMPLES:BOOL=@BUILD_EXAMPLES@ ITK_USE_PATENTED:BOOL=@ITK_USE_PATENTED@ ITK_USE_REVIEW:BOOL=@ITK_USE_REVIEW@ ITK_USE_REVIEW_STATISTICS:BOOL=@ITK_USE_REVIEW_STATISTICS@ -ITK_USE_PORTABLE_ROUND:BOOL=@ITK_USE_PORTABLE_ROUND@ ITK_USE_REGION_VALIDATION_IN_ITERATORS:BOOL=@ITK_USE_REGION_VALIDATION_IN_ITERATORS@ ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY:BOOL=@ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY@ ITK_USE_CONCEPT_CHECKING:BOOL=@ITK_USE_CONCEPT_CHECKING@ diff --git a/Utilities/ITK/CMakeLists.txt b/Utilities/ITK/CMakeLists.txt index 5afa9c2e6ed3acc06350ab13bbdba1cac43953be..08f7f58eb071e4adf6b06d893b4f146b1d581345 100644 --- a/Utilities/ITK/CMakeLists.txt +++ b/Utilities/ITK/CMakeLists.txt @@ -47,7 +47,7 @@ ENDIF("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" MATCHES "^2\\.4$") #----------------------------------------------------------------------------- # ITK version number. An even minor number corresponds to releases. SET(ITK_VERSION_MAJOR "3") -SET(ITK_VERSION_MINOR "14") +SET(ITK_VERSION_MINOR "16") SET(ITK_VERSION_PATCH "0") # Version string should not include patch level. The major.minor is @@ -197,7 +197,7 @@ IF(ITK_USE_OPTIMIZED_REGISTRATION_METHODS) MESSAGE(FATAL_ERROR "ITK_USE_REVIEW is currently OFF but it should be ON if you want to use the experimental optimized registration methods.") ENDIF(NOT ITK_USE_REVIEW) # Warn the user about the implications of turning optimized registration methods ON - SET(msg "Attention: You have chosen to enable the use of Optimizer Registration Methods.") + SET(msg "Attention: You have chosen to enable the use of Optimized Registration Methods.") SET(msg "${msg} These methods add multi-threading capabilities to several image metrics") SET(msg "${msg} as well as some Transforms and Interpolators. In order to take full advantage") SET(msg "${msg} of these new features you will have to also add some new calls to these components.") @@ -261,21 +261,8 @@ MARK_AS_ADVANCED(ITK_USE_ORIENTED_IMAGE_DIRECTION) #----------------------------------------------------------------------------- # ITK turn on the correct usage of centered-pixel coordinates. -OPTION(ITK_USE_PORTABLE_ROUND "Turn on round implementation that works in multiple-platforms." OFF) -MARK_AS_ADVANCED(ITK_USE_PORTABLE_ROUND) - - -#----------------------------------------------------------------------------- -# ITK turn on the correct usage of centered-pixel coordinates. -OPTION(ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY "Turn on correct usage of centered-pixel coordinates." OFF) +OPTION(ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY "Turn on correct usage of centered-pixel coordinates." ON) MARK_AS_ADVANCED(ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY) -IF(ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY) - MESSAGE("Attention: You enabled ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY This feature has not been fully tested and validated.") - IF(NOT ITK_USE_PORTABLE_ROUND) - MESSAGE(FATAL_ERROR "ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY is currently ON but ITK_USE_PORTABLE_ROUND is OFF, you should enable the portable round") - ENDIF(NOT ITK_USE_PORTABLE_ROUND) -ENDIF(ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY) - #----------------------------------------------------------------------------- # ITK turn on the correct usage of centered-pixel coordinates. @@ -303,13 +290,41 @@ MARK_AS_ADVANCED(ITK_USE_DEPRECATED_LEVELSET_INTERPOLATION) # ITK_INSTALL_NO_DOCUMENTATION - do not install documentation files IF(NOT ITK_INSTALL_BIN_DIR) + # Solaris: unlike libraries, 64 bit executables should be installed in "bin${sun64}" only + # if the 32 version is installed in "bin/sparcv7" or "bin/i86", and a isaexec + # is copied in "bin" with the name of the executable, so the system can choose the best + # executable. If only a 32 or 64 bit version is available, the executable should go in + # bin. So it seems better to let the packagers deal with that. + # Ref: http://docs.sun.com/app/docs/doc/816-5138/dev-env-13?a=view SET(ITK_INSTALL_BIN_DIR "/bin") ENDIF(NOT ITK_INSTALL_BIN_DIR) IF(NOT ITK_INSTALL_LIB_DIR) + # 64 bit libraries are not installed in the same directories on solaris + # Ref: http://docs.sun.com/app/docs/doc/816-5138/6mba6ua5m?a=view + SET(sun64 ) + IF(CMAKE_SYSTEM MATCHES "SunOS.*" AND CMAKE_SIZEOF_VOID_P EQUAL 8) + EXEC_PROGRAM("uname" + ARGS "-p" + OUTPUT_VARIABLE sunproc + ) + IF("${sunproc}" STREQUAL "sparc") + SET(sun64 "/sparcv9") + ENDIF("${sunproc}" STREQUAL "sparc") + + IF("${sunproc}" STREQUAL "i386") + SET(sun64 "/amd64") + ENDIF("${sunproc}" STREQUAL "i386") + + IF("${sun64}" STREQUAL "") + # sun64 is not set - solaris has been ported to a new architecture? + MESSAGE("Warning: Unknown processor '${sunproc}'. The libraries may not be installed in the right place.") + ENDIF("${sun64}" STREQUAL "") + ENDIF(CMAKE_SYSTEM MATCHES "SunOS.*" AND CMAKE_SIZEOF_VOID_P EQUAL 8) + # OTB Modifications -# SET(ITK_INSTALL_LIB_DIR "/lib/InsightToolkit") - SET(ITK_INSTALL_LIB_DIR "/lib/otb") +# SET(ITK_INSTALL_LIB_DIR "/lib/InsightToolkit${sun64}") + SET(ITK_INSTALL_LIB_DIR "/lib/otb${sun64}") ENDIF(NOT ITK_INSTALL_LIB_DIR) IF(NOT ITK_INSTALL_DATA_DIR) @@ -410,12 +425,30 @@ INCLUDE(${ITK_SOURCE_DIR}/Wrapping/itkWrapSetup.cmake) IF(WIN32) + # Some libraries (e.g. vxl libs) have no dllexport markup, so we can + # build full shared libraries only with the GNU toolchain. + IF(CMAKE_COMPILER_IS_GNUCXX) + # CMake adds --enable-all-exports on Cygwin (since Cygwin is + # supposed to be UNIX-like), but we need to add it explicitly for + # a native windows build with the MinGW tools. + IF(MINGW) + SET(CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS + "-shared -Wl,--export-all-symbols -Wl,--enable-auto-import") + SET(CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS + "-shared -Wl,--export-all-symbols -Wl,--enable-auto-import") + SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--enable-auto-import") + ENDIF(MINGW) + IF(CYGWIN) + SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--enable-auto-import") + ENDIF(CYGWIN) + ELSE(CMAKE_COMPILER_IS_GNUCXX) IF(BUILD_SHARED_LIBS) SET(ITK_COMMON_BUILD_TYPE "SHARED") ELSE(BUILD_SHARED_LIBS) SET(ITK_COMMON_BUILD_TYPE "STATIC") ENDIF(BUILD_SHARED_LIBS) SET(BUILD_SHARED_LIBS OFF) + ENDIF(CMAKE_COMPILER_IS_GNUCXX) ENDIF(WIN32) # OTB Modifications @@ -477,9 +510,9 @@ IF(CMAKE_COMPILER_IS_GNUCXX) SET(ITK_REQUIRED_CXX_FLAGS "${ITK_REQUIRED_CXX_FLAGS} -ftemplate-depth-50 -Wall") INCLUDE(${ITK_SOURCE_DIR}/CMake/itkCheckCXXAcceptsFlags.cmake) itkCHECK_CXX_ACCEPTS_FLAGS("-Wno-deprecated" CXX_HAS_DEPRECATED_FLAG) - IF(CXX_HAS_DEPRECATED_FLAG) + IF(CXX_HAS_DEPRECATED_FLAG) SET(ITK_REQUIRED_CXX_FLAGS "${ITK_REQUIRED_CXX_FLAGS} -Wno-deprecated") - ENDIF(CXX_HAS_DEPRECATED_FLAG) + ENDIF(CXX_HAS_DEPRECATED_FLAG) IF(APPLE) # -no-cpp-precomp and -Wno-long-double were compiler flags present # only in Apple's gcc and not in the FSF gcc. The flags are obsolete @@ -500,7 +533,7 @@ IF(CMAKE_COMPILER_IS_GNUCXX) MARK_AS_ADVANCED(ITK_USE_64BITS_APPLE_TRUNCATION_WARNING) ENDIF(APPLE) - + # gcc must have -msse2 option to enable sse2 support IF(VNL_CONFIG_ENABLE_SSE2 OR VNL_CONFIG_ENABLE_SSE2_ROUNDING) SET(ITK_REQUIRED_CXX_FLAGS "${ITK_REQUIRED_CXX_FLAGS} -msse2") @@ -519,6 +552,14 @@ IF(UNIX) ENDIF(NOT CMAKE_COMPILER_IS_GNUCXX) ENDIF(UNIX) + +# +# This line is required for gcc 4.3.3, since ITK uses deprecated header files +# by default. +# +INCLUDE(TestForANSIStreamHeaders) + + IF(BORLAND) SET(ITK_REQUIRED_CXX_FLAGS "${ITK_REQUIRED_CXX_FLAGS} -w- -whid -waus -wpar") SET(ITK_REQUIRED_C_FLAGS "${ITK_REQUIRED_C_FLAGS} -w- -whid -waus -wpar") @@ -736,6 +777,14 @@ FIND_PATH(ITK_OSIRIX_DATA_ROOT CEREBRIX MARK_AS_ADVANCED(ITK_OSIRIX_DATA_ROOT) +#----------------------------------------------------------------------------- +# Configure the default ITK_VISIBLEHUMAN_DATA_ROOT for the location of Data from the Visible Human Project +# When this data is available, additional Examples are enabled. +FIND_PATH(ITK_VISIBLEHUMAN_DATA_ROOT Male/Fullcolor/fullbody + DOC "Directory with data taken from http://www.nlm.nih.gov/research/visible/getting_data.html") +MARK_AS_ADVANCED(ITK_VISIBLEHUMAN_DATA_ROOT) + + #----------------------------------------------------------------------------- # This flag is used in particular, to enable some tests that require large memory to run. # This probably can be discovered at configuration time by CMake. (Check with CMake developers). @@ -865,3 +914,4 @@ IF(CMAKE_COMPILER_IS_GNUCXX) ENDIF("${COMP_OPTION}" STREQUAL "-ffloat-store") ENDFOREACH(COMP_OPTION) ENDIF(CMAKE_COMPILER_IS_GNUCXX) + diff --git a/Utilities/ITK/CTestConfig.cmake b/Utilities/ITK/CTestConfig.cmake index 32e220f4a77efc96903cd3c88b0d980af1ed45ea..643e14e327a7e18861b4a49e50f75614481a77df 100644 --- a/Utilities/ITK/CTestConfig.cmake +++ b/Utilities/ITK/CTestConfig.cmake @@ -1,4 +1,4 @@ -set(CTEST_PROJECT_NAME "Insight") +set(CTEST_PROJECT_NAME "ITK") set(CTEST_NIGHTLY_START_TIME "21:00:00 EDT") set(CTEST_DROP_METHOD "http") diff --git a/Utilities/ITK/Code/Algorithms/itkBinaryMask3DMeshSource.h b/Utilities/ITK/Code/Algorithms/itkBinaryMask3DMeshSource.h index 92de9336bb24ab1a19237fbc5065763138df55fd..b11b86581969a40d7417016e6b997498e81fbcbe 100644 --- a/Utilities/ITK/Code/Algorithms/itkBinaryMask3DMeshSource.h +++ b/Utilities/ITK/Code/Algorithms/itkBinaryMask3DMeshSource.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBinaryMask3DMeshSource.h,v $ Language: C++ - Date: $Date: 2009-04-23 03:53:34 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-06-28 19:17:37 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -67,13 +67,7 @@ namespace itk * \par INPUT * The input should be a 3D binary image. * - * - * */ -#ifndef ITK_EXPLICIT_INSTANTIATION -//This is already explicitly defined when ITK_EXPLICIT_INSTANTIATION is used. -template class Image<unsigned short,3>; -#endif - + */ template <class TInputImage, class TOutputMesh> class ITK_EXPORT BinaryMask3DMeshSource : public ImageToMeshFilter< TInputImage, TOutputMesh > { diff --git a/Utilities/ITK/Code/Algorithms/itkBioCellularAggregate.txx b/Utilities/ITK/Code/Algorithms/itkBioCellularAggregate.txx index 1cdff8808d7b96b6478d329a56177628e3e8cc70..0869715f0329c3f072820c4cfd55c8b74943b815 100644 --- a/Utilities/ITK/Code/Algorithms/itkBioCellularAggregate.txx +++ b/Utilities/ITK/Code/Algorithms/itkBioCellularAggregate.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBioCellularAggregate.txx,v $ Language: C++ - Date: $Date: 2008-02-01 13:10:27 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-06-14 19:55:37 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -405,6 +405,7 @@ CellularAggregate<NSpaceDimension> CellsConstIterator end = m_Mesh->GetPointData()->End(); PointType position; + position.Fill(0); while( cellIt != end ) { @@ -442,6 +443,7 @@ CellularAggregate<NSpaceDimension> BioCellType * cell1 = cell1It.Value(); PointType position1; + position1.Fill(0); m_Mesh->GetPoint( cell1Id, &position1 ); const double rA = cell1->GetRadius(); diff --git a/Utilities/ITK/Code/Algorithms/itkCurvatureFlowFunction.txx b/Utilities/ITK/Code/Algorithms/itkCurvatureFlowFunction.txx index 5eb4a52d592e0dc798e00154de54da3f678fe890..bde6dbb377f7bf69f349d17d66796782a48b9611 100644 --- a/Utilities/ITK/Code/Algorithms/itkCurvatureFlowFunction.txx +++ b/Utilities/ITK/Code/Algorithms/itkCurvatureFlowFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCurvatureFlowFunction.txx,v $ Language: C++ - Date: $Date: 2008-10-23 16:26:55 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-07-30 11:57:13 $ + Version: $Revision: 1.20 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -84,9 +84,9 @@ CurvatureFlowFunction<TImage> ::ComputeUpdate(const NeighborhoodType &it, void * itkNotUsed(gd), const FloatOffsetType& itkNotUsed(offset)) { - PixelType firstderiv[ImageDimension]; - PixelType secderiv[ImageDimension]; - PixelType crossderiv[ImageDimension][ImageDimension]; + PixelRealType firstderiv[ImageDimension]; + PixelRealType secderiv[ImageDimension]; + PixelRealType crossderiv[ImageDimension][ImageDimension]; unsigned long center; unsigned long stride[ImageDimension]; unsigned int i,j; @@ -102,7 +102,7 @@ CurvatureFlowFunction<TImage> stride[i] = it.GetStride( (unsigned long) i ); } - PixelType magnitudeSqr = 0.0; + PixelRealType magnitudeSqr = 0.0; for( i = 0; i < ImageDimension; i++ ) { @@ -136,8 +136,8 @@ CurvatureFlowFunction<TImage> } // compute the update value = mean curvature * magnitude - PixelType update = 0.0; - PixelType temp; + PixelRealType update = 0.0; + PixelRealType temp; // accumulate dx^2 * (dyy + dzz) terms for( i = 0; i < ImageDimension; i++ ) @@ -170,7 +170,7 @@ CurvatureFlowFunction<TImage> globalData->m_MaxChange = vnl_math_max( globalData->m_MaxChange, vnl_math_abs(update) ); #endif - return update; + return static_cast<PixelType>(update); } diff --git a/Utilities/ITK/Code/Algorithms/itkCurvatureRegistrationFilter.txx b/Utilities/ITK/Code/Algorithms/itkCurvatureRegistrationFilter.txx index 6874de19658a7d42be387b385c4dc3938eb545f4..52a2594c44e97a64093d2076b235cbe1f65cbd8b 100644 --- a/Utilities/ITK/Code/Algorithms/itkCurvatureRegistrationFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkCurvatureRegistrationFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCurvatureRegistrationFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-23 16:15:23 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-08-08 12:32:43 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -215,6 +215,8 @@ void CurvatureRegistrationFilter<TFixedImage,TMovingImage,TDeformationField,TImageForceFunction> ::ApplyUpdate(TimeStepType dt) { + // unused dt parameter + (void) dt; DeformationFieldPointer update = this->GetUpdateBuffer(); ImageRegionConstIterator<DeformationFieldType> itInDeformation; @@ -247,9 +249,9 @@ CurvatureRegistrationFilter<TFixedImage,TMovingImage,TDeformationField,TImageFor // extract l-th component of deformation field. itInDeformation.GoToBegin(); itInUpdate.GoToBegin(); - for ( size_t offset = 0; (offset < numberOfPixels) && !itInDeformation.IsAtEnd() && !itInUpdate.IsAtEnd(); ++offset ) + for ( size_t offset1 = 0; (offset1 < numberOfPixels) && !itInDeformation.IsAtEnd() && !itInUpdate.IsAtEnd(); ++offset1 ) { - this->m_DeformationFieldComponentImage[offset] = this->m_TimeStep * itInUpdate.Value()[l] + itInDeformation.Value()[l]; + this->m_DeformationFieldComponentImage[offset1] = this->m_TimeStep * itInUpdate.Value()[l] + itInDeformation.Value()[l]; ++itInUpdate; ++itInDeformation; } @@ -279,9 +281,9 @@ CurvatureRegistrationFilter<TFixedImage,TMovingImage,TDeformationField,TImageFor // update deformation field itOutDeformation.GoToBegin(); - for ( size_t offset = 0; (offset < numberOfPixels) && ! itOutDeformation.IsAtEnd(); ++offset ) + for ( size_t offset1 = 0; (offset1 < numberOfPixels) && ! itOutDeformation.IsAtEnd(); ++offset1 ) { - itOutDeformation.Value()[l] = this->m_DeformationFieldComponentImage[offset] * normFactorDCT; + itOutDeformation.Value()[l] = this->m_DeformationFieldComponentImage[offset1] * normFactorDCT; ++itOutDeformation; } } diff --git a/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DGradientConstraintForceFilter.h b/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DGradientConstraintForceFilter.h index 4af70d3ca4661ed1be2d5479f3bed1be4d359d6f..0cc9e6ac354ee3bacd6917c6f86f8d41f004892e 100644 --- a/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DGradientConstraintForceFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkDeformableSimplexMesh3DGradientConstraintForceFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDeformableSimplexMesh3DGradientConstraintForceFilter.h,v $ Language: C++ - Date: $Date: 2009-05-12 17:26:20 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-08-16 13:33:47 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -124,7 +124,8 @@ public: typedef Image<float, 3> OriginalImageType; typedef typename OriginalImageType::IndexType OriginalImageIndexType; typedef typename OriginalImageIndexType::IndexValueType ImageIndexValueType; - typedef typename OriginalImageType::Pointer OriginalImagePointer; + typedef typename OriginalImageType::ConstPointer OriginalImagePointer; + /** control the range of search for Bresenham at normal line */ itkSetMacro(Range, int); itkGetConstMacro(Range, int); @@ -143,7 +144,7 @@ public: /** * Set Original image */ - itkSetMacro(Image, OriginalImagePointer); + itkSetConstObjectMacro( Image, OriginalImageType ); protected: DeformableSimplexMesh3DGradientConstraintForceFilter(); diff --git a/Utilities/ITK/Code/Algorithms/itkFEMRegistrationFilter.txx b/Utilities/ITK/Code/Algorithms/itkFEMRegistrationFilter.txx index bf0534cf2f516f433e1787909bf6fd36481aaccd..22673a29511cad1ba710f7570111abe3836ab58f 100644 --- a/Utilities/ITK/Code/Algorithms/itkFEMRegistrationFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkFEMRegistrationFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFEMRegistrationFilter.txx,v $ Language: C++ - Date: $Date: 2009-04-05 23:09:18 $ - Version: $Revision: 1.58 $ + Date: $Date: 2009-06-15 22:11:29 $ + Version: $Revision: 1.59 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -1775,6 +1775,7 @@ void FEMRegistrationFilter<TMovingImage,TFixedImage>::MultiResSolve() SolverType SSS; typename FixedImageType::SizeType nextLevelSize; + nextLevelSize.Fill( 0 ); typename FixedImageType::SizeType lastLevelSize; if (m_Maxiters[m_CurrentLevel] > 0) diff --git a/Utilities/ITK/Code/Algorithms/itkFastMarchingUpwindGradientImageFilter.h b/Utilities/ITK/Code/Algorithms/itkFastMarchingUpwindGradientImageFilter.h index d3d9f264a931cf0c227c2c315c966f5c650556a7..d9c36808579f0666dff2969f5e3d59cbd72dd8e1 100644 --- a/Utilities/ITK/Code/Algorithms/itkFastMarchingUpwindGradientImageFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkFastMarchingUpwindGradientImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFastMarchingUpwindGradientImageFilter.h,v $ Language: C++ - Date: $Date: 2007-04-20 11:52:27 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-07-29 10:31:53 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -164,7 +164,10 @@ public: /** Get the number of targets. */ itkGetConstReferenceMacro( NumberOfTargets, long ); - /** Get the arrival time corresponding to the last reached target. */ + /** Get the arrival time corresponding to the last reached target. + * If TargetReachedMode is set to NoTargets, TargetValue contains + * the last (aka largest) Eikonal solution value generated. + */ itkGetConstReferenceMacro( TargetValue, double ); enum diff --git a/Utilities/ITK/Code/Algorithms/itkFastMarchingUpwindGradientImageFilter.txx b/Utilities/ITK/Code/Algorithms/itkFastMarchingUpwindGradientImageFilter.txx index e630b957fff4b694ce215539cafdc971edf07443..22d85401d22e9acbc16f52120b01ac1b0f8a9e72 100644 --- a/Utilities/ITK/Code/Algorithms/itkFastMarchingUpwindGradientImageFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkFastMarchingUpwindGradientImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFastMarchingUpwindGradientImageFilter.txx,v $ Language: C++ - Date: $Date: 2007-04-25 15:59:57 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-07-29 10:31:53 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -235,6 +235,10 @@ FastMarchingUpwindGradientImageFilter<TLevelSet,TSpeedImage> } } } + else + { + m_TargetValue = static_cast<double>(output->GetPixel(index)); + } } /** diff --git a/Utilities/ITK/Code/Algorithms/itkImageKmeansModelEstimator.txx b/Utilities/ITK/Code/Algorithms/itkImageKmeansModelEstimator.txx index f8aafedc03700e351fed0039e366ae45afa9df65..967070d3009f94e294d11b51fde0387ef6b75d53 100644 --- a/Utilities/ITK/Code/Algorithms/itkImageKmeansModelEstimator.txx +++ b/Utilities/ITK/Code/Algorithms/itkImageKmeansModelEstimator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageKmeansModelEstimator.txx,v $ Language: C++ - Date: $Date: 2009-05-02 05:43:54 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-09-03 21:11:20 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -559,14 +559,14 @@ ImageKmeansModelEstimator<TInputImage, TMembershipFunction> // normalize the distortions *distortion /= ( double ) totalNumVecsInInput; + delete [] tempVec; + // check for bizarre errors if ( *distortion < 0.0 ) { itkExceptionMacro(<<"Computational overflow"); } - delete [] tempVec; - }// End nearest_neighbor_search_basic //----------------------------------------------------------------- diff --git a/Utilities/ITK/Code/Algorithms/itkImageToImageMetric.h b/Utilities/ITK/Code/Algorithms/itkImageToImageMetric.h index 903fbdfb971863f8999f25c0d11da09ac2258045..0021b00db150f5086e83d0fcafec326c2d49bfaa 100644 --- a/Utilities/ITK/Code/Algorithms/itkImageToImageMetric.h +++ b/Utilities/ITK/Code/Algorithms/itkImageToImageMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageToImageMetric.h,v $ Language: C++ - Date: $Date: 2007-11-12 20:00:37 $ - Version: $Revision: 1.25 $ + Date: $Date: 2009-08-20 09:08:41 $ + Version: $Revision: 1.26 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -131,13 +131,16 @@ public: this mask will be considered for the computation of the metric */ typedef SpatialObject< itkGetStaticConstMacro(FixedImageDimension) > FixedImageMaskType; - typedef typename FixedImageMaskType::Pointer FixedImageMaskPointer; + typedef typename FixedImageMaskType::Pointer FixedImageMaskPointer; + typedef typename FixedImageMaskType::ConstPointer FixedImageMaskConstPointer; + /** Type for the mask of the moving image. Only pixels that are "inside" this mask will be considered for the computation of the metric */ typedef SpatialObject< itkGetStaticConstMacro(MovingImageDimension) > MovingImageMaskType; - typedef typename MovingImageMaskType::Pointer MovingImageMaskPointer; + typedef typename MovingImageMaskType::Pointer MovingImageMaskPointer; + typedef typename MovingImageMaskType::ConstPointer MovingImageMaskConstPointer; /** Type of the measure. */ @@ -184,10 +187,22 @@ public: /** Set/Get the moving image mask. */ itkSetObjectMacro( MovingImageMask, MovingImageMaskType ); +#ifdef ITK_LEGACY_REMOVE + itkSetConstObjectMacro( MovingImageMask, MovingImageMaskType ); +#else + virtual void SetMovingImageMask( const MovingImageMaskType* mask ) + { this->SetMovingImageMask(const_cast<MovingImageMaskType*>(mask)); } +#endif itkGetConstObjectMacro( MovingImageMask, MovingImageMaskType ); /** Set/Get the fixed image mask. */ itkSetObjectMacro( FixedImageMask, FixedImageMaskType ); +#ifdef ITK_LEGACY_REMOVE + itkSetConstObjectMacro( FixedImageMask, FixedImageMaskType ); +#else + virtual void SetFixedImageMask( const FixedImageMaskType* mask ) + { this->SetFixedImageMask(const_cast<FixedImageMaskType*>(mask)); } +#endif itkGetConstObjectMacro( FixedImageMask, FixedImageMaskType ); /** Set/Get gradient computation. */ @@ -228,8 +243,13 @@ protected: bool m_ComputeGradient; GradientImagePointer m_GradientImage; +#ifdef ITK_LEGACY_REMOVE + FixedImageMaskConstPointer m_FixedImageMask; + MovingImageMaskConstPointer m_MovingImageMask; +#else mutable FixedImageMaskPointer m_FixedImageMask; mutable MovingImageMaskPointer m_MovingImageMask; +#endif private: ImageToImageMetric(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Code/Algorithms/itkLevelSetMotionRegistrationFilter.h b/Utilities/ITK/Code/Algorithms/itkLevelSetMotionRegistrationFilter.h index e46390c8883622c2ff9201a02c0df584296ed454..a8cd42d65661520de6f385d7e4878f04965e5251 100644 --- a/Utilities/ITK/Code/Algorithms/itkLevelSetMotionRegistrationFilter.h +++ b/Utilities/ITK/Code/Algorithms/itkLevelSetMotionRegistrationFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLevelSetMotionRegistrationFilter.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:02:58 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-06-14 12:30:08 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -77,7 +77,7 @@ namespace itk { * \warning This filter assumes that the fixed image type, moving image type * and deformation field type all have the same number of dimensions. * - * \cite B.C. Vemuri, J. Ye, Y. Chen, C.M. Leonard. "Image + * Ref: B.C. Vemuri, J. Ye, Y. Chen, C.M. Leonard. "Image * registration via level-set motion: applications to atlas-based * segmentation". Medical Image Analysis. Vol. 7. pp. 1-20. 2003. * diff --git a/Utilities/ITK/Code/Algorithms/itkMRFImageFilter.txx b/Utilities/ITK/Code/Algorithms/itkMRFImageFilter.txx index 458427397dabee8bc47353aaf5dca540ec525323..6455035abbb66fd6d999a4bb1fe3c121ab8773e3 100644 --- a/Utilities/ITK/Code/Algorithms/itkMRFImageFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkMRFImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMRFImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-05-26 23:45:01 $ - Version: $Revision: 1.67 $ + Date: $Date: 2009-06-16 07:58:47 $ + Version: $Revision: 1.68 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -456,15 +456,9 @@ MRFImageFilter<TInputImage, TClassifiedImage> totalNumberOfPixelsInInputImage *= static_cast<int>(inputImageSize[ i ]); } -#ifdef ITK_USE_PORTABLE_ROUND int maxNumPixelError = static_cast<int>( Math::Round( m_ErrorTolerance * m_TotalNumberOfValidPixelsInOutputImage) ); -#else - int maxNumPixelError = - static_cast<int> ( vnl_math_rnd (m_ErrorTolerance * - m_TotalNumberOfValidPixelsInOutputImage) ); -#endif m_NumberOfIterations = 0; do diff --git a/Utilities/ITK/Code/Algorithms/itkMattesMutualInformationImageToImageMetric.txx b/Utilities/ITK/Code/Algorithms/itkMattesMutualInformationImageToImageMetric.txx index 90f9cb0b888166148f9ad731819c1735d469ec8a..86b9ecac48fd348e72adf938db3a2027a4545a3e 100644 --- a/Utilities/ITK/Code/Algorithms/itkMattesMutualInformationImageToImageMetric.txx +++ b/Utilities/ITK/Code/Algorithms/itkMattesMutualInformationImageToImageMetric.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMattesMutualInformationImageToImageMetric.txx,v $ Language: C++ - Date: $Date: 2009-01-24 20:02:59 $ - Version: $Revision: 1.61 $ + Date: $Date: 2009-08-25 11:48:26 $ + Version: $Revision: 1.63 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -732,7 +732,7 @@ MattesMutualInformationImageToImageMetric<TFixedImage,TMovingImage> sampleOk, movingImageValue ); ++nFixedImageSamples; - + if( sampleOk ) { @@ -807,17 +807,19 @@ MattesMutualInformationImageToImageMetric<TFixedImage,TMovingImage> } //end if-block check sampleOk } // end iterating over fixed image spatial sample container for loop - itkDebugMacro( "Ratio of voxels mapping into moving image buffer: " - << nSamples << " / " << m_NumberOfSpatialSamples + itkDebugMacro( "Ratio of voxels mapping into moving image buffer: " + << nSamples << " / " << m_NumberOfSpatialSamples << std::endl ); - if( nSamples < m_NumberOfSpatialSamples / 4 ) + if( nSamples < m_NumberOfSpatialSamples / 16 ) { itkExceptionMacro( "Too many samples map outside moving image buffer: " << nSamples << " / " << m_NumberOfSpatialSamples << std::endl ); } + this->m_NumberOfPixelsCounted = nSamples; + /** * Normalize the PDFs, compute moving image marginal PDF @@ -1003,9 +1005,10 @@ MattesMutualInformationImageToImageMetric<TFixedImage,TMovingImage> bool sampleOk; double movingImageValue; + this->TransformPoint( nFixedImageSamples, parameters, mappedPoint, sampleOk, movingImageValue ); - + if( sampleOk ) { ++nSamples; @@ -1103,7 +1106,7 @@ MattesMutualInformationImageToImageMetric<TFixedImage,TMovingImage> << nSamples << " / " << m_NumberOfSpatialSamples << std::endl ); - if( nSamples < m_NumberOfSpatialSamples / 4 ) + if( nSamples < m_NumberOfSpatialSamples / 16 ) { itkExceptionMacro( "Too many samples map outside moving image buffer: " << nSamples << " / " << m_NumberOfSpatialSamples diff --git a/Utilities/ITK/Code/Algorithms/itkMeanSquaresImageToImageMetric.h b/Utilities/ITK/Code/Algorithms/itkMeanSquaresImageToImageMetric.h index 1f230750504d5e8adc3b5d37f9a15a67730b40b4..2f70f3278841cc6d0e601217173f95f362bc93db 100644 --- a/Utilities/ITK/Code/Algorithms/itkMeanSquaresImageToImageMetric.h +++ b/Utilities/ITK/Code/Algorithms/itkMeanSquaresImageToImageMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMeanSquaresImageToImageMetric.h,v $ Language: C++ - Date: $Date: 2009-01-24 20:03:00 $ - Version: $Revision: 1.32 $ + Date: $Date: 2009-07-15 08:45:50 $ + Version: $Revision: 1.33 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -39,7 +39,7 @@ namespace itk * This Class is templated over the type of the fixed and moving * images to be compared. * - * This metric computes the sum of squared differences between pixels in + * This metric computes the mean of squared differences between pixels in * the moving image and pixels in the fixed image. The spatial correspondance * between both images is established through a Transform. Pixel values are * taken from the Moving image. Their positions are mapped to the Fixed image diff --git a/Utilities/ITK/Code/Algorithms/itkMinMaxCurvatureFlowFunction.txx b/Utilities/ITK/Code/Algorithms/itkMinMaxCurvatureFlowFunction.txx index 93aff70780445d7b414635b64a432cde66da0951..24c567842295c18a0737eb2631318a00a5f6e62a 100644 --- a/Utilities/ITK/Code/Algorithms/itkMinMaxCurvatureFlowFunction.txx +++ b/Utilities/ITK/Code/Algorithms/itkMinMaxCurvatureFlowFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMinMaxCurvatureFlowFunction.txx,v $ Language: C++ - Date: $Date: 2009-05-26 23:45:03 $ - Version: $Revision: 1.28 $ + Date: $Date: 2009-06-16 07:58:47 $ + Version: $Revision: 1.29 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -285,25 +285,15 @@ MinMaxCurvatureFlowFunction<TImage> // Compute first perpendicular point -#ifdef ITK_USE_PORTABLE_ROUND position[0] = Math::Round( (double)(m_StencilRadius - gradient[1]) ); position[1] = Math::Round( (double)(m_StencilRadius + gradient[0]) ); -#else - position[0] = vnl_math_rnd( (double)(m_StencilRadius - gradient[1]) ); - position[1] = vnl_math_rnd( (double)(m_StencilRadius + gradient[0]) ); -#endif threshold = it.GetPixel( position[0] + stride * position[1] ); - // Compute second perpendicular point -#ifdef ITK_USE_PORTABLE_ROUND + // Compute second perpendicular point position[0] = Math::Round( (double)(m_StencilRadius + gradient[1]) ); position[1] = Math::Round( (double)(m_StencilRadius - gradient[0]) ); -#else - position[0] = vnl_math_rnd( (double)(m_StencilRadius + gradient[1]) ); - position[1] = vnl_math_rnd( (double)(m_StencilRadius - gradient[0]) ); -#endif threshold += it.GetPixel( position[0] + stride * position[1] ); @@ -403,54 +393,32 @@ MinMaxCurvatureFlowFunction<TImage> double rCosPhi = m_StencilRadius * cosPhi; // Point 1: angle = 0; -#ifdef ITK_USE_PORTABLE_ROUND position[0] = Math::Round( m_StencilRadius + rCosThetaCosPhi ); position[1] = Math::Round( m_StencilRadius + rCosThetaSinPhi ); position[2] = Math::Round( m_StencilRadius - rSinTheta ); -#else - position[0] = vnl_math_rnd( m_StencilRadius + rCosThetaCosPhi ); - position[1] = vnl_math_rnd( m_StencilRadius + rCosThetaSinPhi ); - position[2] = vnl_math_rnd( m_StencilRadius - rSinTheta ); -#endif threshold += it.GetPixel( position[0] + strideY * position[1] + strideZ * position[2] ); // Point 2: angle = 90; -#ifdef ITK_USE_PORTABLE_ROUND position[0] = Math::Round( m_StencilRadius - rSinPhi ); position[1] = Math::Round( m_StencilRadius + rCosPhi ); -#else - position[0] = vnl_math_rnd( m_StencilRadius - rSinPhi ); - position[1] = vnl_math_rnd( m_StencilRadius + rCosPhi ); -#endif position[2] = m_StencilRadius; threshold += it.GetPixel( position[0] + strideY * position[1] + strideZ * position[2] ); // Point 3: angle = 180; -#ifdef ITK_USE_PORTABLE_ROUND position[0] = Math::Round( m_StencilRadius - rCosThetaCosPhi ); position[1] = Math::Round( m_StencilRadius - rCosThetaSinPhi ); position[2] = Math::Round( m_StencilRadius + rSinTheta ); -#else - position[0] = vnl_math_rnd( m_StencilRadius - rCosThetaCosPhi ); - position[1] = vnl_math_rnd( m_StencilRadius - rCosThetaSinPhi ); - position[2] = vnl_math_rnd( m_StencilRadius + rSinTheta ); -#endif threshold += it.GetPixel( position[0] + strideY * position[1] + strideZ * position[2] ); // Point 4: angle = 270; -#ifdef ITK_USE_PORTABLE_ROUND position[0] = Math::Round( m_StencilRadius + rSinPhi ); position[1] = Math::Round( m_StencilRadius - rCosPhi ); -#else - position[0] = vnl_math_rnd( m_StencilRadius + rSinPhi ); - position[1] = vnl_math_rnd( m_StencilRadius - rCosPhi ); -#endif position[2] = m_StencilRadius; threshold += it.GetPixel( position[0] + diff --git a/Utilities/ITK/Code/Algorithms/itkMultiResolutionPyramidImageFilter.txx b/Utilities/ITK/Code/Algorithms/itkMultiResolutionPyramidImageFilter.txx index 16f4e812b6e8baba0bed5e0e011f7b9dd5c8dfea..a976609cc172963360cb3512587fdcda2ebd0790 100644 --- a/Utilities/ITK/Code/Algorithms/itkMultiResolutionPyramidImageFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkMultiResolutionPyramidImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultiResolutionPyramidImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-04-07 13:14:19 $ - Version: $Revision: 1.32 $ + Date: $Date: 2009-07-12 10:52:50 $ + Version: $Revision: 1.33 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -590,7 +590,9 @@ MultiResolutionPyramidImageFilter<TInputImage, TOutputImage> typedef GaussianOperator<OutputPixelType,ImageDimension> OperatorType; OperatorType *oper = new OperatorType; - unsigned long radius[ImageDimension]; + + typename TInputImage::SizeType radius; + RegionType inputRequestedRegion = baseRegion; refLevel = 0; diff --git a/Utilities/ITK/Code/Algorithms/itkRGBGibbsPriorFilter.txx b/Utilities/ITK/Code/Algorithms/itkRGBGibbsPriorFilter.txx index 8563566ba91a2faf76bc93476768a2472584f887..37250b676cef3ccf3a5238361b9d70f6bb31364d 100644 --- a/Utilities/ITK/Code/Algorithms/itkRGBGibbsPriorFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkRGBGibbsPriorFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRGBGibbsPriorFilter.txx,v $ Language: C++ - Date: $Date: 2009-04-06 11:15:07 $ - Version: $Revision: 1.49 $ + Date: $Date: 2009-06-19 12:13:12 $ + Version: $Revision: 1.50 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -140,6 +140,7 @@ RGBGibbsPriorFilter<TInputImage, TClassifiedImage> int numx; LabelType origin; LabelType neighbors[4]; + neighbors[0] = neighbors[1] = neighbors[2] = neighbors[3] = 0; for (unsigned int rgb = 0; rgb < m_VecDim; rgb++) { diff --git a/Utilities/ITK/Code/Algorithms/itkRecursiveMultiResolutionPyramidImageFilter.txx b/Utilities/ITK/Code/Algorithms/itkRecursiveMultiResolutionPyramidImageFilter.txx index dffa835c57f514afe8d6772b2f1c578a8511b246..b313d1cac457691f49bd0db919ba36ba801850ea 100644 --- a/Utilities/ITK/Code/Algorithms/itkRecursiveMultiResolutionPyramidImageFilter.txx +++ b/Utilities/ITK/Code/Algorithms/itkRecursiveMultiResolutionPyramidImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRecursiveMultiResolutionPyramidImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-04-10 19:14:50 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-07-12 10:52:51 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -285,7 +285,9 @@ RecursiveMultiResolutionPyramidImageFilter<TInputImage, TOutputImage> int ilevel, idim; unsigned int factors[ImageDimension]; - unsigned long radius[ImageDimension]; + + typename TInputImage::SizeType radius; + RegionType requestedRegion; SizeType requestedSize; IndexType requestedIndex; @@ -438,7 +440,9 @@ RecursiveMultiResolutionPyramidImageFilter<TInputImage, TOutputImage> typedef GaussianOperator<OutputPixelType,ImageDimension> OperatorType; OperatorType *oper = new OperatorType; - unsigned long radius[ImageDimension]; + + typename TInputImage::SizeType radius; + RegionType inputRequestedRegion = baseRegion; refLevel = 0; diff --git a/Utilities/ITK/Code/Algorithms/itkSimplexMeshVolumeCalculator.h b/Utilities/ITK/Code/Algorithms/itkSimplexMeshVolumeCalculator.h index 0533a0089789cf82737eecb53dc9d16aad97fff9..b2d264219ef2a6794efdfcd13486bb8b0fc9b9e7 100755 --- a/Utilities/ITK/Code/Algorithms/itkSimplexMeshVolumeCalculator.h +++ b/Utilities/ITK/Code/Algorithms/itkSimplexMeshVolumeCalculator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimplexMeshVolumeCalculator.h,v $ Language: C++ -Date: $Date: 2009-04-23 03:53:37 $ -Version: $Revision: 1.5 $ +Date: $Date: 2009-06-10 12:07:17 $ +Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -123,6 +123,7 @@ public: PointIdIterator it = poly->PointIdsBegin(); InputPointType center,p; center.Fill(0); + p.Fill(0.0); while ( it != poly->PointIdsEnd() ) { diff --git a/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationImageFilterBase.h b/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationImageFilterBase.h index cdddf9511ded386bd58ff23241ae170e5b38eabe..b91248636d8f39fd462f12bc3f9504246b95acc9 100644 --- a/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationImageFilterBase.h +++ b/Utilities/ITK/Code/Algorithms/itkVoronoiSegmentationImageFilterBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVoronoiSegmentationImageFilterBase.h,v $ Language: C++ - Date: $Date: 2009-04-23 03:53:37 $ - Version: $Revision: 1.30 $ + Date: $Date: 2009-06-16 14:57:53 $ + Version: $Revision: 1.31 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -169,6 +169,7 @@ public: VoronoiPointer GetVoronoiDiagram(void) { return m_WorkingVD; } +#if !defined(CABLE_CONFIGURATION) // generates invalid iterator instantiation with msvc /** Seeds positions are randomly set. * If you need to set seeds position then use the SetSeeds method * after the InitializeSegment method . */ @@ -177,6 +178,17 @@ public: m_NumberOfSeeds = num; m_WorkingVD->SetSeeds(num,begin); } +#endif + + /** Seeds positions are randomly set. + * If you need to set seeds position then use the SetSeeds method + * after the InitializeSegment method . */ + void SetSeeds(SeedsType & seeds) + { + m_NumberOfSeeds = seeds.size(); + typename SeedsType::iterator it = seeds.begin(); + m_WorkingVD->SetSeeds(m_NumberOfSeeds, it); + } /** Get the point specified by the ID given. */ PointType GetSeed(int SeedID) diff --git a/Utilities/ITK/Code/BasicFilters/itkAnisotropicDiffusionImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkAnisotropicDiffusionImageFilter.txx index 985353746fe36b305e9ba986d84addd640b2e34c..b57ca57822bc68cb43bea43ba9c0d65c6c93fa26 100644 --- a/Utilities/ITK/Code/BasicFilters/itkAnisotropicDiffusionImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkAnisotropicDiffusionImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAnisotropicDiffusionImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-07 14:49:30 $ - Version: $Revision: 1.29 $ + Date: $Date: 2009-08-16 02:05:44 $ + Version: $Revision: 1.30 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -77,7 +77,7 @@ AnisotropicDiffusionImageFilter<TInputImage, TOutputImage> // f->SetTimeStep(1.0 / vcl_pow(2.0, static_cast<double>(ImageDimension))); itkWarningMacro( << "Anisotropic diffusion unstable time step: " << m_TimeStep << std::endl - << "Minimum stable time step for this image is " + << "Stable time step for this image must be smaller than " << minSpacing / vcl_pow(2.0, static_cast<double>(ImageDimension+1))); } diff --git a/Utilities/ITK/Code/BasicFilters/itkBilateralImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkBilateralImageFilter.txx index 29959bc3c85f7088052e0680351b549d2129758c..7c2b7009b8831b0d421a1a707ecfecff30fb00e9 100644 --- a/Utilities/ITK/Code/BasicFilters/itkBilateralImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkBilateralImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBilateralImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-07 17:31:02 $ - Version: $Revision: 1.29 $ + Date: $Date: 2009-08-07 15:27:48 $ + Version: $Revision: 1.32 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,28 +26,6 @@ #include "itkStatisticsImageFilter.h" -// anonymous namespace -namespace -{ -//-------------------------------------------------------------------------- -// The 'floor' function on x86 and mips is many times slower than these -// and is used a lot in this code, optimize for different CPU architectures -inline int BilateralFloor(double x) -{ -#if defined mips || defined sparc || defined __ppc__ - return (int)((unsigned int)(x + 2147483648.0) - 2147483648U); -#elif defined i386 || defined _M_IX86 - union { unsigned int hilo[2]; double d; } u; - u.d = x + 103079215104.0; - return (int)((u.hilo[1]<<16)|(u.hilo[0]>>16)); -#else - return int(floor(x)); -#endif -} - -} - - namespace itk { template< class TInputImage, class TOutputImage > @@ -169,7 +147,7 @@ BilateralImageFilter<TInputImage, TOutputImage> typename GaussianImageSource<GaussianImageType>::ArrayType sigma; gaussianImage = GaussianImageSource<GaussianImageType>::New(); - gaussianImage->SetSize(domainKernelSize.GetSize()); + gaussianImage->SetSize( domainKernelSize.GetSize() ); gaussianImage->SetSpacing( inputSpacing ); gaussianImage->SetOrigin( inputOrigin ); gaussianImage->SetScale( 1.0 ); @@ -225,7 +203,7 @@ BilateralImageFilter<TInputImage, TOutputImage> // denominator (normalization factor) for Gaussian used for range double rangeGaussianDenom; - rangeGaussianDenom = m_RangeSigma*vcl_sqrt(2.0*3.1415927); + rangeGaussianDenom = m_RangeSigma*vcl_sqrt(2.0*vnl_math::pi); // Maximum delta for the dynamic range double tableDelta; @@ -327,7 +305,7 @@ BilateralImageFilter<TInputImage, TOutputImage> { // look up the range gaussian in a table tableArg = rangeDistance * distanceToTableIndex; - rangeGaussian = m_RangeGaussianTable[BilateralFloor(tableArg)]; + rangeGaussian = m_RangeGaussianTable[Math::Floor(tableArg)]; // normalization factor so filter integrates to one // (product of the domain and the range gaussian) diff --git a/Utilities/ITK/Code/BasicFilters/itkCannyEdgeDetectionImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkCannyEdgeDetectionImageFilter.txx index 700d86e5c474d3404584dde1a9249273fdb54df7..46af4f7a1fab7dba0e559b66fa852415fd223962 100644 --- a/Utilities/ITK/Code/BasicFilters/itkCannyEdgeDetectionImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkCannyEdgeDetectionImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCannyEdgeDetectionImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-04-08 16:31:08 $ - Version: $Revision: 1.54 $ + Date: $Date: 2009-08-17 12:01:33 $ + Version: $Revision: 1.56 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -116,7 +116,7 @@ CannyEdgeDetectionImageFilter<TInputImage,TOutputImage> //Set the kernel size. // fix me this needs to be based on the variance of the gaussian filter - unsigned long radius = 1; + typename TInputImage::SizeValueType radius = 1; // get a copy of the input requested region (should equal the output // requested region) @@ -333,6 +333,8 @@ CannyEdgeDetectionImageFilter< TInputImage, TOutputImage > m_GaussianFilter->SetVariance(m_Variance); m_GaussianFilter->SetMaximumError(m_MaximumError); m_GaussianFilter->SetInput(input); + // modify to force excution, due to grafting complications + m_GaussianFilter->Modified(); m_GaussianFilter->Update(); //2. Calculate 2nd order directional derivative------- @@ -342,7 +344,8 @@ CannyEdgeDetectionImageFilter< TInputImage, TOutputImage > this->Compute2ndDerivative(); this->Compute2ndDerivativePos(); - + + // 3. Non-maximum suppression---------- // Calculate the zero crossings of the 2nd directional derivative and write @@ -351,7 +354,7 @@ CannyEdgeDetectionImageFilter< TInputImage, TOutputImage > zeroCrossFilter->Update(); // 4. Hysteresis Thresholding--------- - + // First get all the edges corresponding to zerocrossings m_MultiplyImageFilter->SetInput1(m_UpdateBuffer1); m_MultiplyImageFilter->SetInput2(zeroCrossFilter->GetOutput()); @@ -388,7 +391,7 @@ CannyEdgeDetectionImageFilter< TInputImage, TOutputImage > uit.GoToBegin(); while(!uit.IsAtEnd()) { - uit.Value() = 0; + uit.Value() = NumericTraits<OutputImagePixelType>::Zero; ++uit; } @@ -433,8 +436,14 @@ CannyEdgeDetectionImageFilter< TInputImage, TOutputImage > this->GetOutput()->GetRequestedRegion()); uit.SetIndex(index); - if(uit.Get() == 1) + if(uit.Get() == NumericTraits<OutputImagePixelType>::One ) { + // we must remove the node if we are not going to follow it! + + // Pop the front node from the list and read its index value. + node = m_NodeList->Front(); // get a pointer to the first node + m_NodeList->PopFront(); // unlink the front node + m_NodeStore->Return(node); // return the memory for reuse return; } @@ -459,14 +468,14 @@ CannyEdgeDetectionImageFilter< TInputImage, TOutputImage > uit.SetIndex(nIndex); if(inputRegion.IsInside(nIndex)) { - if(oit.GetPixel(i) > m_LowerThreshold && uit.Value() != 1 ) + if(oit.GetPixel(i) > m_LowerThreshold && uit.Value() != NumericTraits<OutputImagePixelType>::One ) { node = m_NodeStore->Borrow(); // get a new node struct node->m_Value = nIndex; // set its value m_NodeList->PushFront(node); // add the new node to the list uit.SetIndex(nIndex); - uit.Value() = 1; + uit.Value() = NumericTraits<OutputImagePixelType>::One; } } } diff --git a/Utilities/ITK/Code/BasicFilters/itkConnectedComponentImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkConnectedComponentImageFilter.h index 6afa9ff67be0e4570438f13b52bc2961abb94a11..06abdf794bbf4a13c3f3ae672edf4bec3335ebbb 100644 --- a/Utilities/ITK/Code/BasicFilters/itkConnectedComponentImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkConnectedComponentImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkConnectedComponentImageFilter.h,v $ Language: C++ - Date: $Date: 2009-04-27 22:58:48 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-06-26 16:37:45 $ + Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -137,7 +137,7 @@ public: itkConceptMacro(SameDimension, (Concept::SameDimension<itkGetStaticConstMacro(InputImageDimension), itkGetStaticConstMacro(OutputImageDimension)>)); - + itkConceptMacro(OutputImagePixelTypeIsInteger, (Concept::IsInteger<OutputImagePixelType>)); void SetMaskImage(TMaskImage* mask) { diff --git a/Utilities/ITK/Code/BasicFilters/itkConnectedThresholdImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkConnectedThresholdImageFilter.h index e4b5eef860e3685fbe92cd9801ac652faf7143cf..ddde4ed6adecf5cd57da5ca914673d2087c8fafa 100644 --- a/Utilities/ITK/Code/BasicFilters/itkConnectedThresholdImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkConnectedThresholdImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkConnectedThresholdImageFilter.h,v $ Language: C++ - Date: $Date: 2009-04-25 12:27:20 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-06-05 16:06:22 $ + Version: $Revision: 1.22 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -129,8 +129,8 @@ public: #ifdef ITK_USE_REVIEW /** Type of connectivity to use (fully connected OR 4(2D), 6(3D), * 2*N(ND) connectivity) */ - itkSetMacro( Connectivity, ConnectivityEnumType ); - itkGetConstMacro( Connectivity, ConnectivityEnumType ); + itkSetEnumMacro( Connectivity, ConnectivityEnumType ); + itkGetEnumMacro( Connectivity, ConnectivityEnumType ); #endif protected: diff --git a/Utilities/ITK/Code/BasicFilters/itkDiscreteGaussianImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkDiscreteGaussianImageFilter.txx index f7cea0d3c3a13545eef48e1abbeb5c6697d89898..354c715b62d75a6aa5b4879f27cb96d477ae9003 100644 --- a/Utilities/ITK/Code/BasicFilters/itkDiscreteGaussianImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkDiscreteGaussianImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDiscreteGaussianImageFilter.txx,v $ Language: C++ -Date: $Date: 2008-12-10 01:58:48 $ -Version: $Revision: 1.42 $ +Date: $Date: 2009-07-29 12:44:26 $ +Version: $Revision: 1.43 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,6 +17,7 @@ PURPOSE. See the above copyright notices for more information. #ifndef __itkDiscreteGaussianImageFilter_txx #define __itkDiscreteGaussianImageFilter_txx +#include "itkDiscreteGaussianImageFilter.h" #include "itkNeighborhoodOperatorImageFilter.h" #include "itkGaussianOperator.h" #include "itkImageRegionIterator.h" diff --git a/Utilities/ITK/Code/BasicFilters/itkGaussianImageSource.h b/Utilities/ITK/Code/BasicFilters/itkGaussianImageSource.h index fe316a12595837c95efddb885414162ec9d31a98..eeab4e07116eae0c288df78a9622ec29feb6e781 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGaussianImageSource.h +++ b/Utilities/ITK/Code/BasicFilters/itkGaussianImageSource.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianImageSource.h,v $ Language: C++ - Date: $Date: 2009-05-12 17:22:43 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-07-12 10:52:52 $ + Version: $Revision: 1.20 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -74,7 +74,8 @@ public: typedef FixedArray<double, itkGetStaticConstMacro(NDimensions)> ArrayType; /** Size type matches that used for images */ - typedef Size<itkGetStaticConstMacro(NDimensions)> SizeType; + typedef typename TOutputImage::SizeType SizeType; + typedef typename TOutputImage::SizeValueType SizeValueType; /** Run-time type information (and related methods). */ itkTypeMacro(GaussianImageSource,ImageSource); @@ -83,13 +84,13 @@ public: itkNewMacro(Self); /** Specify the size of the output image. */ - virtual void SetSize( const unsigned long* values); + virtual void SetSize( const SizeValueType * values); /** Specify the size of the output image. */ virtual void SetSize( const SizeType values); /** Get the size of the output image. */ - itkGetVectorMacro(Size,const unsigned long,NDimensions); + itkGetVectorMacro(Size,const SizeValueType,NDimensions); /** Specify the spacing of the output image. */ itkSetMacro(Spacing, SpacingType); @@ -133,7 +134,7 @@ private: GaussianImageSource(const GaussianImageSource&); //purposely not implemented void operator=(const GaussianImageSource&); //purposely not implemented - unsigned long m_Size[NDimensions]; //size of the output image + SizeValueType m_Size[NDimensions]; //size of the output image SpacingType m_Spacing; //spacing PointType m_Origin; //origin DirectionType m_Direction; // direction diff --git a/Utilities/ITK/Code/BasicFilters/itkGaussianImageSource.txx b/Utilities/ITK/Code/BasicFilters/itkGaussianImageSource.txx index eeec7abd25cad657a34b9690ff0f933320192224..182e2997d01f0c8f7b40c1af00b9f4587d975191 100644 --- a/Utilities/ITK/Code/BasicFilters/itkGaussianImageSource.txx +++ b/Utilities/ITK/Code/BasicFilters/itkGaussianImageSource.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianImageSource.txx,v $ Language: C++ - Date: $Date: 2008-12-17 18:56:53 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-07-12 10:52:52 $ + Version: $Revision: 1.20 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -266,7 +266,7 @@ GaussianImageSource<TOutputImage> template<typename TOutputImage> void GaussianImageSource<TOutputImage> -::SetSize(const unsigned long* size) +::SetSize(const SizeValueType * size) { unsigned int i; for (i=0; i<TOutputImage::ImageDimension; i++) diff --git a/Utilities/ITK/Code/BasicFilters/itkHMaximaImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkHMaximaImageFilter.txx index 024507a0cdd044dee6c5111da3da961f2e496672..b1bd1a508a526870bcffe800552ecd14de6c2cd9 100644 --- a/Utilities/ITK/Code/BasicFilters/itkHMaximaImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkHMaximaImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHMaximaImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:09 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-07-26 12:50:31 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -20,8 +20,8 @@ #include "itkImageRegionIterator.h" #include "itkImageRegionConstIterator.h" #include "itkHMaximaImageFilter.h" -//#include "itkGrayscaleGeodesicDilateImageFilter.h" #include "itkShiftScaleImageFilter.h" +#include "itkCastImageFilter.h" #include "itkProgressAccumulator.h" #include "itkReconstructionByDilationImageFilter.h" @@ -97,17 +97,23 @@ HMaximaImageFilter<TInputImage, TOutputImage> dilate->SetMaskImage( this->GetInput() ); dilate->SetFullyConnected( m_FullyConnected ); - // graft our output to the dilate filter to force the proper regions + // Must cast to the output type + typename CastImageFilter<TInputImage, TOutputImage>::Pointer cast + = CastImageFilter<TInputImage, TOutputImage>::New(); + cast->SetInput( dilate->GetOutput() ); + cast->InPlaceOn(); + + // graft our output to the cast filter to force the proper regions // to be generated - dilate->GraftOutput( this->GetOutput() ); + cast->GraftOutput( this->GetOutput() ); // reconstruction by dilation - dilate->Update(); + cast->Update(); // graft the output of the dilate filter back onto this filter's // output. this is needed to get the appropriate regions passed // back. - this->GraftOutput( dilate->GetOutput() ); + this->GraftOutput( cast->GetOutput() ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkHMinimaImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkHMinimaImageFilter.txx index de9693dfb6bf97f80f014a94650c201abb20068e..3c860ac44076421c5d5e1addbbbc7705957b36ad 100644 --- a/Utilities/ITK/Code/BasicFilters/itkHMinimaImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkHMinimaImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHMinimaImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-16 16:45:09 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-07-26 12:50:33 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,6 +22,7 @@ #include "itkHMinimaImageFilter.h" #include "itkReconstructionByErosionImageFilter.h" #include "itkShiftScaleImageFilter.h" +#include "itkCastImageFilter.h" #include "itkProgressAccumulator.h" namespace itk { @@ -96,17 +97,23 @@ HMinimaImageFilter<TInputImage, TOutputImage> erode->SetMaskImage( this->GetInput() ); erode->SetFullyConnected( m_FullyConnected ); - // graft our output to the erode filter to force the proper regions + // Must cast to the output type + typename CastImageFilter<TInputImage, TOutputImage>::Pointer cast + = CastImageFilter<TInputImage, TOutputImage>::New(); + cast->SetInput( erode->GetOutput() ); + cast->InPlaceOn(); + + // graft our output to the cast filter to force the proper regions // to be generated - erode->GraftOutput( this->GetOutput() ); + cast->GraftOutput( this->GetOutput() ); // reconstruction by erosion - erode->Update(); + cast->Update(); // graft the output of the erode filter back onto this filter's // output. this is needed to get the appropriate regions passed // back. - this->GraftOutput( erode->GetOutput() ); + this->GraftOutput( cast->GetOutput() ); } diff --git a/Utilities/ITK/Code/BasicFilters/itkNarrowBand.h b/Utilities/ITK/Code/BasicFilters/itkNarrowBand.h index ea9fc68c57af0c455b44ec7250d395b7c22bb2cd..8e38473301e4bf1fbf2cd83aac922c7e1db40fda 100644 --- a/Utilities/ITK/Code/BasicFilters/itkNarrowBand.h +++ b/Utilities/ITK/Code/BasicFilters/itkNarrowBand.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNarrowBand.h,v $ Language: C++ - Date: $Date: 2008-10-16 19:33:41 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-06-19 19:47:57 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -72,7 +72,7 @@ public: /** Returns an array of RegionStructs which represent contiguous * arrays of nodes within the narrow band. */ #if !defined(CABLE_CONFIGURATION) - std::vector<struct RegionStruct> SplitBand( unsigned int ); + std::vector<RegionType> SplitBand( unsigned int ); #endif Iterator Begin() diff --git a/Utilities/ITK/Code/BasicFilters/itkNarrowBand.txx b/Utilities/ITK/Code/BasicFilters/itkNarrowBand.txx index c3d4390ef582d220580e9471a44c44e4203d9931..c3557b3fe62f518df53d91659e5e9799471c9f7c 100644 --- a/Utilities/ITK/Code/BasicFilters/itkNarrowBand.txx +++ b/Utilities/ITK/Code/BasicFilters/itkNarrowBand.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNarrowBand.txx,v $ Language: C++ - Date: $Date: 2009-04-06 13:59:00 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-06-19 19:46:56 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,14 +26,6 @@ namespace itk { -//template <class NodeType> -//void -//NarrowBand<NodeType> -//::PrintSelf(std::ostream& os, Indent indent) const -//{ -// Superclass::PrintSelf(os, indent); -//} - #if !defined(CABLE_CONFIGURATION) template <class NodeType > std::vector< ITK_TYPENAME NarrowBand<NodeType>::RegionType> diff --git a/Utilities/ITK/Code/BasicFilters/itkPadImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkPadImageFilter.h index d9f6b44db3297d4360b853f06b6351848382ab1b..6b631f900f5ed5dc69dce127e86811ee3e43b657 100644 --- a/Utilities/ITK/Code/BasicFilters/itkPadImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkPadImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPadImageFilter.h,v $ Language: C++ - Date: $Date: 2008-10-17 16:30:46 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-07-12 10:52:52 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -61,10 +61,11 @@ public: typedef typename TInputImage::PixelType InputImagePixelType; /** Typedef to describe the output and input image index and size types. */ - typedef typename TOutputImage::IndexType OutputImageIndexType; - typedef typename TInputImage::IndexType InputImageIndexType; - typedef typename TOutputImage::SizeType OutputImageSizeType; - typedef typename TInputImage::SizeType InputImageSizeType; + typedef typename TOutputImage::IndexType OutputImageIndexType; + typedef typename TInputImage::IndexType InputImageIndexType; + typedef typename TOutputImage::SizeType OutputImageSizeType; + typedef typename TInputImage::SizeType InputImageSizeType; + typedef typename TInputImage::SizeValueType SizeValueType; /** Run-time type information (and related methods). */ itkTypeMacro(PadImageFilter, ImageToImageFilter); @@ -75,10 +76,10 @@ public: /** Set/Get the output image padding. Default is no padding * (same as input). */ - itkSetVectorMacro(PadLowerBound, const unsigned long, ImageDimension); - itkSetVectorMacro(PadUpperBound, const unsigned long, ImageDimension); - itkGetVectorMacro(PadLowerBound, const unsigned long, ImageDimension); - itkGetVectorMacro(PadUpperBound, const unsigned long, ImageDimension); + itkSetVectorMacro(PadLowerBound, const SizeValueType, ImageDimension); + itkSetVectorMacro(PadUpperBound, const SizeValueType, ImageDimension); + itkGetVectorMacro(PadLowerBound, const SizeValueType, ImageDimension); + itkGetVectorMacro(PadUpperBound, const SizeValueType, ImageDimension); void SetPadLowerBound(const InputImageSizeType & bound) @@ -121,8 +122,8 @@ private: PadImageFilter(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented - unsigned long m_PadLowerBound[ImageDimension]; - unsigned long m_PadUpperBound[ImageDimension]; + SizeValueType m_PadLowerBound[ImageDimension]; + SizeValueType m_PadUpperBound[ImageDimension]; }; diff --git a/Utilities/ITK/Code/BasicFilters/itkPasteImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkPasteImageFilter.h index 5a458809c3dd4632c36dc6f99ee879765aa33e24..9ef1ce340c4957be6b37ffe41fb332ab0dcdefa1 100644 --- a/Utilities/ITK/Code/BasicFilters/itkPasteImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkPasteImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPasteImageFilter.h,v $ Language: C++ - Date: $Date: 2009-04-25 12:27:48 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-07-14 11:49:10 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -60,34 +60,37 @@ public: typedef typename Superclass::InputImagePointer InputImagePointer; typedef typename Superclass::OutputImagePointer OutputImagePointer; - typedef typename TSourceImage::Pointer SourceImagePointer; - typedef typename TSourceImage::ConstPointer SourceImageConstPointer; - /** Typedef to describe the output and input image region types. */ - typedef typename TOutputImage::RegionType OutputImageRegionType; - typedef typename TInputImage::RegionType InputImageRegionType; - typedef typename TSourceImage::RegionType SourceImageRegionType; + typedef TInputImage InputImageType; + typedef TOutputImage OutputImageType; + typedef TSourceImage SourceImageType; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename SourceImageType::RegionType SourceImageRegionType; + + typedef typename SourceImageType::Pointer SourceImagePointer; + typedef typename SourceImageType::ConstPointer SourceImageConstPointer; /** Typedef to describe the type of pixel. */ - typedef typename TOutputImage::PixelType OutputImagePixelType; - typedef typename TInputImage::PixelType InputImagePixelType; - typedef typename TSourceImage::PixelType SourceImagePixelType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename SourceImageType::PixelType SourceImagePixelType; /** Typedef to describe the output and input image index and size types. */ - typedef typename TOutputImage::IndexType OutputImageIndexType; - typedef typename TOutputImage::SizeType OutputImageSizeType; - typedef typename TInputImage::IndexType InputImageIndexType; - typedef typename TInputImage::SizeType InputImageSizeType; - typedef typename TSourceImage::IndexType SourceImageIndexType; - typedef typename TSourceImage::SizeType SourceImageSizeType; + typedef typename OutputImageType::IndexType OutputImageIndexType; + typedef typename OutputImageType::SizeType OutputImageSizeType; + typedef typename InputImageType::IndexType InputImageIndexType; + typedef typename InputImageType::SizeType InputImageSizeType; + typedef typename SourceImageType::IndexType SourceImageIndexType; + typedef typename SourceImageType::SizeType SourceImageSizeType; /** ImageDimension enumeration */ itkStaticConstMacro(InputImageDimension, unsigned int, - TInputImage::ImageDimension); + InputImageType::ImageDimension); itkStaticConstMacro(OutputImageDimension, unsigned int, - TOutputImage::ImageDimension); + OutputImageType::ImageDimension); itkStaticConstMacro(SourceImageDimension, unsigned int, - TSourceImage::ImageDimension); + SourceImageType::ImageDimension); /** Set/Get the destination index (where in the first input the second * input will be pasted. */ @@ -101,13 +104,13 @@ public: /** Set/Get the "destination" image. This is the image that will be * obscured by the paste operation. */ - void SetDestinationImage(TInputImage *dest) { this->SetNthInput(0, dest); } - const TInputImage* GetDestinationImage() { return this->GetInput(0); } + void SetDestinationImage(const InputImageType *dest); + const InputImageType * GetDestinationImage() const; /** Set/Get the "source" image. This is the image that will be * pasted over the destination image. */ - void SetSourceImage(TSourceImage *src) { this->SetNthInput(1, src); } - const TSourceImage* GetSourceImage() { return this->GetInput(1); } + void SetSourceImage(const SourceImageType *src); + const SourceImageType * GetSourceImage() const; /** PasteImageFilter needs to set the input requested regions for its * inputs. The first input's requested region will be set to match diff --git a/Utilities/ITK/Code/BasicFilters/itkPasteImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkPasteImageFilter.txx index 2bdb7f258df62517947d248c07971ab19a620fe6..6aef9e423ac9eb6b55cfd265e970c94e72ec21ac 100644 --- a/Utilities/ITK/Code/BasicFilters/itkPasteImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkPasteImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPasteImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-17 16:30:48 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-07-14 11:49:10 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -40,6 +40,43 @@ PasteImageFilter<TInputImage,TSourceImage,TOutputImage> m_DestinationIndex.Fill(0); } +template <class TInputImage, class TSourceImage, class TOutputImage> +void +PasteImageFilter<TInputImage,TSourceImage,TOutputImage> +::SetSourceImage(const SourceImageType *src) +{ + // Process object is not const-correct so the const casting is required. + this->SetNthInput(1, const_cast<SourceImageType *>( src )); +} + +template <class TInputImage, class TSourceImage, class TOutputImage> +const typename PasteImageFilter<TInputImage,TSourceImage,TOutputImage>::SourceImageType * +PasteImageFilter<TInputImage,TSourceImage,TOutputImage> +::GetSourceImage() const +{ + const SourceImageType * sourceImage = + dynamic_cast< const SourceImageType * >( this->ProcessObject::GetInput(1) ); + return sourceImage; +} + +template <class TInputImage, class TSourceImage, class TOutputImage> +void +PasteImageFilter<TInputImage,TSourceImage,TOutputImage> +::SetDestinationImage(const InputImageType *src) +{ + // Process object is not const-correct so the const casting is required. + this->SetNthInput(0, const_cast<InputImageType *>( src )); +} + +template <class TInputImage, class TSourceImage, class TOutputImage> +const typename PasteImageFilter<TInputImage,TSourceImage,TOutputImage>::InputImageType * +PasteImageFilter<TInputImage,TSourceImage,TOutputImage> +::GetDestinationImage() const +{ + const InputImageType * destinationImage = + dynamic_cast< const InputImageType * >( this->ProcessObject::GetInput(0) ); + return destinationImage; +} /** * @@ -55,7 +92,6 @@ PasteImageFilter<TInputImage,TSourceImage,TOutputImage> os << indent << "SourceRegion: " << m_SourceRegion << std::endl; } - /** * */ @@ -68,10 +104,8 @@ PasteImageFilter<TInputImage,TSourceImage,TOutputImage> Superclass::GenerateInputRequestedRegion(); // get the pointers for the inputs and output - InputImagePointer destPtr = - const_cast< TInputImage * >( this->GetInput() ); - SourceImagePointer sourcePtr = - const_cast< TSourceImage * >( this->GetSourceImage() ); + InputImagePointer destPtr = const_cast< InputImageType * >( this->GetInput() ); + SourceImagePointer sourcePtr = const_cast< SourceImageType * >( this->GetSourceImage() ); OutputImagePointer outputPtr = this->GetOutput(); if( !destPtr || !sourcePtr || !outputPtr ) @@ -174,9 +208,9 @@ PasteImageFilter<TInputImage,TSourceImage,TOutputImage> // Define iterators types - typedef ImageRegionIterator<TOutputImage> OutputIterator; - typedef ImageRegionConstIterator<TInputImage> InputIterator; - typedef ImageRegionConstIterator<TSourceImage> SourceIterator; + typedef ImageRegionIterator<OutputImageType> OutputIterator; + typedef ImageRegionConstIterator<InputImageType> InputIterator; + typedef ImageRegionConstIterator<SourceImageType> SourceIterator; // There are three cases that we need to consider: // diff --git a/Utilities/ITK/Code/BasicFilters/itkRandomImageSource.h b/Utilities/ITK/Code/BasicFilters/itkRandomImageSource.h index 2aa41fe8c517c43ff09d659c7f928f613afe3a82..c4b6af860d17cf17f5158a2cbb3e6d46d48d2c2d 100644 --- a/Utilities/ITK/Code/BasicFilters/itkRandomImageSource.h +++ b/Utilities/ITK/Code/BasicFilters/itkRandomImageSource.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRandomImageSource.h,v $ Language: C++ - Date: $Date: 2009-04-25 12:27:55 $ - Version: $Revision: 1.43 $ + Date: $Date: 2009-07-12 10:45:28 $ + Version: $Revision: 1.44 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -60,23 +60,32 @@ public: /** Method for creation through the object factory. */ itkNewMacro(Self); - /** Specify the size of the output image. */ - itkSetVectorMacro(Size,unsigned long,TOutputImage::ImageDimension); - - /** Get the size of the output image. */ - itkGetVectorMacro(Size,unsigned long,TOutputImage::ImageDimension); - - /** Specify the spacing of the output image. */ - itkSetVectorMacro(Spacing,float,TOutputImage::ImageDimension); - - /** Get the spacing of the output image. */ - itkGetVectorMacro(Spacing,float,TOutputImage::ImageDimension); - - /** Specify the origin of the output image. */ - itkSetVectorMacro(Origin,float,TOutputImage::ImageDimension); - - /** Get the origin of the output image. */ - itkGetVectorMacro(Origin,float,TOutputImage::ImageDimension); + /** Basic types from the OutputImageType */ + typedef typename TOutputImage::SizeType SizeType; + typedef typename TOutputImage::IndexType IndexType; + typedef typename TOutputImage::SpacingType SpacingType; + typedef typename TOutputImage::PointType PointType; + typedef typename SizeType::SizeValueType SizeValueType; + typedef SizeValueType SizeValueArrayType[TOutputImage::ImageDimension]; + typedef typename TOutputImage::SpacingValueType SpacingValueType; + typedef SpacingValueType SpacingValueArrayType[TOutputImage::ImageDimension]; + typedef typename TOutputImage::PointValueType PointValueType; + typedef PointValueType PointValueArrayType[TOutputImage::ImageDimension]; + + /** Set/Get size of the output image */ + itkSetMacro( Size, SizeType ); + virtual void SetSize( SizeValueArrayType sizeArray ); + virtual const SizeValueType * GetSize() const; + + /** Set/Get spacing of the output image */ + itkSetMacro( Spacing, SpacingType ); + virtual void SetSpacing( SpacingValueArrayType spacingArray ); + virtual const SpacingValueType * GetSpacing() const; + + /** Set/Get origin of the output image */ + itkSetMacro( Origin, PointType ); + virtual void SetOrigin( PointValueArrayType originArray ); + virtual const PointValueType * GetOrigin() const; /** Set the minimum possible pixel value. By default, it is * NumericTraits<TOutputImage::PixelType>::min(). */ @@ -110,12 +119,18 @@ private: RandomImageSource(const RandomImageSource&); //purposely not implemented void operator=(const RandomImageSource&); //purposely not implemented - unsigned long *m_Size; //size of the output image - float *m_Spacing; //spacing - float *m_Origin; //origin + SizeType m_Size; //size of the output image + SpacingType m_Spacing; //spacing + PointType m_Origin; //origin typename TOutputImage::PixelType m_Min; //minimum possible value typename TOutputImage::PixelType m_Max; //maximum possible value + + // The following variables are deprecated, and provided here just for + // backward compatibility. It use is discouraged. + mutable PointValueArrayType m_OriginArray; + mutable SpacingValueArrayType m_SpacingArray; + }; } // end namespace itk diff --git a/Utilities/ITK/Code/BasicFilters/itkRandomImageSource.txx b/Utilities/ITK/Code/BasicFilters/itkRandomImageSource.txx index 2506c2aa515241c8a87f208a73b0d2b1d43a2370..dd5441240461eacc970e29179a041401f200307d 100644 --- a/Utilities/ITK/Code/BasicFilters/itkRandomImageSource.txx +++ b/Utilities/ITK/Code/BasicFilters/itkRandomImageSource.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRandomImageSource.txx,v $ Language: C++ - Date: $Date: 2008-01-04 20:22:11 $ - Version: $Revision: 1.55 $ + Date: $Date: 2009-07-12 10:45:29 $ + Version: $Revision: 1.56 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -36,9 +36,6 @@ template <class TOutputImage> RandomImageSource<TOutputImage> ::RandomImageSource() { - m_Size = new unsigned long [TOutputImage::GetImageDimension()]; - m_Spacing = new float [TOutputImage::GetImageDimension()]; - m_Origin = new float [TOutputImage::GetImageDimension()]; //Initial image is 64 wide in each direction. for (unsigned int i=0; i<TOutputImage::GetImageDimension(); i++) @@ -56,11 +53,114 @@ template <class TOutputImage> RandomImageSource<TOutputImage> ::~RandomImageSource() { - delete [] m_Size; - delete [] m_Spacing; - delete [] m_Origin; } +template <class TOutputImage> +void +RandomImageSource<TOutputImage> +::SetSize( SizeValueArrayType sizeArray ) +{ + const unsigned int count = TOutputImage::ImageDimension; + unsigned int i; + for( i=0; i<count; i++ ) + { + if( sizeArray[i] != this->m_Size[i] ) + { + break; + } + } + if( i < count ) + { + this->Modified(); + for( i=0; i<count; i++ ) + { + this->m_Size[i] = sizeArray[i]; + } + } +} + +template <class TOutputImage> +const typename RandomImageSource<TOutputImage>::SizeValueType * +RandomImageSource<TOutputImage> +::GetSize() const +{ + return this->m_Size.GetSize(); +} + +template <class TOutputImage> +void +RandomImageSource<TOutputImage> +::SetSpacing( SpacingValueArrayType spacingArray ) +{ + const unsigned int count = TOutputImage::ImageDimension; + unsigned int i; + for( i=0; i<count; i++ ) + { + if( spacingArray[i] != this->m_Spacing[i] ) + { + break; + } + } + if( i < count ) + { + this->Modified(); + for( i=0; i<count; i++ ) + { + this->m_Spacing[i] = spacingArray[i]; + } + } +} + +template <class TOutputImage> +void +RandomImageSource<TOutputImage> +::SetOrigin( PointValueArrayType originArray ) +{ + const unsigned int count = TOutputImage::ImageDimension; + unsigned int i; + for( i=0; i<count; i++ ) + { + if( originArray[i] != this->m_Origin[i] ) + { + break; + } + } + if( i < count ) + { + this->Modified(); + for( i=0; i<count; i++ ) + { + this->m_Origin[i] = originArray[i]; + } + } +} + +template <class TOutputImage> +const typename RandomImageSource<TOutputImage>::PointValueType * +RandomImageSource<TOutputImage> +::GetOrigin() const +{ + for(unsigned int i=0; i < TOutputImage::ImageDimension; i++ ) + { + this->m_OriginArray[i] = this->m_Origin[i]; + } + return this->m_OriginArray; +} + + +template <class TOutputImage> +const typename RandomImageSource<TOutputImage>::SpacingValueType * +RandomImageSource<TOutputImage> +::GetSpacing() const +{ + for(unsigned int i=0; i < TOutputImage::ImageDimension; i++ ) + { + this->m_SpacingArray[i] = this->m_Spacing[i]; + } + return this->m_SpacingArray; +} + + /** * */ @@ -106,14 +206,13 @@ RandomImageSource<TOutputImage> ::GenerateOutputInformation() { TOutputImage *output; - typename TOutputImage::IndexType index = {{0}}; - typename TOutputImage::SizeType size = {{0}}; - size.SetSize( m_Size ); + IndexType index; + index.Fill( 0 ); output = this->GetOutput(0); typename TOutputImage::RegionType largestPossibleRegion; - largestPossibleRegion.SetSize( size ); + largestPossibleRegion.SetSize( this->m_Size ); largestPossibleRegion.SetIndex( index ); output->SetLargestPossibleRegion( largestPossibleRegion ); diff --git a/Utilities/ITK/Code/BasicFilters/itkRecursiveSeparableImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkRecursiveSeparableImageFilter.h index 77a32827578ca37d66af51877a3538240e8cbcc1..6c9593d1306e8452598dcc01be1d71cd500663ad 100644 --- a/Utilities/ITK/Code/BasicFilters/itkRecursiveSeparableImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkRecursiveSeparableImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRecursiveSeparableImageFilter.h,v $ Language: C++ - Date: $Date: 2009-04-25 12:28:01 $ - Version: $Revision: 1.26 $ + Date: $Date: 2009-08-21 20:27:43 $ + Version: $Revision: 1.27 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -103,14 +103,14 @@ protected: int SplitRequestedRegion(int i, int num, OutputImageRegionType& splitRegion); - /** RecursiveSeparableImageFilter needs all of the input to produce an - * output. Therefore, RecursiveSeparableImageFilter needs to provide - * an implementation for GenerateInputRequestedRegion in order to inform - * the pipeline execution model. - * \sa ImageToImageFilter::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() throw(InvalidRequestedRegionError); - - // Override since the filter produces the entire dataset. + /** RecursiveSeparableImageFilter needs all of the input only in the + * "Direction" dimension. Therefore we enlarge the output's + * RequestedRegion to this. Then the superclass's + * GenerateInputRequestedRegion method will copy the output region + * to the input. + * + * \sa ImageToImageFilter::GenerateInputRequestedRegion() + */ void EnlargeOutputRequestedRegion(DataObject *output); /** Set up the coefficients of the filter to approximate a specific kernel. diff --git a/Utilities/ITK/Code/BasicFilters/itkRecursiveSeparableImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkRecursiveSeparableImageFilter.txx index e1adc732d1bcfe75177d672cc9a00040bc097cdb..fce3b64e5cb0ef05e9ba3a2f066328967745303d 100644 --- a/Utilities/ITK/Code/BasicFilters/itkRecursiveSeparableImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkRecursiveSeparableImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRecursiveSeparableImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-04-06 13:46:37 $ - Version: $Revision: 1.43 $ + Date: $Date: 2009-08-21 20:27:43 $ + Version: $Revision: 1.44 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -155,28 +155,7 @@ RecursiveSeparableImageFilter<TInputImage,TOutputImage> // -// -// -template <typename TInputImage, typename TOutputImage> -void -RecursiveSeparableImageFilter<TInputImage,TOutputImage> -::GenerateInputRequestedRegion() throw(InvalidRequestedRegionError) -{ - // call the superclass' implementation of this method. this should - // copy the output requested region to the input requested region - Superclass::GenerateInputRequestedRegion(); - - // This filter needs all of the input - InputImagePointer image = const_cast<InputImageType *>( this->GetInput() ); - if( image ) - { - image->SetRequestedRegion( this->GetInput()->GetLargestPossibleRegion() ); - } -} - - -// -// +// we need all of the image in just the "Direction" we are separated into // template <typename TInputImage, typename TOutputImage> void @@ -187,7 +166,20 @@ RecursiveSeparableImageFilter<TInputImage,TOutputImage> if (out) { - out->SetRequestedRegion( out->GetLargestPossibleRegion() ); + OutputImageRegionType outputRegion = out->GetRequestedRegion(); + const OutputImageRegionType &largestOutputRegion = out->GetLargestPossibleRegion(); + + // verify sane parameter + if ( this->m_Direction >= outputRegion.GetImageDimension() ) + { + itkExceptionMacro("Direction selected for filtering is greater than ImageDimension") + } + + // expand output region to match largest in the "Direction" dimension + outputRegion.SetIndex( m_Direction, largestOutputRegion.GetIndex(m_Direction) ); + outputRegion.SetSize( m_Direction, largestOutputRegion.GetSize(m_Direction) ); + + out->SetRequestedRegion( outputRegion ); } } diff --git a/Utilities/ITK/Code/BasicFilters/itkScalarConnectedComponentImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkScalarConnectedComponentImageFilter.h index 4339449e72724345161016bef30dc6061b820968..6f4d88798ae0c8b0e6855e734ec28995155ab1e0 100644 --- a/Utilities/ITK/Code/BasicFilters/itkScalarConnectedComponentImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkScalarConnectedComponentImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarConnectedComponentImageFilter.h,v $ Language: C++ - Date: $Date: 2009-04-01 14:36:31 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-07-05 17:36:22 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -42,8 +42,14 @@ class SimilarPixelsFunctor { public: SimilarPixelsFunctor() - {m_Threshold = itk::NumericTraits<TInput>::Zero;} - ~SimilarPixelsFunctor() {} + { + m_Threshold = NumericTraits<TInput>::Zero; + } + + ~SimilarPixelsFunctor() + { + } + bool operator!=( const SimilarPixelsFunctor & other ) const { if( m_Threshold != other.m_Threshold ) @@ -52,17 +58,36 @@ public: } return false; } + bool operator==( const SimilarPixelsFunctor & other ) const { return !(*this != other); } - void SetDistanceThreshold(const TInput &thresh) {m_Threshold = thresh;} - TInput GetDistanceThreshold() {return (m_Threshold);} + void SetDistanceThreshold(const TInput &thresh) + { + m_Threshold = thresh; + } + + TInput GetDistanceThreshold() + { + return (m_Threshold); + } bool operator()(const TInput &a, const TInput &b) const { - return (vnl_math_abs(a-b) <= m_Threshold); + typedef typename NumericTraits<TInput>::RealType InputRealType; + TInput absDifference = static_cast<TInput>( vnl_math_abs( + static_cast<InputRealType>(a) + - static_cast<InputRealType>(b) ) ); + if( absDifference <= m_Threshold ) + { + return true; + } + else + { + return false; + } } protected: diff --git a/Utilities/ITK/Code/BasicFilters/itkShrinkImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkShrinkImageFilter.txx index 42284eade7534403ae3b5cd439b56924af48994f..5dae33dd429b9342f1da384155698d5129ea539d 100644 --- a/Utilities/ITK/Code/BasicFilters/itkShrinkImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkShrinkImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkShrinkImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-05-05 21:45:49 $ - Version: $Revision: 1.61 $ + Date: $Date: 2009-09-08 20:55:50 $ + Version: $Revision: 1.64 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -132,7 +132,7 @@ ShrinkImageFilter<TInputImage,TOutputImage> OutputImagePointer outputPtr = this->GetOutput(); - // convert the factor for convenient multiplication + // Convert the factor for convenient multiplication unsigned int i; typename TOutputImage::SizeType factorSize; for ( i=0; i < TInputImage::ImageDimension; i++ ) @@ -148,9 +148,8 @@ ShrinkImageFilter<TInputImage,TOutputImage> typename TOutputImage::PointType tempPoint; - // use this index to compute the offset everywhere in this class + // Use this index to compute the offset everywhere in this class outputIndex = outputPtr->GetLargestPossibleRegion().GetIndex(); - inputIndex = inputPtr->GetLargestPossibleRegion().GetIndex(); // We wish to perform the following mapping of outputIndex to // inputIndex on all points in our region @@ -165,14 +164,13 @@ ShrinkImageFilter<TInputImage,TOutputImage> for ( i=0; i < TInputImage::ImageDimension; i++ ) { offsetIndex[i] = inputIndex[i] - outputIndex[i]*m_ShrinkFactors[i]; - // it is plausible that due to small amounts of loss of numerical + // It is plausible that due to small amounts of loss of numerical // precision that the offset it negaive, this would cause sampling // out of out region, this is insurance against that possibility offsetIndex[i] = vnl_math_max( zeroOffset, offsetIndex[i] ); } - - // support progress methods/callbacks + // Support progress methods/callbacks ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); // Define/declare an iterator that will walk the output region for this @@ -182,16 +180,16 @@ ShrinkImageFilter<TInputImage,TOutputImage> while ( !outIt.IsAtEnd() ) { - // determine the index and physical location of the output pixel + // Determine the index and physical location of the output pixel outputIndex = outIt.GetIndex(); - // an optimized version of + // An optimized version of // outputPtr->TransformIndexToPhysicalPoint(outputIndex, tempPoint); // inputPtr->TransformPhysicalPointToIndex(tempPoint, inputIndex); // but without the rounding and precision issues inputIndex = outputIndex * factorSize + offsetIndex; - // copy the input pixel to the output + // Copy the input pixel to the output outIt.Set( inputPtr->GetPixel(inputIndex) ); ++outIt; @@ -207,10 +205,10 @@ void ShrinkImageFilter<TInputImage,TOutputImage> ::GenerateInputRequestedRegion() { - // call the superclass' implementation of this method + // Call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); - // get pointers to the input and output + // Get pointers to the input and output InputImagePointer inputPtr = const_cast<TInputImage *> (this->GetInput()); OutputImagePointer outputPtr = this->GetOutput(); @@ -229,7 +227,7 @@ ShrinkImageFilter<TInputImage,TOutputImage> = outputPtr->GetRequestedRegion().GetIndex(); - // convert the factor for convenient multiplication + // Convert the factor for convenient multiplication typename TOutputImage::SizeType factorSize; for ( i=0; i < TInputImage::ImageDimension; i++ ) { @@ -243,10 +241,8 @@ ShrinkImageFilter<TInputImage,TOutputImage> typename TInputImage::SizeType inputRequestedRegionSize; typename TOutputImage::PointType tempPoint; - - // use this index to compute the offset everywhere in this class + // Use this index to compute the offset everywhere in this class outputIndex = outputPtr->GetLargestPossibleRegion().GetIndex(); - inputIndex = inputPtr->GetLargestPossibleRegion().GetIndex(); // We wish to perform the following mapping of outputIndex to // inputIndex on all points in our region @@ -261,7 +257,7 @@ ShrinkImageFilter<TInputImage,TOutputImage> for ( i=0; i < TInputImage::ImageDimension; i++ ) { offsetIndex[i] = inputIndex[i] - outputIndex[i]*m_ShrinkFactors[i]; - // it is plausible that due to small amounts of loss of numerical + // It is plausible that due to small amounts of loss of numerical // precision that the offset it negaive, this would cause sampling // out of out region, this is insurance against that possibility offsetIndex[i] = vnl_math_max( zeroOffset, offsetIndex[i] ); @@ -269,14 +265,14 @@ ShrinkImageFilter<TInputImage,TOutputImage> inputRequestedRegionIndex = outputRequestedRegionStartIndex*factorSize + offsetIndex; - // originally this was - // inputSize = outputRequestedRegionSize * factorSize - // but since we don't sample edge to edge, we can reduce the size - for ( i=0; i < TInputImage::ImageDimension; ++i ) - { - inputRequestedRegionSize[i] = (outputRequestedRegionSize[i] - 1 ) * factorSize[i] + 1; - } - + // Originally this was + // for ( i=0; i < TInputImage::ImageDimension; ++i ) + // { + // inputRequestedRegionSize[i] = (outputRequestedRegionSize[i] - 1 ) * factorSize[i] + 1; + // } + // but with centered pixels we may sample edge to edge + + inputRequestedRegionSize = outputRequestedRegionSize * factorSize; typename TInputImage::RegionType inputRequestedRegion; inputRequestedRegion.SetIndex( inputRequestedRegionIndex ); @@ -294,10 +290,10 @@ void ShrinkImageFilter<TInputImage,TOutputImage> ::GenerateOutputInformation() { - // call the superclass' implementation of this method + // Call the superclass' implementation of this method Superclass::GenerateOutputInformation(); - // get pointers to the input and output + // Get pointers to the input and output InputImageConstPointer inputPtr = this->GetInput(); OutputImagePointer outputPtr = this->GetOutput(); @@ -306,7 +302,7 @@ ShrinkImageFilter<TInputImage,TOutputImage> return; } - // we need to compute the output spacing, the output image size, and the + // Compute the output spacing, the output image size, and the // output image start index unsigned int i; const typename TInputImage::SpacingType& @@ -324,7 +320,7 @@ ShrinkImageFilter<TInputImage,TOutputImage> { outputSpacing[i] = inputSpacing[i] * (double) m_ShrinkFactors[i]; - // we round down so that all output pixels fit input input region + // Round down so that all output pixels fit input input region outputSize[i] = (unsigned long) vcl_floor((double) inputSize[i] / (double) m_ShrinkFactors[i]); @@ -333,7 +329,7 @@ ShrinkImageFilter<TInputImage,TOutputImage> outputSize[i] = 1; } - // because of the later origin shift this starting index is not + // Because of the later origin shift this starting index is not // critical outputStartIndex[i] = (long) vcl_ceil((double) inputStartIndex[i] / (double) m_ShrinkFactors[i] ); @@ -341,7 +337,7 @@ ShrinkImageFilter<TInputImage,TOutputImage> outputPtr->SetSpacing( outputSpacing ); - // compute origin offset + // Compute origin offset // The physical center's of the input and output should be the same ContinuousIndex<double, TOutputImage::ImageDimension> inputCenterIndex; ContinuousIndex<double, TOutputImage::ImageDimension> outputCenterIndex; @@ -360,7 +356,7 @@ ShrinkImageFilter<TInputImage,TOutputImage> outputOrigin = outputOrigin + (inputCenterPoint - outputCenterPoint); outputPtr->SetOrigin(outputOrigin); - // set region + // Set region typename TOutputImage::RegionType outputLargestPossibleRegion; outputLargestPossibleRegion.SetSize( outputSize ); outputLargestPossibleRegion.SetIndex( outputStartIndex ); diff --git a/Utilities/ITK/Code/BasicFilters/itkSignedMaurerDistanceMapImageFilter.h b/Utilities/ITK/Code/BasicFilters/itkSignedMaurerDistanceMapImageFilter.h index 77c788efb6d5d895c903b3ae492c42d0d68255dc..611ec0f929e3f250c883b26fdbe214a3488234a4 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSignedMaurerDistanceMapImageFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkSignedMaurerDistanceMapImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSignedMaurerDistanceMapImageFilter.h,v $ Language: C++ - Date: $Date: 2009-05-12 17:22:53 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-06-14 12:30:08 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -50,7 +50,7 @@ namespace itk * itkDanielssonDistanceImageFilterClass except is does not return the Voronoi * map. * - * \cite C. R. Maurer, Jr., R. Qi, and V. Raghavan, "A Linear Time Algorithm + * Ref: C. R. Maurer, Jr., R. Qi, and V. Raghavan, "A Linear Time Algorithm * for Computing Exact Euclidean Distance Transforms of Binary Images in * Arbitrary Dimensions", IEEE - Transactions on Pattern Analysis and Machine * Intelligence, 25(2): 265-270, 2003. diff --git a/Utilities/ITK/Code/BasicFilters/itkSimplexMeshAdaptTopologyFilter.h b/Utilities/ITK/Code/BasicFilters/itkSimplexMeshAdaptTopologyFilter.h index 2718f7bf1427894886d8a9432afca70ff5c1cfd1..d7cd406c0e7a4f219f57be1cd80e3df524d5db3c 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSimplexMeshAdaptTopologyFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkSimplexMeshAdaptTopologyFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimplexMeshAdaptTopologyFilter.h,v $ Language: C++ -Date: $Date: 2009-05-12 17:22:53 $ -Version: $Revision: 1.14 $ +Date: $Date: 2009-06-13 17:42:54 $ +Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -176,6 +176,10 @@ public: double ComputeArea(unsigned long p1,unsigned long p2, unsigned long p3) { InputPointType v1,v2,v3; + v1.Fill(0); + v2.Fill(0); + v3.Fill(0); + mesh->GetPoint(p1, &v1); mesh->GetPoint(p2, &v2); mesh->GetPoint(p3, &v3); diff --git a/Utilities/ITK/Code/BasicFilters/itkSimplexMeshAdaptTopologyFilter.txx b/Utilities/ITK/Code/BasicFilters/itkSimplexMeshAdaptTopologyFilter.txx index fb58409948965648db93b14331eed2bbc882d808..f49068332569d58edbf522317a232c7ec389495d 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSimplexMeshAdaptTopologyFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkSimplexMeshAdaptTopologyFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimplexMeshAdaptTopologyFilter.txx,v $ Language: C++ - Date: $Date: 2009-05-12 17:22:53 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-06-14 19:55:37 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -149,6 +149,8 @@ void SimplexMeshAdaptTopologyFilter<TInputMesh, TOutputMesh> //create first new point InputPointType newMidPoint, helperPoint; InputPointType p1, p2; + p1.Fill(0); + p2.Fill(0); inputMesh->GetPoint(lineOneFirstIdx, &p1); inputMesh->GetPoint(lineOneSecondIdx, &p2); @@ -370,6 +372,7 @@ SimplexMeshAdaptTopologyFilter<TInputMesh, TOutputMesh> InputVectorType tmp; InputPointType p1, p2, cellCenter; + p1.Fill(0); cellCenter.Fill(0); // compute the cell center first diff --git a/Utilities/ITK/Code/BasicFilters/itkSimplexMeshToTriangleMeshFilter.h b/Utilities/ITK/Code/BasicFilters/itkSimplexMeshToTriangleMeshFilter.h index f60ce10d7f268edc41439f82f1f0927273263d79..8c8d18118a10cb7893e826f64f4ed060dcf9bccc 100644 --- a/Utilities/ITK/Code/BasicFilters/itkSimplexMeshToTriangleMeshFilter.h +++ b/Utilities/ITK/Code/BasicFilters/itkSimplexMeshToTriangleMeshFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimplexMeshToTriangleMeshFilter.h,v $ Language: C++ -Date: $Date: 2009-05-12 17:22:53 $ -Version: $Revision: 1.8 $ +Date: $Date: 2009-06-13 17:42:56 $ +Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -112,11 +112,14 @@ public: */ void Visit(unsigned long cellId, SimplexPolygonType * poly) { - typedef typename SimplexPolygonType::PointIdIterator PointIdIterator; + typedef typename SimplexPolygonType::PointIdIterator PointIdIterator; PointIdIterator it = poly->PointIdsBegin(); - InputPointType center,p; + InputPointType center; center.Fill(0); + InputPointType p; + p.Fill(0); + while ( it != poly->PointIdsEnd() ) { this->m_Mesh->GetPoint(*it, &p); diff --git a/Utilities/ITK/Code/BasicFilters/itkVectorGradientMagnitudeImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkVectorGradientMagnitudeImageFilter.txx index 3e1de55b01cf7115b07fd813cb1d28bacee2dcb3..0e288c2ce9af864309cc6622518c856490e01a32 100644 --- a/Utilities/ITK/Code/BasicFilters/itkVectorGradientMagnitudeImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkVectorGradientMagnitudeImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVectorGradientMagnitudeImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-04-06 00:19:17 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-08-07 15:27:43 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -315,7 +315,7 @@ VectorGradientMagnitudeImageFilter<TInputImage, TRealType, TOutputImage> // s are not necessarily sorted, and int is the number of distinct roots // found in s. int num; - const double dpi = 3.14159265358979323846; + const double dpi = vnl_math::pi; const double epsilon = 1.0e-11; // Substitution of x = y - c[2]/3 eliminate the quadric term x^3 +px + q = 0 diff --git a/Utilities/ITK/Code/BasicFilters/itkWarpImageFilter.txx b/Utilities/ITK/Code/BasicFilters/itkWarpImageFilter.txx index fa0d0882983902f8817585a50ced1d1511f4885f..44b3d93619dfc1bf0308a65bb69c29364b370cfa 100644 --- a/Utilities/ITK/Code/BasicFilters/itkWarpImageFilter.txx +++ b/Utilities/ITK/Code/BasicFilters/itkWarpImageFilter.txx @@ -9,8 +9,8 @@ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ @@ -38,8 +38,8 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> ::WarpImageFilter() { // Setup the number of required inputs - this->SetNumberOfRequiredInputs( 2 ); - + this->SetNumberOfRequiredInputs( 2 ); + // Setup default values m_OutputSpacing.Fill( 1.0 ); m_OutputOrigin.Fill( 0.0 ); @@ -51,7 +51,7 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> typename DefaultInterpolatorType::Pointer interp = DefaultInterpolatorType::New(); - m_Interpolator = + m_Interpolator = static_cast<InterpolatorType*>( interp.GetPointer() ); } @@ -75,7 +75,7 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> << static_cast<typename NumericTraits<PixelType>::PrintType>(m_EdgePaddingValue) << std::endl; os << indent << "Interpolator: " << m_Interpolator.GetPointer() << std::endl; - + } @@ -110,7 +110,7 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> /** Helper method to set the output parameters based on this image */ template <class TInputImage,class TOutputImage,class TDeformationField> -void +void WarpImageFilter<TInputImage,TOutputImage,TDeformationField> ::SetOutputParametersFromImage ( const ImageBaseType * image ) { @@ -132,7 +132,7 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> const DeformationFieldType * field ) { // const cast is needed because the pipeline is not const-correct. - DeformationFieldType * input = + DeformationFieldType * input = const_cast< DeformationFieldType * >( field ); this->ProcessObject::SetNthInput( 1, input ); } @@ -171,7 +171,7 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> // Connect input image to interpolator m_Interpolator->SetInputImage( this->GetInput() ); - typename DeformationFieldType::RegionType defRegion = + typename DeformationFieldType::RegionType defRegion = fieldPtr->GetLargestPossibleRegion(); typename OutputImageType::RegionType outRegion = this->GetOutput()->GetLargestPossibleRegion(); @@ -181,7 +181,7 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> m_StartIndex = fieldPtr->GetBufferedRegion().GetIndex(); for(unsigned i = 0; i < ImageDimension; i++) { - m_EndIndex[i] = m_StartIndex[i] + + m_EndIndex[i] = m_StartIndex[i] + fieldPtr->GetBufferedRegion().GetSize()[i] - 1; } } @@ -280,7 +280,7 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> // get neighbor value only if overlap is not zero if( overlap ) { - const DisplacementType input = + const DisplacementType input = fieldPtr->GetPixel( neighIndex ); for(unsigned int k = 0; k < PixelSizeFinder(input); k++ ) { @@ -325,7 +325,7 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> // support progress methods/callbacks ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); - + // iterator for the output image ImageRegionIteratorWithIndex<OutputImageType> outputIt( outputPtr, outputRegionForThread ); @@ -335,7 +335,7 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> if(this->m_DefFieldSizeSame) { // iterator for the deformation field - ImageRegionIterator<DeformationFieldType> + ImageRegionIterator<DeformationFieldType> fieldIt(fieldPtr, outputRegionForThread ); while( !outputIt.IsAtEnd() ) @@ -356,20 +356,20 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> // get the interpolated value if( m_Interpolator->IsInsideBuffer( point ) ) { - PixelType value = + PixelType value = static_cast<PixelType>(m_Interpolator->Evaluate( point ) ); outputIt.Set( value ); } else { outputIt.Set( m_EdgePaddingValue ); - } + } ++outputIt; - ++fieldIt; + ++fieldIt; progress.CompletedPixel(); } - } - else + } + else { while( !outputIt.IsAtEnd() ) { @@ -387,14 +387,14 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> // get the interpolated value if( m_Interpolator->IsInsideBuffer( point ) ) { - PixelType value = + PixelType value = static_cast<PixelType>(m_Interpolator->Evaluate( point ) ); outputIt.Set( value ); } else { outputIt.Set( m_EdgePaddingValue ); - } + } ++outputIt; progress.CompletedPixel(); } @@ -412,7 +412,7 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> Superclass::GenerateInputRequestedRegion(); // request the largest possible region for the input image - InputImagePointer inputPtr = + InputImagePointer inputPtr = const_cast< InputImageType * >( this->GetInput() ); if( inputPtr ) @@ -420,7 +420,7 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> inputPtr->SetRequestedRegionToLargestPossibleRegion(); } - // just propagate up the output requested region for the + // just propagate up the output requested region for the // deformation field. DeformationFieldPointer fieldPtr = this->GetDeformationField(); OutputImagePointer outputPtr = this->GetOutput(); @@ -450,7 +450,7 @@ WarpImageFilter<TInputImage,TOutputImage,TDeformationField> outputPtr->SetDirection( m_OutputDirection ); DeformationFieldPointer fieldPtr = this->GetDeformationField(); - if( this->m_OutputSize[0] == 0 && + if( this->m_OutputSize[0] == 0 && fieldPtr.IsNotNull()) { outputPtr->SetLargestPossibleRegion( fieldPtr-> diff --git a/Utilities/ITK/Code/Common/itkAffineTransform.h b/Utilities/ITK/Code/Common/itkAffineTransform.h index 1dbdeb5ad947194d2f67a475c7d87333895f560e..8b1c631c5e9a1b0b5d4868d3e73c901a03e0b8ad 100644 --- a/Utilities/ITK/Code/Common/itkAffineTransform.h +++ b/Utilities/ITK/Code/Common/itkAffineTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAffineTransform.h,v $ Language: C++ - Date: $Date: 2009-04-09 09:23:20 $ - Version: $Revision: 1.70 $ + Date: $Date: 2009-06-17 12:17:33 $ + Version: $Revision: 1.71 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -89,7 +89,7 @@ namespace itk * transform parameters can also be set as an Array<double> of size * (NDimension + 1) * NDimension using method SetParameters(). * The first (NDimension x NDimension) parameters defines the matrix in - * column-major order (where the column index) varies the fastest). + * row-major order (where the column index varies the fastest). * The last NDimension parameters defines the translation * in each dimensions. * diff --git a/Utilities/ITK/Code/Common/itkAutoPointer.h b/Utilities/ITK/Code/Common/itkAutoPointer.h index d5a8d94d87e7cc788ed6330e33e1ffb9452d4f93..e057141bb51f4b50f5b87da57b660f055bc4ece3 100644 --- a/Utilities/ITK/Code/Common/itkAutoPointer.h +++ b/Utilities/ITK/Code/Common/itkAutoPointer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAutoPointer.h,v $ Language: C++ - Date: $Date: 2006-03-18 18:06:14 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-08-05 19:52:39 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -171,7 +171,7 @@ public: { return (void*)m_Pointer >= (void*) r.m_Pointer; } /** Overload operator assignment. */ - AutoPointer &operator = (AutoPointer &r) const + AutoPointer &operator = (AutoPointer &r) { AutoPointer( r ).Swap( *this ); return *this; @@ -183,13 +183,14 @@ public: { return (m_Pointer!=NULL); } /** Function to print object pointed to. */ - ObjectType *Print (std::ostream& os) const +/* ObjectType *Print (std::ostream& os) const { // This prints the object pointed to by the pointer (*m_Pointer).Print(os); os << "Owner: " << m_IsOwner << std::endl; return m_Pointer; } +*/ private: diff --git a/Utilities/ITK/Code/Common/itkBSplineInterpolationWeightFunction.txx b/Utilities/ITK/Code/Common/itkBSplineInterpolationWeightFunction.txx index 257cc5a97445c49a357c8d66afe4d384ddd1b605..fd670d7eb237e1b70029034e4db14695901d1258 100644 --- a/Utilities/ITK/Code/Common/itkBSplineInterpolationWeightFunction.txx +++ b/Utilities/ITK/Code/Common/itkBSplineInterpolationWeightFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBSplineInterpolationWeightFunction.txx,v $ Language: C++ - Date: $Date: 2008-03-21 00:47:43 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-06-16 08:01:55 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,27 +22,6 @@ #include "itkMatrix.h" #include "itkImageRegionConstIteratorWithIndex.h" -// anonymous namespace -namespace -{ -//-------------------------------------------------------------------------- -// The 'floor' function on x86 and mips is many times slower than these -// and is used a lot in this code, optimize for different CPU architectures -inline int BSplineFloor(double x) -{ -#if defined mips || defined sparc || defined __ppc__ - return (int)((unsigned int)(x + 2147483648.0) - 2147483648U); -#elif defined i386 || defined _M_IX86 - union { unsigned int hilo[2]; double d; } u; - u.d = x + 103079215104.0; - return (int)((u.hilo[1]<<16)|(u.hilo[0]>>16)); -#else - return int(floor(x)); -#endif -} - -} - namespace itk { @@ -147,7 +126,7 @@ void BSplineInterpolationWeightFunction<TCoordRep, VSpaceDimension, for ( j = 0; j < SpaceDimension; j++ ) { startIndex[j] = static_cast<typename IndexType::IndexValueType>( - BSplineFloor( index[j] - static_cast<double>( SplineOrder - 1 ) / 2.0 ) ); + Math::Floor( index[j] - static_cast<double>( SplineOrder - 1 ) / 2.0 ) ); } // Compute the weights diff --git a/Utilities/ITK/Code/Common/itkCellInterface.h b/Utilities/ITK/Code/Common/itkCellInterface.h index 02f9717fd849c7bcdb784cb2cf7faed634687125..8bd87c9b59799df6b33ff61c85f5e17f60c44117 100644 --- a/Utilities/ITK/Code/Common/itkCellInterface.h +++ b/Utilities/ITK/Code/Common/itkCellInterface.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCellInterface.h,v $ Language: C++ - Date: $Date: 2008-07-10 19:09:39 $ - Version: $Revision: 1.67 $ + Date: $Date: 2009-08-08 20:13:35 $ + Version: $Revision: 1.72 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -51,12 +51,7 @@ virtual void Accept(unsigned long cellid, typename CellInterface<PixelType,\ typedef AutoPointer<const Self> ConstSelfAutoPointer; \ typedef AutoPointer<Self> SelfAutoPointer; \ typedef Self * RawPointer; \ - typedef const Self * ConstRawPointer; \ - SelfAutoPointer New(void) { \ - SelfAutoPointer ptr( new celltype ); \ - ptr.TakeOwnership(); \ - return ptr; \ - } \ + typedef const Self * ConstRawPointer // Define a macro for the common typedefs required by the @@ -166,7 +161,7 @@ public: typedef Array<CoordRepType> ParametricCoordArrayType; typedef Array<InterpolationWeightType> ShapeFunctionsArrayType; - static int GetNextUserCellId(); // never return > MAX_INTERFACE +// static int GetNextUserCellId(); // never return > MAX_INTERFACE /** \class MultiVisitor * \brief A visitor that can visit different cell types in a mesh. @@ -416,6 +411,7 @@ public: */ virtual unsigned int GetNumberOfUsingCells(void); +#if !defined(CABLE_CONFIGURATION) /** * Get a begin iterator for the UsingCellsContainer. */ @@ -425,7 +421,8 @@ public: * Get an end iterator for the UsingCellsContainer. */ virtual UsingCellsContainerIterator UsingCellsEnd(void); - +#endif + /** Standard part of every itk Object. */ itkTypeMacro(CellInterface, LightObject); @@ -493,8 +490,10 @@ public: } // end namespace itk -#ifndef ITK_MANUAL_INSTANTIATION +#if !defined(CABLE_CONFIGURATION) +# ifndef ITK_MANUAL_INSTANTIATION #include "itkCellInterface.txx" #endif +#endif #endif diff --git a/Utilities/ITK/Code/Common/itkCellInterface.txx b/Utilities/ITK/Code/Common/itkCellInterface.txx index 71dac7a426f3014290ba6ba00d8649e2da399f2a..9aa69d04eac3919e9d329b3627d6ea07a4fa5d1c 100644 --- a/Utilities/ITK/Code/Common/itkCellInterface.txx +++ b/Utilities/ITK/Code/Common/itkCellInterface.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCellInterface.txx,v $ Language: C++ - Date: $Date: 2006-03-18 18:06:25 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-08-08 20:42:15 $ + Version: $Revision: 1.20 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -114,6 +114,8 @@ CellInterface< TPixelType , TCellTraits > } +#if !defined(CABLE_CONFIGURATION) + /** * Get a begin iterator for the UsingCellsContainer. */ @@ -137,6 +139,8 @@ CellInterface< TPixelType , TCellTraits > return m_UsingCells.end(); } +#endif + } // end namespace itk #endif diff --git a/Utilities/ITK/Code/Common/itkCenteredTransformInitializer.h b/Utilities/ITK/Code/Common/itkCenteredTransformInitializer.h index 909a51e100c02e323dd1001d6373d5828572615b..d5b425c0c2636e36a0d65669e69991dbb232a57a 100644 --- a/Utilities/ITK/Code/Common/itkCenteredTransformInitializer.h +++ b/Utilities/ITK/Code/Common/itkCenteredTransformInitializer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCenteredTransformInitializer.h,v $ Language: C++ - Date: $Date: 2007-04-11 18:10:06 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-08-15 23:42:49 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -122,7 +122,7 @@ public: /** Initialize the transform using data from the images */ - virtual void InitializeTransform() const; + virtual void InitializeTransform(); /** Select between using the geometrical center of the images or using the center of mass given by the image intensities. */ @@ -139,6 +139,8 @@ protected: void PrintSelf(std::ostream &os, Indent indent) const; + itkGetObjectMacro( Transform, TransformType ); + private: CenteredTransformInitializer(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Code/Common/itkCenteredTransformInitializer.txx b/Utilities/ITK/Code/Common/itkCenteredTransformInitializer.txx index 8a03d4dfb75abb3c8c25f58eda1e81116831ab77..1c049acd678ad95778451d282cd0f6fa92073791 100644 --- a/Utilities/ITK/Code/Common/itkCenteredTransformInitializer.txx +++ b/Utilities/ITK/Code/Common/itkCenteredTransformInitializer.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCenteredTransformInitializer.txx,v $ Language: C++ - Date: $Date: 2008-06-12 17:14:07 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-08-15 23:42:49 $ + Version: $Revision: 1.22 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -37,7 +37,7 @@ CenteredTransformInitializer<TTransform, TFixedImage, TMovingImage > template < class TTransform, class TFixedImage, class TMovingImage > void CenteredTransformInitializer<TTransform, TFixedImage, TMovingImage > -::InitializeTransform() const +::InitializeTransform() { // Sanity check if( !m_FixedImage ) diff --git a/Utilities/ITK/Code/Common/itkCenteredVersorTransformInitializer.h b/Utilities/ITK/Code/Common/itkCenteredVersorTransformInitializer.h index b5324fe312389b9226f64dd19723b1e825d18e4a..c41c705495bde3cd6cd85e8bb39303b7d0b489ce 100644 --- a/Utilities/ITK/Code/Common/itkCenteredVersorTransformInitializer.h +++ b/Utilities/ITK/Code/Common/itkCenteredVersorTransformInitializer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCenteredVersorTransformInitializer.h,v $ Language: C++ - Date: $Date: 2007-04-11 18:10:06 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-08-16 23:09:27 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -88,7 +88,13 @@ public: typedef typename Superclass::OutputVectorType OutputVectorType; /** Initialize the transform using data from the images */ - void InitializeTransform() const; + void InitializeTransform(); + + /** Enable the use of the principal axes of each image to compute an + * initial rotation that will align them. */ + itkSetMacro( ComputeRotation, bool ); + itkGetMacro( ComputeRotation, bool ); + itkBooleanMacro( ComputeRotation ); protected: CenteredVersorTransformInitializer(); @@ -100,6 +106,7 @@ private: CenteredVersorTransformInitializer(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented + bool m_ComputeRotation; }; //class CenteredVersorTransformInitializer diff --git a/Utilities/ITK/Code/Common/itkCenteredVersorTransformInitializer.txx b/Utilities/ITK/Code/Common/itkCenteredVersorTransformInitializer.txx index 15b9971a6264460df00db188c15025020aa18273..bccbd74bc5513baeb7538fe2c7bb4d7ae219a248 100644 --- a/Utilities/ITK/Code/Common/itkCenteredVersorTransformInitializer.txx +++ b/Utilities/ITK/Code/Common/itkCenteredVersorTransformInitializer.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCenteredVersorTransformInitializer.txx,v $ Language: C++ - Date: $Date: 2006-03-18 20:13:58 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-08-17 23:21:05 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -30,27 +30,31 @@ CenteredVersorTransformInitializer<TFixedImage, TMovingImage > // Force to use Moments computation since we need here the second // order moments in order to estimate a rotation this->Superclass::MomentsOn(); + + this->m_ComputeRotation = false; } template < class TFixedImage, class TMovingImage > void CenteredVersorTransformInitializer<TFixedImage, TMovingImage > -::InitializeTransform() const +::InitializeTransform() { // Compute moments and initialize center of rotaion and translation this->Superclass::InitializeTransform(); - typedef typename Superclass::FixedImageCalculatorType::MatrixType - FixedMatrixType; - typedef typename Superclass::MovingImageCalculatorType::MatrixType - MovingMatrixType; - - FixedMatrixType fixedPrincipalAxis = - this->GetFixedCalculator()->GetPrincipalAxes(); - MovingMatrixType movingPrincipalAxis = - this->GetMovingCalculator()->GetPrincipalAxes(); - + if( this->m_ComputeRotation ) + { + typedef typename Superclass::FixedImageCalculatorType::MatrixType FixedMatrixType; + typedef typename Superclass::MovingImageCalculatorType::MatrixType MovingMatrixType; + + FixedMatrixType fixedPrincipalAxis = this->GetFixedCalculator()->GetPrincipalAxes(); + MovingMatrixType movingPrincipalAxis = this->GetMovingCalculator()->GetPrincipalAxes(); + + MovingMatrixType rotationMatrix = movingPrincipalAxis * fixedPrincipalAxis.GetInverse(); + + this->GetTransform()->SetMatrix( rotationMatrix ); + } } @@ -60,6 +64,7 @@ CenteredVersorTransformInitializer<TFixedImage, TMovingImage > ::PrintSelf(std::ostream& os, Indent indent) const { this->Superclass::PrintSelf(os,indent); + os << indent << "Compute Rotation " << this->m_ComputeRotation << std::endl; } } // namespace itk diff --git a/Utilities/ITK/Code/Common/itkCorrespondingMedialNodeClique.txx b/Utilities/ITK/Code/Common/itkCorrespondingMedialNodeClique.txx index e67ce75d454ab7e456a082ca8321f3a1515c7184..c1f213a013ddec6222448ef055be5f914f016245 100644 --- a/Utilities/ITK/Code/Common/itkCorrespondingMedialNodeClique.txx +++ b/Utilities/ITK/Code/Common/itkCorrespondingMedialNodeClique.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCorrespondingMedialNodeClique.txx,v $ Language: C++ - Date: $Date: 2003-09-10 14:29:05 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-06-16 13:33:34 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,7 +26,16 @@ template <unsigned int VImageDimension, unsigned int VCliqueSize> CorrespondingMedialNodeClique<VImageDimension, VCliqueSize> ::CorrespondingMedialNodeClique() { + m_NodeCoordinates = 0; + m_CenterOfMass = 0; + m_TransformMatrix = 0; + m_AverageDistance = 0; + + for( unsigned int i = 0; i < VCliqueSize; i++ ) + { + m_CorrespondenceValue[i] = 0; + } } template <unsigned int VImageDimension, unsigned int VCliqueSize> diff --git a/Utilities/ITK/Code/Common/itkElasticBodySplineKernelTransform.h b/Utilities/ITK/Code/Common/itkElasticBodySplineKernelTransform.h index 91846d157753c9a7a027d295699137b57f1db00e..1985d023e98003ff835afb63c87bd3a34553872e 100644 --- a/Utilities/ITK/Code/Common/itkElasticBodySplineKernelTransform.h +++ b/Utilities/ITK/Code/Common/itkElasticBodySplineKernelTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkElasticBodySplineKernelTransform.h,v $ Language: C++ - Date: $Date: 2009-04-25 12:24:05 $ - Version: $Revision: 1.36 $ + Date: $Date: 2009-06-14 12:30:08 $ + Version: $Revision: 1.37 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -96,22 +96,23 @@ protected: /** Compute G(x) * For the elastic body spline, this is: - * G(x) = [alpha*r(x)^2*I - 3*x*x']*r(x) + * \f$ G(x) = [alpha*r(x)^2*I - 3*x*x']*r(x) \f$ * \f$ G(x) = [\alpha*r(x)^2*I - 3*x*x']*r(x) \f$ * where * \f$\alpha = 12 ( 1 - \nu ) - 1\f$ * \f$\nu\f$ is Poisson's Ratio - * r(x) = Euclidean norm = sqrt[x1^2 + x2^2 + x3^2] + * \f$ r(x) = Euclidean norm = sqrt[x1^2 + x2^2 + x3^2] \f$ * \f[ r(x) = \sqrt{ x_1^2 + x_2^2 + x_3^2 } \f] - * I = identity matrix */ + * I = identity matrix + */ virtual void ComputeG(const InputVectorType& landmarkVector, GMatrixType & gmatrix) const; /** * \deprecated in ITK 3.6, please use void ComputeG(vector,gmatrix) instead. */ itkLegacyMacro( virtual const GMatrixType & ComputeG(const InputVectorType& landmarkVector) const ); - /** alpha, Alpha is related to Poisson's Ratio ($\nu$) as - * $\alpha = 12 ( 1 - \nu ) - 1$ + /** alpha, Alpha is related to Poisson's Ratio (\f$\nu\f$) as + * \$\alpha = 12 ( 1 - \nu ) - 1\f$ */ TScalarType m_Alpha; diff --git a/Utilities/ITK/Code/Common/itkFixedArray.h b/Utilities/ITK/Code/Common/itkFixedArray.h index 4c9f3c1120585960910552c9aebc444b4168da4b..7d0a66dccbe355e2749970725af4abdaee37401b 100644 --- a/Utilities/ITK/Code/Common/itkFixedArray.h +++ b/Utilities/ITK/Code/Common/itkFixedArray.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFixedArray.h,v $ Language: C++ - Date: $Date: 2008-10-16 13:28:49 $ - Version: $Revision: 1.42 $ + Date: $Date: 2009-07-09 18:06:39 $ + Version: $Revision: 1.45 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -82,6 +82,8 @@ public: /** A const iterator through the array. */ typedef const ValueType* ConstIterator; + class ConstReverseIterator; + /** \class ReverseIterator * \brief A reverse iterator through the array. */ class ReverseIterator @@ -98,6 +100,7 @@ public: bool operator==(const ReverseIterator &rit) const {return m_Iterator == rit.m_Iterator;} private: Iterator m_Iterator; + friend class ConstReverseIterator; }; /** \class ConstReverseIterator @@ -106,6 +109,7 @@ public: { public: explicit ConstReverseIterator(ConstIterator i): m_Iterator(i) {} + ConstReverseIterator(const ReverseIterator& rit) { m_Iterator = rit.m_Iterator; } ConstIterator operator++() { return --m_Iterator; } ConstIterator operator++(int) { return m_Iterator--; } ConstIterator operator--() { return ++m_Iterator; } diff --git a/Utilities/ITK/Code/Common/itkGaussianBlurImageFunction.txx b/Utilities/ITK/Code/Common/itkGaussianBlurImageFunction.txx index 12af06c433b4a8ca175170506630dc5bd62547ea..4cc8b55e3625babfe0c015b230bcf5768661b099 100644 --- a/Utilities/ITK/Code/Common/itkGaussianBlurImageFunction.txx +++ b/Utilities/ITK/Code/Common/itkGaussianBlurImageFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianBlurImageFunction.txx,v $ Language: C++ - Date: $Date: 2009-05-14 12:32:23 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-06-17 14:43:50 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -423,33 +423,32 @@ TOutput GaussianBlurImageFunction<TInputImage,TOutput> ::Evaluate(const PointType& point) const { + ContinuousIndexType cindex; - IndexType index; - - double offset[itkGetStaticConstMacro(ImageDimension)]; - for(unsigned int i=0; i<itkGetStaticConstMacro(ImageDimension);i++) - { - index[i] = (unsigned long)point[i]; - offset[i] = point[i]-index[i]; - } + this->m_InternalImage->TransformPhysicalPointToContinuousIndex( point, cindex ); - this->RecomputeContinuousGaussianKernel(offset); - - return this->EvaluateAtIndex( index, m_ContinuousOperatorArray ); + return this->EvaluateAtContinuousIndex( cindex ); } /** Evaluate the function at specified ContinousIndex position.*/ template <class TInputImage,class TOutput> TOutput GaussianBlurImageFunction<TInputImage,TOutput> -::EvaluateAtContinuousIndex( const ContinuousIndexType & index ) const +::EvaluateAtContinuousIndex( const ContinuousIndexType & cindex ) const { - PointType point; + IndexType index; + + index.CopyWithRound( cindex ); + + double offset[itkGetStaticConstMacro(ImageDimension)]; for(unsigned int i=0; i<itkGetStaticConstMacro(ImageDimension);i++) { - point[i] = index[i]; + offset[i] = cindex[i] - index[i]; } - return this->Evaluate(point); + + this->RecomputeContinuousGaussianKernel( offset ); + + return this->EvaluateAtIndex( index, m_ContinuousOperatorArray ); } } // end namespace itk diff --git a/Utilities/ITK/Code/Common/itkGaussianDerivativeSpatialFunction.txx b/Utilities/ITK/Code/Common/itkGaussianDerivativeSpatialFunction.txx index 837c62d9d6f378f575a740ca9ed6070c9f05ce7a..f92f4b4c6d27e8cf9aaaac2ae34750369b6b9672 100644 --- a/Utilities/ITK/Code/Common/itkGaussianDerivativeSpatialFunction.txx +++ b/Utilities/ITK/Code/Common/itkGaussianDerivativeSpatialFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianDerivativeSpatialFunction.txx,v $ Language: C++ - Date: $Date: 2007-06-11 15:12:09 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-08-07 15:27:42 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -60,7 +60,7 @@ GaussianDerivativeSpatialFunction<TOutput, VImageDimension, TInput> prefixDenom *= m_Sigma[i]; } - prefixDenom *= 2*vcl_pow( 2 * 3.1415927, VImageDimension / 2.0); + prefixDenom *= 2*vcl_pow( 2 * vnl_math::pi, VImageDimension / 2.0); } else { diff --git a/Utilities/ITK/Code/Common/itkIdentityTransform.h b/Utilities/ITK/Code/Common/itkIdentityTransform.h index aa8c0236175cf9ee77a76d39de438b7828697ef3..d5a24f96b49471b678eeb077e24f964557855e84 100644 --- a/Utilities/ITK/Code/Common/itkIdentityTransform.h +++ b/Utilities/ITK/Code/Common/itkIdentityTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkIdentityTransform.h,v $ Language: C++ - Date: $Date: 2009-04-09 09:23:21 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-06-28 14:41:47 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -133,11 +133,6 @@ public: The method is provided only to comply with the interface of other transforms. */ void SetIdentity( void ) { } - - /** Set the Transformation Parameters - * and update the internal transformation. */ - virtual void SetParameters(const ParametersType &) {}; - /** Compute the Jacobian of the transformation * * This method computes the Jacobian matrix of the transformation. @@ -184,6 +179,25 @@ public: */ virtual bool IsLinear() const { return true; } + /** Get the Fixed Parameters. */ + virtual const ParametersType& GetFixedParameters(void) const + { + return this->m_FixedParameters; + } + + /** Set the fixed parameters and update internal transformation. */ + virtual void SetFixedParameters( const ParametersType & ) {} + + /** Get the Parameters. */ + virtual const ParametersType& GetParameters(void) const + { + return this->m_Parameters; + } + + /** Set the fixed parameters and update internal transformation. */ + virtual void SetParameters( const ParametersType & ) {} + + protected: IdentityTransform():Transform<TScalarType,NDimensions,NDimensions>(NDimensions,1) { diff --git a/Utilities/ITK/Code/Common/itkImage.h b/Utilities/ITK/Code/Common/itkImage.h index fc9347d466c926ef9de0cfcd69b124dbfd0c6f7b..6bbbafa8a9bd53df522bcb873df0daff3af74879 100644 --- a/Utilities/ITK/Code/Common/itkImage.h +++ b/Utilities/ITK/Code/Common/itkImage.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImage.h,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:56 $ - Version: $Revision: 1.150 $ + Date: $Date: 2009-08-14 13:28:21 $ + Version: $Revision: 1.151 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -135,7 +135,8 @@ public: typedef typename Superclass::OffsetType OffsetType; /** Size typedef support. A size is used to define region bounds. */ - typedef typename Superclass::SizeType SizeType; + typedef typename Superclass::SizeType SizeType; + typedef typename Superclass::SizeValueType SizeValueType; /** Direction typedef support. A matrix of direction cosines. */ typedef typename Superclass::DirectionType DirectionType; diff --git a/Utilities/ITK/Code/Common/itkImage.txx b/Utilities/ITK/Code/Common/itkImage.txx index df979cbebd7e230cc05ec05e83187541bfcac4c6..ae91522903ffa583d5afce78d72b20f7b487fe7b 100644 --- a/Utilities/ITK/Code/Common/itkImage.txx +++ b/Utilities/ITK/Code/Common/itkImage.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImage.txx,v $ Language: C++ - Date: $Date: 2008-10-18 17:19:48 $ - Version: $Revision: 1.102 $ + Date: $Date: 2009-08-14 11:40:36 $ + Version: $Revision: 1.103 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -76,10 +76,10 @@ void Image<TPixel, VImageDimension> ::FillBuffer (const TPixel& value) { - const unsigned long numberOfPixels = + const SizeValueType numberOfPixels = this->GetBufferedRegion().GetNumberOfPixels(); - for(unsigned int i=0; i<numberOfPixels; i++) + for(SizeValueType i=0; i<numberOfPixels; i++) { (*m_Buffer)[i] = value; } diff --git a/Utilities/ITK/Code/Common/itkImageBase.h b/Utilities/ITK/Code/Common/itkImageBase.h index a29ba52ad34caae3aaf811568db399fe159efe3c..9568955914832f85a2b8926f48b5da0a47b9b2b5 100644 --- a/Utilities/ITK/Code/Common/itkImageBase.h +++ b/Utilities/ITK/Code/Common/itkImageBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageBase.h,v $ Language: C++ - Date: $Date: 2009-05-07 14:03:42 $ - Version: $Revision: 1.80 $ + Date: $Date: 2009-07-12 10:52:52 $ + Version: $Revision: 1.81 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -125,11 +125,13 @@ public: * spacing is the geometric distance between image samples. ITK only * supports positive spacing value: negative values may cause * undesirable results. */ - typedef Vector<double, VImageDimension> SpacingType; + typedef double SpacingValueType; + typedef Vector<SpacingValueType, VImageDimension> SpacingType; /** Origin typedef support. The origin is the geometric coordinates * of the index (0,0). */ - typedef Point<double, VImageDimension> PointType; + typedef double PointValueType; + typedef Point<PointValueType, VImageDimension> PointType; /** Direction typedef support. The Direction is a matix of * direction cosines that specify the direction between samples. diff --git a/Utilities/ITK/Code/Common/itkImageBase.txx b/Utilities/ITK/Code/Common/itkImageBase.txx index 0b5bdc2da54e1e29d3c6d1ea34a638a052a15a91..ba3465f7c7b94159184e399831a796a63cb6fe7c 100644 --- a/Utilities/ITK/Code/Common/itkImageBase.txx +++ b/Utilities/ITK/Code/Common/itkImageBase.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageBase.txx,v $ Language: C++ - Date: $Date: 2009-04-05 17:10:16 $ - Version: $Revision: 1.56 $ + Date: $Date: 2009-08-15 08:03:36 $ + Version: $Revision: 1.60 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -203,15 +203,23 @@ void ImageBase<VImageDimension> ::ComputeOffsetTable() { + // vxl_uint_64 num=1; OffsetValueType num=1; const SizeType& bufferSize = this->GetBufferedRegion().GetSize(); + // m_OffsetTable[0] = (OffsetValueType)num; m_OffsetTable[0] = num; for (unsigned int i=0; i < VImageDimension; i++) { num *= bufferSize[i]; + // m_OffsetTable[i+1] = (OffsetValueType)num; m_OffsetTable[i+1] = num; } + // if( num > NumericTraits<SizeValueType>::max() ) + // { + // itkExceptionMacro(<< "Requested number of pixels (" << num + // << ") is greater than the largest possible number of pixels (" << NumericTraits<SizeValueType>::max() << ")."); + // } } diff --git a/Utilities/ITK/Code/Common/itkImageFunction.h b/Utilities/ITK/Code/Common/itkImageFunction.h index 21167aa3f100286d735f476c50fe39e05241d007..3df0b84d891d0e4cd7b2649801f5c35f1742b7bc 100644 --- a/Utilities/ITK/Code/Common/itkImageFunction.h +++ b/Utilities/ITK/Code/Common/itkImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageFunction.h,v $ Language: C++ - Date: $Date: 2009-05-07 14:03:42 $ - Version: $Revision: 1.48 $ + Date: $Date: 2009-06-01 13:39:10 $ + Version: $Revision: 1.49 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -160,8 +160,12 @@ public: { return false; } +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + if( index[j] >= m_EndContinuousIndex[j] ) +#else if( index[j] > m_EndContinuousIndex[j] ) - { +#endif + { return false; } } diff --git a/Utilities/ITK/Code/Common/itkImageRegion.h b/Utilities/ITK/Code/Common/itkImageRegion.h index f11932fed0f23498c3c794d3c947167ba17ae64c..937a989a5b4abd532c538191bb12f94457a7ba8e 100644 --- a/Utilities/ITK/Code/Common/itkImageRegion.h +++ b/Utilities/ITK/Code/Common/itkImageRegion.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageRegion.h,v $ Language: C++ - Date: $Date: 2009-05-13 15:27:49 $ - Version: $Revision: 1.32 $ + Date: $Date: 2009-07-12 23:19:57 $ + Version: $Revision: 1.35 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -68,19 +68,22 @@ public: /** Dimension one lower than the image unless the image is one dimensional in which case the SliceDimension is also one dimensional. */ itkStaticConstMacro(SliceDimension, unsigned int, - (VImageDimension - (VImageDimension > 1))); + (ImageDimension - (ImageDimension > 1))); /** Dimension of the image available at run time. */ static unsigned int GetImageDimension() - { return VImageDimension; } + { return ImageDimension; } /** Index typedef support. An index is used to access pixel values. */ - typedef Index<VImageDimension> IndexType; - typedef typename IndexType::IndexValueType IndexValueType; + typedef Index< itkGetStaticConstMacro( ImageDimension) > IndexType; + typedef typename IndexType::IndexValueType IndexValueType; + typedef IndexValueType IndexValueArrayType[ ImageDimension]; + typedef typename IndexType::OffsetType OffsetType; + typedef typename OffsetType::OffsetValueType OffsetValueType; /** Size typedef support. A size is used to define region bounds. */ - typedef Size<VImageDimension> SizeType; - typedef typename SizeType::SizeValueType SizeValueType; + typedef Size< itkGetStaticConstMacro( ImageDimension ) > SizeType; + typedef typename SizeType::SizeValueType SizeValueType; /** Slice region typedef. SliceRegion is one dimension less than Self. */ typedef ImageRegion<itkGetStaticConstMacro(SliceDimension)> SliceRegion; @@ -245,13 +248,13 @@ public: /** Get the number of pixels contained in this region. This just * multiplies the size components. */ - unsigned long GetNumberOfPixels() const; + SizeValueType GetNumberOfPixels() const; /** Pad an image region by the specified radius. Region can be padded * uniformly in all dimensions or can be padded by different amounts * in each dimension. */ - void PadByRadius(unsigned long radius); - void PadByRadius(const unsigned long radius[VImageDimension]); + void PadByRadius(IndexValueType radius); + void PadByRadius(const IndexValueArrayType radius); void PadByRadius(const SizeType &radius); /** Crop a region by another region. If this region is outside of the diff --git a/Utilities/ITK/Code/Common/itkImageRegion.txx b/Utilities/ITK/Code/Common/itkImageRegion.txx index 3873ef88432d562ac9d6793098eacd74df25f8b6..359eb43cf51e38bf5ce09df384cd642e4c456d5e 100644 --- a/Utilities/ITK/Code/Common/itkImageRegion.txx +++ b/Utilities/ITK/Code/Common/itkImageRegion.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageRegion.txx,v $ Language: C++ - Date: $Date: 2008-10-18 21:13:25 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-07-12 10:52:52 $ + Version: $Revision: 1.22 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -46,7 +46,7 @@ ImageRegion<VImageDimension> } template<unsigned int VImageDimension> -unsigned long +typename ImageRegion<VImageDimension>::SizeValueType ImageRegion<VImageDimension> ::GetNumberOfPixels() const { @@ -76,9 +76,9 @@ ImageRegion<VImageDimension> template<unsigned int VImageDimension> void ImageRegion<VImageDimension> -::PadByRadius(unsigned long radius) +::PadByRadius( IndexValueType radius) { - unsigned long radiusVector[VImageDimension]; + SizeType radiusVector; for (unsigned int i=0; i < VImageDimension; ++i) { @@ -93,18 +93,22 @@ void ImageRegion<VImageDimension> ::PadByRadius(const SizeType &radius) { - this->PadByRadius( radius.GetSize() ); + for (unsigned int i = 0; i < VImageDimension; i++) + { + m_Size[i] += 2 * radius[i]; + m_Index[i] -= static_cast<IndexValueType>(radius[i]); + } } template<unsigned int VImageDimension> void ImageRegion<VImageDimension> -::PadByRadius(const unsigned long radius[VImageDimension]) +::PadByRadius(const IndexValueArrayType radius) { for (unsigned int i = 0; i < VImageDimension; i++) { m_Size[i] += 2 * radius[i]; - m_Index[i] -= static_cast<long>(radius[i]); + m_Index[i] -= static_cast<IndexValueType>(radius[i]); } } @@ -123,13 +127,13 @@ ImageRegion<VImageDimension> // Is left edge of current region to the right of the right edge // of the region to crop with? (if so, we cannot crop) if (m_Index[i] >= region.GetIndex()[i] - + static_cast<long>(region.GetSize()[i])) + + static_cast<IndexValueType>(region.GetSize()[i])) { cropPossible = false; } // If right edge of the current region to the left of the left // edge of the region to crop with? (if so, we cannot crop) - if (m_Index[i] + static_cast<long>(m_Size[i]) <= region.GetIndex()[i]) + if (m_Index[i] + static_cast<IndexValueType>(m_Size[i]) <= region.GetIndex()[i]) { cropPossible = false; } diff --git a/Utilities/ITK/Code/Common/itkImageRegionMultidimensionalSplitter.h b/Utilities/ITK/Code/Common/itkImageRegionMultidimensionalSplitter.h index b511a987786bab8fa330ddde78fc427b54adb015..ce2cb7a79638403a2a06a88558c8e68108db3a5b 100644 --- a/Utilities/ITK/Code/Common/itkImageRegionMultidimensionalSplitter.h +++ b/Utilities/ITK/Code/Common/itkImageRegionMultidimensionalSplitter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageRegionMultidimensionalSplitter.h,v $ Language: C++ - Date: $Date: 2008-10-18 21:13:25 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-08-17 13:39:47 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -36,12 +36,13 @@ namespace itk * series of smaller requests of the pipeline. This object has two * basic methods: GetNumberOfSplits() and GetSplit(). * + * GetNumberOfSplits() is used to determine how may subregions a given * region can be divided. You call GetNumberOfSplits with an argument * that is the number of subregions you want. If the image region can * support that number of subregions, that number is returned. - * Otherwise, the maximum number of splits a region can support will - * be returned. For example, if a region splitter class only divides + * Otherwise, the maximum number of splits less then or equal to the + * argumen be returned. For example, if a region splitter class only divides * a region into horizontal slabs, then the maximum number of splits * will be the number of rows in the region. * @@ -94,7 +95,7 @@ public: unsigned int requestedNumber); /** Get a region definition that represents the ith piece a specified region. - * The "numberOfPieces" specified should be less than or equal to what + * The "numberOfPieces" must be equal to what * GetNumberOfSplits() returns. */ virtual RegionType GetSplit(unsigned int i, unsigned int numberOfPieces, const RegionType ®ion); diff --git a/Utilities/ITK/Code/Common/itkImageRegionSplitter.h b/Utilities/ITK/Code/Common/itkImageRegionSplitter.h index 707b36719f0cd06208309fb3ea4af9feb02f2c54..7fedc919499573330084121da4db7bff46a4e3c4 100644 --- a/Utilities/ITK/Code/Common/itkImageRegionSplitter.h +++ b/Utilities/ITK/Code/Common/itkImageRegionSplitter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageRegionSplitter.h,v $ Language: C++ - Date: $Date: 2008-10-18 21:13:25 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-08-17 13:39:44 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -40,8 +40,8 @@ namespace itk * region can be divided. You call GetNumberOfSplits with an argument * that is the number of subregions you want. If the image region can * support that number of subregions, that number is returned. - * Otherwise, the maximum number of splits a region can support will - * be returned. For example, if a region splitter class only divides + * Otherwise, the maximum number of splits less then or equal to the + * argumen be returned. For example, if a region splitter class only divides * a region into horizontal slabs, then the maximum number of splits * will be the number of rows in the region. * @@ -106,7 +106,7 @@ public: unsigned int requestedNumber); /** Get a region definition that represents the ith piece a specified region. - * The "numberOfPieces" specified should be less than or equal to what + * The "numberOfPieces" must be equal to what * GetNumberOfSplits() returns. */ virtual RegionType GetSplit(unsigned int i, unsigned int numberOfPieces, const RegionType ®ion); diff --git a/Utilities/ITK/Code/Common/itkImageSliceConstIteratorWithIndex.h b/Utilities/ITK/Code/Common/itkImageSliceConstIteratorWithIndex.h index d45b07dc60d2a331b4c5d80643eac8710cddefe4..b50ddeffdc5c98c8acf2978276a654c144490fa6 100644 --- a/Utilities/ITK/Code/Common/itkImageSliceConstIteratorWithIndex.h +++ b/Utilities/ITK/Code/Common/itkImageSliceConstIteratorWithIndex.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageSliceConstIteratorWithIndex.h,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:57 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-08-14 20:48:00 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -163,6 +163,9 @@ public: * \sa operator++ \sa EndOfLine \sa End \sa NextSlice */ void NextLine(void); + /** Go to the first pixel of the current slice */ + void GoToBeginOfSlice(void); + /** Go to the next slice * \sa operator++ \sa EndOfLine \sa End */ void NextSlice(void); diff --git a/Utilities/ITK/Code/Common/itkImageSliceConstIteratorWithIndex.txx b/Utilities/ITK/Code/Common/itkImageSliceConstIteratorWithIndex.txx index f855f8132f474a7323df004cb5a0529ff0eec514..5f04a503b2d6f68bb6485c34d53718f62ff79e2d 100644 --- a/Utilities/ITK/Code/Common/itkImageSliceConstIteratorWithIndex.txx +++ b/Utilities/ITK/Code/Common/itkImageSliceConstIteratorWithIndex.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageSliceConstIteratorWithIndex.txx,v $ Language: C++ - Date: $Date: 2009-02-05 19:04:57 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-08-14 20:48:00 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -59,20 +59,35 @@ ImageSliceConstIteratorWithIndex<TImage> } //---------------------------------------------------------------------- -// Advance to next slice +// Go to the first pixel of the current slice //---------------------------------------------------------------------- template<class TImage> void ImageSliceConstIteratorWithIndex<TImage> -::NextSlice(void) +::GoToBeginOfSlice(void) { - // Move to beginning of Slice this->m_PositionIndex[m_Direction_B] = this->m_BeginIndex[m_Direction_B]; this->m_Position -= m_LineJump * ( this->m_EndIndex[ m_Direction_B ] - this->m_BeginIndex[ m_Direction_B ] ); +} + +//---------------------------------------------------------------------- +// Advance to next slice +//---------------------------------------------------------------------- +template<class TImage> +void +ImageSliceConstIteratorWithIndex<TImage> +::NextSlice(void) +{ + + // Move to beginning of Slice + this->m_Position -= m_LineJump * + ( this->m_PositionIndex[ m_Direction_B ] - this->m_BeginIndex[ m_Direction_B ] ); + this->m_PositionIndex[m_Direction_B] = this->m_BeginIndex[m_Direction_B]; + for( unsigned int n=0; n<TImage::ImageDimension; n++ ) { diff --git a/Utilities/ITK/Code/Common/itkImageSource.txx b/Utilities/ITK/Code/Common/itkImageSource.txx index fe588b56b71fae2c76f337f01b63a873e1bf1ebb..d97f6435547435d3acb4c623800eebff81eacfb0 100644 --- a/Utilities/ITK/Code/Common/itkImageSource.txx +++ b/Utilities/ITK/Code/Common/itkImageSource.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageSource.txx,v $ Language: C++ - Date: $Date: 2009-04-05 10:56:39 $ - Version: $Revision: 1.67 $ + Date: $Date: 2009-08-26 19:09:35 $ + Version: $Revision: 1.68 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -84,8 +84,12 @@ typename ImageSource<TOutputImage>::OutputImageType * ImageSource<TOutputImage> ::GetOutput(unsigned int idx) { - return dynamic_cast<TOutputImage*> + TOutputImage* out = dynamic_cast<TOutputImage*> (this->ProcessObject::GetOutput(idx)); + if ( out == NULL ) { + itkWarningMacro ( << "dynamic_cast to output type failed" ); + } + return out; } /** diff --git a/Utilities/ITK/Code/Common/itkIndex.h b/Utilities/ITK/Code/Common/itkIndex.h index 343279692d9974e6016279580283111f3305a906..83e4fe5b11c8973829293cac6c5d5fdaa735b325 100644 --- a/Utilities/ITK/Code/Common/itkIndex.h +++ b/Utilities/ITK/Code/Common/itkIndex.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkIndex.h,v $ Language: C++ - Date: $Date: 2009-05-17 02:31:26 $ - Version: $Revision: 1.62 $ + Date: $Date: 2009-07-12 10:52:52 $ + Version: $Revision: 1.64 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -240,7 +240,7 @@ public: * \warning No bound checking is performed * \sa GetIndex() * \sa SetElement() */ - IndexValueType GetElement( unsigned long element ) + IndexValueType GetElement( unsigned long element ) const { return m_Index[ element ]; } /** Return a basis vector of the form [0, ..., 0, 1, 0, ... 0] where the "1" @@ -260,20 +260,6 @@ public: * Index<3> index = {5, 2, 7}; */ IndexValueType m_Index[VIndexDimension]; -#ifndef ITK_USE_PORTABLE_ROUND - // The Windows implementaton of vnl_math_rnd() does not round the - // same way as other versions. It has an assembly "fast" implementation - // but with the drawback of rounding to the closest even number. - // See: http://www.musicdsp.org/showone.php?id=170 - // For example 0.5 is rounded down to 0.0. - // This conditional code replaces the standard vnl implementation that uses - // assembler code. The code below will be slower for windows but will - // produce consistent results. This can be removed once vnl_math_rnd is - // fixed in VXL. -#if (defined (VCL_VC) && !defined(__GCCXML__)) || (defined(_MSC_VER) && (_MSC_VER <= 1310)) -#define vnl_math_rnd_halfintup(x) ((x>=0.0)?(int)(x + 0.5):(int)(x - 0.5)) -#endif -#endif /** Copy values from a FixedArray by rounding each one of the components */ template <class TCoordRep> inline void CopyWithRound( const FixedArray<TCoordRep,VIndexDimension> & point ) @@ -283,19 +269,10 @@ public: #else for(unsigned int i=0;i < VIndexDimension; ++i) { -#ifdef ITK_USE_PORTABLE_ROUND m_Index[i] = static_cast< IndexValueType>( itk::Math::Round( point[i] ) ); -#else - m_Index[i] = static_cast< IndexValueType>( vnl_math_rnd_halfintup( point[i] ) ); -#endif } #endif } -#ifndef ITK_USE_PORTABLE_ROUND -#if (defined (VCL_VC) && !defined(__GCCXML__)) || (defined(_MSC_VER) && (_MSC_VER <= 1310)) -#undef vnl_math_rnd_halfintup -#endif -#endif /** Copy values from a FixedArray by casting each one of the components */ template <class TCoordRep> diff --git a/Utilities/ITK/Code/Common/itkLineConstIterator.txx b/Utilities/ITK/Code/Common/itkLineConstIterator.txx index 675ae3079748118a765713a07eef31ec306b55ec..532883ee95e2319cbba5e48618d77c76bd53d59b 100644 --- a/Utilities/ITK/Code/Common/itkLineConstIterator.txx +++ b/Utilities/ITK/Code/Common/itkLineConstIterator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLineConstIterator.txx,v $ Language: C++ - Date: $Date: 2009-02-05 19:05:01 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-07-12 10:52:52 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -43,7 +43,7 @@ LineConstIterator<TImage> int maxDistanceDimension = 0; for (i = 0; i < TImage::ImageDimension; ++i) { - IndexValueType distance = vcl_abs(difference[i]); + IndexValueType distance = vnl_math_abs(difference[i]); if (distance > maxDistance) { maxDistance = distance; diff --git a/Utilities/ITK/Code/Common/itkLinearInterpolateImageFunction.h b/Utilities/ITK/Code/Common/itkLinearInterpolateImageFunction.h index 432c9b39c9beb46bdce6539678dc62c0c63a3964..1890a95503904363123dd220291007a9823f0123 100644 --- a/Utilities/ITK/Code/Common/itkLinearInterpolateImageFunction.h +++ b/Utilities/ITK/Code/Common/itkLinearInterpolateImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLinearInterpolateImageFunction.h,v $ Language: C++ - Date: $Date: 2009-03-20 10:25:36 $ - Version: $Revision: 1.36 $ + Date: $Date: 2009-07-29 07:38:01 $ + Version: $Revision: 1.37 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,7 +22,7 @@ // gets integrated into the main directories. #include "itkConfigure.h" -#if defined( ITK_USE_OPTIMIZED_REGISTRATION_METHODS ) && defined( LINEAR_INTERPOLATOR_FIXED ) +#ifdef ITK_USE_OPTIMIZED_REGISTRATION_METHODS #include "itkOptLinearInterpolateImageFunction.h" #else diff --git a/Utilities/ITK/Code/Common/itkLinearInterpolateImageFunction.txx b/Utilities/ITK/Code/Common/itkLinearInterpolateImageFunction.txx index 62ced264fc1f0f1b0f3fdfecf6e0840868b61ff0..9ef4e89daa50b715f04646e51feccf7b563ac3ed 100644 --- a/Utilities/ITK/Code/Common/itkLinearInterpolateImageFunction.txx +++ b/Utilities/ITK/Code/Common/itkLinearInterpolateImageFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLinearInterpolateImageFunction.txx,v $ Language: C++ - Date: $Date: 2009-05-07 14:03:45 $ - Version: $Revision: 1.42 $ + Date: $Date: 2009-07-29 07:38:01 $ + Version: $Revision: 1.43 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -23,7 +23,7 @@ #include "itkConfigure.h" // Second, redirect to the optimized version if necessary -#if defined( ITK_USE_OPTIMIZED_REGISTRATION_METHODS ) && defined( LINEAR_INTERPOLATOR_FIXED ) +#ifdef ITK_USE_OPTIMIZED_REGISTRATION_METHODS #include "itkOptLinearInterpolateImageFunction.txx" #else @@ -85,27 +85,11 @@ LinearInterpolateImageFunction< TInputImage, TCoordRep > */ signed long baseIndex[ImageDimension]; double distance[ImageDimension]; - long tIndex; for( dim = 0; dim < ImageDimension; dim++ ) { - // The following "if" block is equivalent to the following line without - // having to call floor. - // baseIndex[dim] = (long) vcl_floor(index[dim] ); - if (index[dim] >= 0.0) - { - baseIndex[dim] = (long) index[dim]; - } - else - { - tIndex = (long) index[dim]; - if (double(tIndex) != index[dim]) - { - tIndex--; - } - baseIndex[dim] = tIndex; - } - distance[dim] = index[dim] - double( baseIndex[dim] ); + baseIndex[dim] = Math::Floor( index[dim] ); + distance[dim] = index[dim] - static_cast< double >( baseIndex[dim] ); } /** diff --git a/Utilities/ITK/Code/Common/itkMacro.h b/Utilities/ITK/Code/Common/itkMacro.h index 28389a8adef267fcf740b31b046c421b3ba14e0b..48049b76f277d36f0da57997947738dbcce8a347 100644 --- a/Utilities/ITK/Code/Common/itkMacro.h +++ b/Utilities/ITK/Code/Common/itkMacro.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMacro.h,v $ Language: C++ - Date: $Date: 2009-05-26 23:45:03 $ - Version: $Revision: 1.96 $ + Date: $Date: 2009-06-16 07:58:46 $ + Version: $Revision: 1.97 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -980,6 +980,10 @@ inline int RoundHalfIntegerToEven(float x) { return vnl_math_rnd_halfinttoeven inline int RoundHalfIntegerToEven(double x) { return vnl_math_rnd_halfinttoeven(x); } inline int Round(float x) { return RoundHalfIntegerUp(x); } inline int Round(double x) { return RoundHalfIntegerUp(x); } +inline int Floor(float x) { return vnl_math_floor(x); } +inline int Floor(double x) { return vnl_math_floor(x); } +inline int Ceil(float x) { return vnl_math_ceil(x); } +inline int Ceil(double x) { return vnl_math_ceil(x); } } // end namespace Math } // end namespace itk @@ -1010,19 +1014,11 @@ inline int Round(double x) { return RoundHalfIntegerUp(x); } // perfomed as part of the assignment, by using the DestinationElementType as // the casting type. // Source and destination array types must have defined opearator[] in their API. -#ifdef ITK_USE_PORTABLE_ROUND #define itkForLoopRoundingAndAssignmentMacro(DestinationType,Sourcrnd_halfintup,DestinationElementType,DestinationArray,SourceArray,NumberOfIterations) \ for(unsigned int i=0;i < NumberOfIterations; ++i) \ { \ DestinationArray[i] = static_cast< DestinationElementType >( itk::Math::Round( SourceArray[i] ) ); \ } -#else -#define itkForLoopRoundingAndAssignmentMacro(DestinationType,SourceType,DestinationElementType,DestinationArray,SourceArray,NumberOfIterations) \ - for(unsigned int i=0;i < NumberOfIterations; ++i) \ - { \ - DestinationArray[i] = static_cast< DestinationElementType >( itk::Math::RoundHalfIntegerUp( SourceArray[i] ) ); \ - } -#endif #endif // end of Template Meta Programming helper macros diff --git a/Utilities/ITK/Code/Common/itkMersenneTwisterRandomVariateGenerator.h b/Utilities/ITK/Code/Common/itkMersenneTwisterRandomVariateGenerator.h index ab7ce07509e027e53c1d7049af462f5519ffe006..4885b7bdade4ad760929961831ebb3b6e58950fb 100755 --- a/Utilities/ITK/Code/Common/itkMersenneTwisterRandomVariateGenerator.h +++ b/Utilities/ITK/Code/Common/itkMersenneTwisterRandomVariateGenerator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMersenneTwisterRandomVariateGenerator.h,v $ Language: C++ - Date: $Date: 2009-02-06 20:53:05 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-08-08 15:25:34 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -36,6 +36,8 @@ namespace Statistics { /** \class MersenneTwisterRandomVariateGenerator * \brief MersenneTwisterRandom random variate generator * + * \warning This class is NOT thread-safe. + * * This notice was included with the original implementation. * The only changes made were to obfuscate the author's email addresses. * @@ -501,7 +503,7 @@ MersenneTwisterRandomVariateGenerator::GetNormalVariate( // Return a real number from a normal (Gaussian) distribution with given // mean and variance by Box-Muller method double r = vcl_sqrt( -2.0 * vcl_log( 1.0-GetVariateWithOpenRange()) * variance); - double phi = 2.0 * 3.14159265358979323846264338328 + double phi = 2.0 * vnl_math::pi * GetVariateWithOpenUpperRange(); return mean + r * vcl_cos(phi); } diff --git a/Utilities/ITK/Code/Common/itkMesh.h b/Utilities/ITK/Code/Common/itkMesh.h index 6d2fb3d5ce97a524ae466a43d6900a43c3eb48eb..e3d437d19dcb5dba02f9dd07c7283e1955306f30 100644 --- a/Utilities/ITK/Code/Common/itkMesh.h +++ b/Utilities/ITK/Code/Common/itkMesh.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMesh.h,v $ Language: C++ - Date: $Date: 2008-06-16 02:07:16 $ - Version: $Revision: 1.97 $ + Date: $Date: 2009-06-21 16:25:08 $ + Version: $Revision: 1.98 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -173,6 +173,7 @@ public: /** Create types that are pointers to each of the container types. */ typedef typename PointsContainer::Pointer PointsContainerPointer; typedef typename CellsContainer::Pointer CellsContainerPointer; + typedef typename CellsContainer::ConstPointer CellsContainerConstPointer; typedef typename CellLinksContainer::Pointer CellLinksContainerPointer; typedef typename PointDataContainer::Pointer PointDataContainerPointer; typedef typename CellDataContainer::Pointer CellDataContainerPointer; @@ -310,23 +311,23 @@ public: * cell identifiers */ void SetCellLinks(CellLinksContainer*); #ifndef CABLE_CONFIGURATION - CellLinksContainerPointer GetCellLinks(); - const CellLinksContainerPointer GetCellLinks() const; + CellLinksContainer * GetCellLinks(); + const CellLinksContainer * GetCellLinks() const; /** Access m_CellsContainer, which holds cells used by the mesh. * Individual cells are accessed through cell identifiers. */ void SetCells(CellsContainer*); - CellsContainerPointer GetCells(); - const CellsContainerPointer GetCells() const; + CellsContainer * GetCells(); + const CellsContainer * GetCells() const; #endif /** Access m_CellDataContainer, which contains data associated with * the mesh's cells. Optionally, this can be NULL, indicating that * no data are associated with the cells. The data for a cell can * be accessed through its cell identifier. */ void SetCellData(CellDataContainer*); - CellDataContainerPointer GetCellData(); - const CellDataContainerPointer GetCellData() const; + CellDataContainer * GetCellData(); + const CellDataContainer * GetCellData() const; /** * Set/get the BoundaryAssignmentsContainer for a given dimension. diff --git a/Utilities/ITK/Code/Common/itkMesh.txx b/Utilities/ITK/Code/Common/itkMesh.txx index c945db8e640ddcb157e906a4ff58a9dc7463cfdf..f0e868de89b35da4c82fe95b41b414b61016397e 100644 --- a/Utilities/ITK/Code/Common/itkMesh.txx +++ b/Utilities/ITK/Code/Common/itkMesh.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMesh.txx,v $ Language: C++ - Date: $Date: 2008-07-12 00:10:13 $ - Version: $Revision: 1.101 $ + Date: $Date: 2009-06-21 23:14:45 $ + Version: $Revision: 1.103 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -40,14 +40,14 @@ Mesh<TPixelType, VDimension, TMeshTraits> << ((m_CellLinksContainer) ? m_CellLinksContainer->Size() : 0) << std::endl; os << indent << "Number Of Cells: " << ((m_CellsContainer) ? m_CellsContainer->Size() : 0) << std::endl; + os << indent << "Cell Data Container pointer: " + << ((m_CellDataContainer) ? m_CellDataContainer.GetPointer() : 0) << std::endl; os << indent << "Size of Cell Data Container: " << ((m_CellDataContainer) ? m_CellDataContainer->Size() : 0) << std::endl; os << indent << "Number of explicit cell boundary assignments: " << static_cast<unsigned long>( m_BoundaryAssignmentsContainers.size() ) << std::endl; - os << indent << "CellsAllocationMethod: " << m_CellsAllocationMethod << std::endl; - } @@ -71,7 +71,7 @@ Mesh<TPixelType, VDimension, TMeshTraits> * Access routines to get the cell links container. */ template <typename TPixelType, unsigned int VDimension, typename TMeshTraits> -typename Mesh<TPixelType, VDimension, TMeshTraits>::CellLinksContainerPointer +typename Mesh<TPixelType, VDimension, TMeshTraits>::CellLinksContainer * Mesh<TPixelType, VDimension, TMeshTraits> ::GetCellLinks() { @@ -80,7 +80,7 @@ Mesh<TPixelType, VDimension, TMeshTraits> return m_CellLinksContainer; } template <typename TPixelType, unsigned int VDimension, typename TMeshTraits> -const typename Mesh<TPixelType, VDimension, TMeshTraits>::CellLinksContainerPointer +const typename Mesh<TPixelType, VDimension, TMeshTraits>::CellLinksContainer * Mesh<TPixelType, VDimension, TMeshTraits> ::GetCellLinks() const { @@ -112,7 +112,7 @@ Mesh<TPixelType, VDimension, TMeshTraits> * Access routines to get the cells container. */ template <typename TPixelType, unsigned int VDimension, typename TMeshTraits> -typename Mesh<TPixelType, VDimension, TMeshTraits>::CellsContainerPointer +typename Mesh<TPixelType, VDimension, TMeshTraits>::CellsContainer * Mesh<TPixelType, VDimension, TMeshTraits> ::GetCells() { @@ -120,7 +120,7 @@ Mesh<TPixelType, VDimension, TMeshTraits> return m_CellsContainer; } template <typename TPixelType, unsigned int VDimension, typename TMeshTraits> -const typename Mesh<TPixelType, VDimension, TMeshTraits>::CellsContainerPointer +const typename Mesh<TPixelType, VDimension, TMeshTraits>::CellsContainer * Mesh<TPixelType, VDimension, TMeshTraits> ::GetCells() const { @@ -150,7 +150,7 @@ Mesh<TPixelType, VDimension, TMeshTraits> * Access routines to get the cell data container. */ template <typename TPixelType, unsigned int VDimension, typename TMeshTraits> -typename Mesh<TPixelType, VDimension, TMeshTraits>::CellDataContainerPointer +typename Mesh<TPixelType, VDimension, TMeshTraits>::CellDataContainer * Mesh<TPixelType, VDimension, TMeshTraits> ::GetCellData() { @@ -159,7 +159,7 @@ Mesh<TPixelType, VDimension, TMeshTraits> return m_CellDataContainer; } template <typename TPixelType, unsigned int VDimension, typename TMeshTraits> -const typename Mesh<TPixelType, VDimension, TMeshTraits>::CellDataContainerPointer +const typename Mesh<TPixelType, VDimension, TMeshTraits>::CellDataContainer * Mesh<TPixelType, VDimension, TMeshTraits> ::GetCellData() const { diff --git a/Utilities/ITK/Code/Common/itkMetaDataObject.h b/Utilities/ITK/Code/Common/itkMetaDataObject.h index 3fb6effb868766d47f9861c6253325c0de221f21..45b04a2a14fbb7c7318a34687b1a0b6982020d35 100644 --- a/Utilities/ITK/Code/Common/itkMetaDataObject.h +++ b/Utilities/ITK/Code/Common/itkMetaDataObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaDataObject.h,v $ Language: C++ - Date: $Date: 2009-04-05 10:56:41 $ - Version: $Revision: 1.26 $ + Date: $Date: 2009-06-14 09:20:22 $ + Version: $Revision: 1.27 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -118,7 +118,7 @@ public: /** * \author Hans J. Johnson * Function to set the stored value of type MetaDataObjectType. - * \param A constant reference to at MetaDataObjectType. + * \param NewValue A constant reference to at MetaDataObjectType. */ void SetMetaDataObjectValue(const MetaDataObjectType & NewValue ); /** @@ -140,7 +140,9 @@ private: /** * EncapsulateMetaData is a convenience function that encapsulates raw MetaData into a * MetaDataObject that can be put into the MetaDataDictionary. - * \param value the value of type T that is to be encapsulated. + * \param Dictionary TODO + * \param key TODO + * \param invalue the value of type T that is to be encapsulated. * \return A smartpointer ot a MetaDataObject that is suitable for * insertion into a MetaDataDictionary. */ diff --git a/Utilities/ITK/Code/Common/itkMultiThreader.h b/Utilities/ITK/Code/Common/itkMultiThreader.h index 83296f9f981a54c86b5639ee14f2a2000bcd741b..4482695932d564bc4d0ad88c7ea3cac099d2f0eb 100644 --- a/Utilities/ITK/Code/Common/itkMultiThreader.h +++ b/Utilities/ITK/Code/Common/itkMultiThreader.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultiThreader.h,v $ Language: C++ - Date: $Date: 2009-04-25 12:24:09 $ - Version: $Revision: 1.31 $ + Date: $Date: 2009-06-14 08:50:53 $ + Version: $Revision: 1.32 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -66,7 +66,8 @@ namespace itk * If ITK_USE_SPROC is defined, then sproc() will be used to create * multiple threads on an SGI. If ITK_USE_PTHREADS is defined, then * pthread_create() will be used to create multiple threads (on - * a sun, for example). */ + * a sun, for example). + */ // The maximum number of threads allowed #ifdef ITK_USE_SPROC diff --git a/Utilities/ITK/Code/Common/itkNearestNeighborExtrapolateImageFunction.h b/Utilities/ITK/Code/Common/itkNearestNeighborExtrapolateImageFunction.h index c908fba95d758493750634f97429abbeb40c0971..ed6a97d8ebdf8407336cb0506f2b4dadd644c467 100644 --- a/Utilities/ITK/Code/Common/itkNearestNeighborExtrapolateImageFunction.h +++ b/Utilities/ITK/Code/Common/itkNearestNeighborExtrapolateImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNearestNeighborExtrapolateImageFunction.h,v $ Language: C++ - Date: $Date: 2009-05-16 16:05:13 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-08-08 14:29:02 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -82,22 +82,15 @@ public: IndexType nindex; for ( unsigned int j = 0; j < ImageDimension; j++ ) { - if ( index[j] < this->GetStartContinuousIndex()[j] ) + nindex[j] = static_cast<ValueType>( itk::Math::RoundHalfIntegerUp( index[j] ) ); + if ( nindex[j] < this->GetStartIndex()[j] ) { nindex[j] = this->GetStartIndex()[j]; } - else if ( index[j] > this->GetEndContinuousIndex()[j] ) + else if ( nindex[j] > this->GetEndIndex()[j] ) { nindex[j] = this->GetEndIndex()[j]; } - else - { -#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY - nindex[j] = static_cast<ValueType>( itk::Math::RoundHalfIntegerUp( index[j] ) ); -#else - nindex[j] = static_cast<ValueType>( vnl_math_rnd_halfintup( index[j] ) ); -#endif - } } return static_cast<OutputType>( this->GetInputImage()->GetPixel( nindex ) ); } diff --git a/Utilities/ITK/Code/Common/itkNumericTraits.h b/Utilities/ITK/Code/Common/itkNumericTraits.h index a9d03858225b5bb25b87fe0d94b0ae4a9b972c24..9cc93715e339433974ae29642b9ad1ff07990932 100644 --- a/Utilities/ITK/Code/Common/itkNumericTraits.h +++ b/Utilities/ITK/Code/Common/itkNumericTraits.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNumericTraits.h,v $ Language: C++ - Date: $Date: 2009-02-07 23:09:24 $ - Version: $Revision: 1.56 $ + Date: $Date: 2009-07-12 10:48:39 $ + Version: $Revision: 1.58 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -39,7 +39,7 @@ namespace itk * * NumericTraits is used to extend the traits associated with native types * such as float, char, int, and so on. These traits are extensions of the - * standard <numeric_limits> defined by the C++ compilers. Some of the added + * standard numeric_limits defined by the C++ compilers. Some of the added * traits include minimum and maximum value; accumulation type; etc. * * \ingroup DataRepresentation @@ -621,6 +621,42 @@ public: }; +#if 0 +#ifndef ITK_TYPE_SAME_LONG_AND___INT64 +/** \class NumericTraits< __int64 > + * \brief Define traits for type std::complex<double>. + * \ingroup DataRepresentation + */ +template <> +class NumericTraits< __int64 > { +public: + typedef __int64 TheType; + typedef __int64 ValueType; + typedef TheType PrintType; + typedef __int64 AbsType; + typedef TheType AccumulateType; + typedef double RealType; + typedef double ScalarRealType; + typedef double FloatType; + + static const TheType ITKCommon_EXPORT Zero; + static const TheType ITKCommon_EXPORT One; + + static TheType min( TheType ) { return vcl_numeric_limits<ValueType>::min(); } + static TheType max( TheType ) { return vcl_numeric_limits<ValueType>::max(); } + static TheType NonpositiveMin() { + return TheType(-NumericTraits<double>::NonpositiveMin(),0.0); } + static bool IsPositive(TheType val) { return val.real() > 0.0; } + static bool IsNonpositive(TheType val) { return val.real() <= 0.0; } + static bool IsNegative(TheType val) { return val.real() < 0.0; } + static bool IsNonnegative(TheType val) {return val.real() >= 0.0; } + static TheType ZeroValue() { return Zero; } + static TheType OneValue() { return One; } +}; +#endif +#endif + + } // end namespace itk #endif // __itkNumericTraits_h diff --git a/Utilities/ITK/Code/Common/itkNumericTraitsRGBAPixel.h b/Utilities/ITK/Code/Common/itkNumericTraitsRGBAPixel.h index 21f2553a4036e28326e09e590fc08c858313d66a..6e0ecdba94191065d357a92a05bad67caf745409 100644 --- a/Utilities/ITK/Code/Common/itkNumericTraitsRGBAPixel.h +++ b/Utilities/ITK/Code/Common/itkNumericTraitsRGBAPixel.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNumericTraitsRGBAPixel.h,v $ Language: C++ - Date: $Date: 2009-02-06 20:53:13 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-07-30 20:51:30 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -52,15 +52,15 @@ public: \ \ typedef ElementRealType ScalarRealType; \ \ - static const RealType max( const Self & a ) \ + static const Self max( const Self & a ) \ { \ - RealType b; \ + Self b; \ b.Fill( NumericTraits< T >::max() ); \ return b; \ } \ - static const RealType min( const Self & a ) \ + static const Self min( const Self & a ) \ { \ - RealType b; \ + Self b; \ b.Fill( NumericTraits< T >::min() ); \ return b; \ } \ diff --git a/Utilities/ITK/Code/Common/itkNumericTraitsRGBPixel.h b/Utilities/ITK/Code/Common/itkNumericTraitsRGBPixel.h index 05bcbe9d28d4ff4474b0477ed2545cd6d128ccf5..48c587cfd23b0f476039cc4eec2aee83ce848553 100644 --- a/Utilities/ITK/Code/Common/itkNumericTraitsRGBPixel.h +++ b/Utilities/ITK/Code/Common/itkNumericTraitsRGBPixel.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNumericTraitsRGBPixel.h,v $ Language: C++ - Date: $Date: 2009-02-06 20:53:13 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-07-30 20:51:30 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -52,15 +52,15 @@ public: \ \ typedef ElementRealType ScalarRealType; \ \ - static const RealType max( const Self & a ) \ + static const Self max( const Self & a ) \ { \ - RealType b; \ + Self b; \ b.Fill( NumericTraits< T >::max() ); \ return b; \ } \ - static const RealType min( const Self & a ) \ + static const Self min( const Self & a ) \ { \ - RealType b; \ + Self b; \ b.Fill( NumericTraits< T >::min() ); \ return b; \ } \ diff --git a/Utilities/ITK/Code/Common/itkNumericTraitsVariableLengthVectorPixel.h b/Utilities/ITK/Code/Common/itkNumericTraitsVariableLengthVectorPixel.h index 4b22d56e6063b5d5247abaa8bcdfc2aaf4cb9abf..a4168b04b4864a65fb4581e5426a75ab05f2506e 100644 --- a/Utilities/ITK/Code/Common/itkNumericTraitsVariableLengthVectorPixel.h +++ b/Utilities/ITK/Code/Common/itkNumericTraitsVariableLengthVectorPixel.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNumericTraitsVariableLengthVectorPixel.h,v $ Language: C++ - Date: $Date: 2009-02-06 20:53:13 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-07-30 20:51:30 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -64,15 +64,15 @@ public: \ \ typedef ElementRealType ScalarRealType; \ \ - static const RealType max( const Self & a ) \ + static const Self max( const Self & a ) \ { \ - RealType b(a.Size()); \ + Self b(a.Size()); \ b.Fill( NumericTraits< T >::max() ); \ return b; \ } \ - static const RealType min( const Self & a ) \ + static const Self min( const Self & a ) \ { \ - RealType b(a.Size()); \ + Self b(a.Size()); \ b.Fill( NumericTraits< T >::min() ); \ return b; \ } \ diff --git a/Utilities/ITK/Code/Common/itkObjectFactoryBase.cxx b/Utilities/ITK/Code/Common/itkObjectFactoryBase.cxx index a8c0a25a32ce4fa1697ea2f493791b52d9901247..e404a7b7cb6511a8b407c63065343a6c65f27713 100644 --- a/Utilities/ITK/Code/Common/itkObjectFactoryBase.cxx +++ b/Utilities/ITK/Code/Common/itkObjectFactoryBase.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkObjectFactoryBase.cxx,v $ Language: C++ - Date: $Date: 2009-04-05 10:56:46 $ - Version: $Revision: 1.58 $ + Date: $Date: 2009-08-23 12:25:21 $ + Version: $Revision: 1.59 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -515,6 +515,7 @@ ObjectFactoryBase (*f)->UnRegister(); } // And delete the library handles all at once +#ifndef __CYGWIN__ for ( std::list<void *>::iterator lib = libs.begin(); lib != libs.end(); ++lib) @@ -524,6 +525,7 @@ ObjectFactoryBase DynamicLoader::CloseLibrary(static_cast<LibHandle>(*lib)); } } +#endif delete ObjectFactoryBase::m_RegisteredFactories; ObjectFactoryBase::m_RegisteredFactories = 0; } diff --git a/Utilities/ITK/Code/Common/itkPathConstIterator.h b/Utilities/ITK/Code/Common/itkPathConstIterator.h index 5432241f6c7c3366b4657cee4f7c0d2f8b71f2ab..bb273ba5e13cb1a1e71c8a44f437006b42bdaae7 100644 --- a/Utilities/ITK/Code/Common/itkPathConstIterator.h +++ b/Utilities/ITK/Code/Common/itkPathConstIterator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPathConstIterator.h,v $ Language: C++ - Date: $Date: 2004-11-01 21:16:31 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-07-12 10:52:52 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -216,7 +216,7 @@ protected: //made protected so other iterators can access SpacingType m_ImageSpacing; /** Size of the source image */ - const unsigned long int* m_ImageSize; + const SizeValueType * m_ImageSize; /** Should GoToBegin() initially skip the first index of a closed path so that * the first index will only be visited once--at the end of the path? If diff --git a/Utilities/ITK/Code/Common/itkPoint.h b/Utilities/ITK/Code/Common/itkPoint.h index fc3c8189431c86495cc3def6233267575cfd040a..76fcd9d26305a2bb2c10b41454f7eb127369a273 100644 --- a/Utilities/ITK/Code/Common/itkPoint.h +++ b/Utilities/ITK/Code/Common/itkPoint.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPoint.h,v $ Language: C++ - Date: $Date: 2009-03-03 15:07:54 $ - Version: $Revision: 1.68 $ + Date: $Date: 2009-06-14 11:52:00 $ + Version: $Revision: 1.69 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -151,7 +151,9 @@ public: /** Set the current point to a barycentric combination of the two points * given as arguments. * - * \param \f$ \alpha \f$ = weight for the first point + * \param A First point + * \param B Second point + * \param alpha Weight for the first point * * The first point is multiplied by \f$ \alpha \f$, the second is multiplied * by * \f$ (1-\alpha) \f$, and the sum is stored in the Point on which the diff --git a/Utilities/ITK/Code/Common/itkPointSet.txx b/Utilities/ITK/Code/Common/itkPointSet.txx index 66b967f36c8856e86c8db6df5efd03949ac9d7ce..fec17fb45fe549575c77efc2078a8974fd87d533 100644 --- a/Utilities/ITK/Code/Common/itkPointSet.txx +++ b/Utilities/ITK/Code/Common/itkPointSet.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPointSet.txx,v $ Language: C++ - Date: $Date: 2009-03-03 15:07:57 $ - Version: $Revision: 1.34 $ + Date: $Date: 2009-06-21 23:14:46 $ + Version: $Revision: 1.35 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -42,7 +42,10 @@ PointSet<TPixelType, VDimension, TMeshTraits> os << indent << "Buffered Region: " << m_BufferedRegion << std::endl; os << indent << "Maximum Number Of Regions: " << m_MaximumNumberOfRegions << std::endl; - + os << indent << "Point Data Container pointer: " + << ((this->m_PointDataContainer) ? this->m_PointDataContainer.GetPointer() : 0) << std::endl; + os << indent << "Size of Point Data Container: " + << ((this->m_PointDataContainer) ? this->m_PointDataContainer->Size() : 0) << std::endl; } diff --git a/Utilities/ITK/Code/Common/itkRGBAPixel.h b/Utilities/ITK/Code/Common/itkRGBAPixel.h index e167cb30f72aed94e961343380784660952db747..129a55253570962526bee9bbe95d7a0b02f7d066 100644 --- a/Utilities/ITK/Code/Common/itkRGBAPixel.h +++ b/Utilities/ITK/Code/Common/itkRGBAPixel.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRGBAPixel.h,v $ Language: C++ - Date: $Date: 2009-03-12 01:11:14 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-07-31 12:54:40 $ + Version: $Revision: 1.22 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -82,7 +82,8 @@ public: { this->Fill(r);} /** Pass-through constructor for the Array base class. */ - RGBAPixel(const Self& r): BaseArray(r) {} + template< class TRGBAPixelValueType > + RGBAPixel(const RGBAPixel< TRGBAPixelValueType >& r): BaseArray(r) {} RGBAPixel(const ComponentType r[4]): BaseArray(r) {} /** Pass-through assignment operator for the Array base class. */ diff --git a/Utilities/ITK/Code/Common/itkRigid3DTransform.h b/Utilities/ITK/Code/Common/itkRigid3DTransform.h index a6e6ceecad09ee02b38ae1965af6e9cf8070759f..f422bedc855469c075f1090e1e19d54b6687cd84 100644 --- a/Utilities/ITK/Code/Common/itkRigid3DTransform.h +++ b/Utilities/ITK/Code/Common/itkRigid3DTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRigid3DTransform.h,v $ Language: C++ - Date: $Date: 2009-04-09 09:23:21 $ - Version: $Revision: 1.40 $ + Date: $Date: 2009-06-17 12:17:38 $ + Version: $Revision: 1.41 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -37,7 +37,7 @@ namespace itk * methods or in serialized form using SetParameters() and SetFixedParameters(). * * The serialization of the optimizable parameters is an array of 12 elements. - * The first 9 parameters represents the rotation matrix in column-major order + * The first 9 parameters represents the rotation matrix in row-major order * (where the column index varies the fastest). The last 3 parameters defines * the translation in each dimension. * @@ -96,7 +96,7 @@ public: /** Set the transformation from a container of parameters * This is typically used by optimizers. * There are 12 parameters. The first 9 represents the rotation - * matrix is column-major order and the last 3 represents the translation. + * matrix is row-major order and the last 3 represents the translation. * * \warning The rotation matrix must be orthogonal to within a specified tolerance, * else an exception is thrown. diff --git a/Utilities/ITK/Code/Common/itkSimplexMesh.h b/Utilities/ITK/Code/Common/itkSimplexMesh.h index e422960ad4e7bf72715fb4e7cb7ebfaec5b001d0..a67a8c4254cfb5c3490b7888f19d165e2957c076 100644 --- a/Utilities/ITK/Code/Common/itkSimplexMesh.h +++ b/Utilities/ITK/Code/Common/itkSimplexMesh.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimplexMesh.h,v $ Language: C++ -Date: $Date: 2009-04-25 12:24:12 $ -Version: $Revision: 1.13 $ +Date: $Date: 2009-06-21 16:25:08 $ +Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -120,7 +120,10 @@ public: typedef typename Superclass::PointsContainer::Iterator PointsContainerIterator; typedef typename Superclass::PointsContainerConstIterator PointsContainerConstIterator; typedef typename Superclass::CellsContainerPointer CellsContainerPointer; + typedef typename Superclass::CellsContainerConstPointer CellsContainerConstPointer; typedef typename Superclass::CellsContainerIterator CellsContainerIterator; + typedef typename Superclass::CellsContainerConstIterator CellsContainerConstIterator; + /** set the map of geometrydata to the new pointer */ itkSetMacro(GeometryData, GeometryMapPointer ); diff --git a/Utilities/ITK/Code/Common/itkSimplexMesh.txx b/Utilities/ITK/Code/Common/itkSimplexMesh.txx index a82f6f3d3eee8afd7811fac5381f07b8e25de562..532f4f5763932f55f30feb33f136a671134827b7 100644 --- a/Utilities/ITK/Code/Common/itkSimplexMesh.txx +++ b/Utilities/ITK/Code/Common/itkSimplexMesh.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSimplexMesh.txx,v $ Language: C++ -Date: $Date: 2009-03-03 15:09:26 $ -Version: $Revision: 1.22 $ +Date: $Date: 2009-06-21 16:25:08 $ +Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -258,8 +258,8 @@ SimplexMesh<TPixelType, VDimension, TMeshTraits> os << indent << "LastCellId = " << m_LastCellId << std::endl; - CellsContainerPointer cells = this->GetCells(); - CellsContainerIterator cellIt = cells->Begin(); + CellsContainerConstPointer cells = this->GetCells(); + CellsContainerConstIterator cellIt = cells->Begin(); os << indent << "Cells Point Ids:" << std::endl; while ( cellIt != cells->End() ) @@ -443,6 +443,11 @@ SimplexMesh<TPixelType, VDimension, TMeshTraits> { PointType p,n1,n2,n3; + p.Fill(0); + n1.Fill(0); + n2.Fill(0); + n3.Fill(0); + IndexArray neighbors = this->GetNeighbors( idx ); this->GetPoint(idx,&p); this->GetPoint(neighbors[0],&n1); diff --git a/Utilities/ITK/Code/Common/itkTransform.h b/Utilities/ITK/Code/Common/itkTransform.h index 21bc4b8ed873017af5bf93866be3fd7aaad48d85..31b5080473fb6658c9ccd509027d4d35c6cb5b79 100644 --- a/Utilities/ITK/Code/Common/itkTransform.h +++ b/Utilities/ITK/Code/Common/itkTransform.h @@ -3,14 +3,14 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTransform.h,v $ Language: C++ - Date: $Date: 2009-04-10 16:47:58 $ - Version: $Revision: 1.69 $ + Date: $Date: 2009-09-08 01:00:58 $ + Version: $Revision: 1.72 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ @@ -30,21 +30,21 @@ namespace itk { - + /** \class Transform * \brief Transform points and vector from an input space to an output space. * - * This abstract class define the generic interface for a geometrical + * This abstract class define the generic interface for a geometrical * transformation from one space to another. The class provides methods - * for mapping points, vectors and covariant vectors from the input space - * to the output space. + * for mapping points, vectors and covariant vectors from the input space + * to the output space. * * Given that transformation are not necesarily invertible, this basic * class does not provide the methods for back transfromation. Back transform * methods are implemented in derived classes where appropriate. - * + * * \par Registration Framework Support - * Typically a Transform class has several methods for setting its + * Typically a Transform class has several methods for setting its * parameters. For use in the registration framework, the parameters must * also be represented by an array of doubles to allow communication * with generic optimizers. The Array of transformation parameters is set using @@ -61,7 +61,7 @@ namespace itk * */ template <class TScalarType, - unsigned int NInputDimensions=3, + unsigned int NInputDimensions=3, unsigned int NOutputDimensions=3> class ITK_EXPORT Transform : public TransformBase { @@ -71,7 +71,7 @@ public: typedef TransformBase Superclass; typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; - + /** New method for creating an object using a factory. */ itkNewMacro(Self); @@ -102,32 +102,34 @@ public: /** Standard vector type for this class. */ typedef Vector<TScalarType, NInputDimensions> InputVectorType; typedef Vector<TScalarType, NOutputDimensions> OutputVectorType; - + /** Standard covariant vector type for this class */ typedef CovariantVector<TScalarType, NInputDimensions> InputCovariantVectorType; typedef CovariantVector<TScalarType, NOutputDimensions> OutputCovariantVectorType; - + /** Standard vnl_vector type for this class. */ typedef vnl_vector_fixed<TScalarType, NInputDimensions> InputVnlVectorType; typedef vnl_vector_fixed<TScalarType, NOutputDimensions> OutputVnlVectorType; - + /** Standard coordinate point type for this class */ typedef Point<CoordRepType, NInputDimensions> InputPointType; typedef Point<CoordRepType, NOutputDimensions> OutputPointType; - + /** Base inverse transform type. This type should not be changed to the * concrete inverse transform type or inheritance would be lost. */ -#if defined(_MSC_VER) +#if _MSC_VER <= 1300 + // Work-around for a visual c++ 6.0 and 7.0 bug. For details, see + // http://www.itk.org/mailman/private/insight-developers/2009-April/012191.html typedef TransformBase InverseTransformBaseType; #else - typedef Transform< + typedef Transform< TScalarType, NOutputDimensions, NInputDimensions > InverseTransformBaseType; #endif typedef typename InverseTransformBaseType::Pointer InverseTransformBasePointer; - + /** Method to transform a point. */ virtual OutputPointType TransformPoint(const InputPointType & ) const - { return OutputPointType(); } + { return OutputPointType(); } /** Method to transform a vector. */ virtual OutputVectorType TransformVector(const InputVectorType &) const @@ -140,7 +142,7 @@ public: /** Method to transform a CovariantVector. */ virtual OutputCovariantVectorType TransformCovariantVector( const InputCovariantVectorType &) const - { return OutputCovariantVectorType(); } + { return OutputCovariantVectorType(); } /** Set the transformation parameters and update internal transformation. * SetParameters gives the transform the option to set it's @@ -149,37 +151,37 @@ public: * SetParametersByValue. * \sa SetParametersByValue */ - virtual void SetParameters( const ParametersType & ) + virtual void SetParameters( const ParametersType & ) { itkExceptionMacro( << "Subclasses should override this method" ) } - /** Set the transformation parameters and update internal transformation. + /** Set the transformation parameters and update internal transformation. * This method forces the transform to copy the parameters. The * default implementation is to call SetParameters. This call must * be overridden if the transform normally implements SetParameters * by keeping a reference to the parameters. * \sa SetParameters */ - virtual void SetParametersByValue ( const ParametersType & p ) + virtual void SetParametersByValue ( const ParametersType & p ) { this->SetParameters ( p ); } /** Get the Transformation Parameters. */ virtual const ParametersType& GetParameters(void) const - { + { itkExceptionMacro( << "Subclasses should override this method" ); - // Next line is needed to avoid errors due to: + // Next line is needed to avoid errors due to: // "function must return a value". - return this->m_Parameters; + return this->m_Parameters; } /** Set the fixed parameters and update internal transformation. */ - virtual void SetFixedParameters( const ParametersType & ) + virtual void SetFixedParameters( const ParametersType & ) { itkExceptionMacro( << "Subclasses should override this method" ) } /** Get the Fixed Parameters. */ virtual const ParametersType& GetFixedParameters(void) const { itkExceptionMacro( << "Subclasses should override this method" ); - // Next line is needed to avoid errors due to: + // Next line is needed to avoid errors due to: // "function must return a value". return this->m_FixedParameters; } @@ -187,7 +189,7 @@ public: /** Compute the Jacobian of the transformation * * This method computes the Jacobian matrix of the transformation - * at a given input point. The rank of the Jacobian will also indicate + * at a given input point. The rank of the Jacobian will also indicate * if the transform is invertible at this point. * * The Jacobian is be expressed as a matrix of partial derivatives of the @@ -197,31 +199,31 @@ public: * \f[ * J=\left[ \begin{array}{cccc} - \frac{\partial x_{1}}{\partial p_{1}} & - \frac{\partial x_{1}}{\partial p_{2}} & + \frac{\partial x_{1}}{\partial p_{1}} & + \frac{\partial x_{1}}{\partial p_{2}} & \cdots & \frac{\partial x_{1}}{\partial p_{m}}\\ - \frac{\partial x_{2}}{\partial p_{1}} & - \frac{\partial x_{2}}{\partial p_{2}} & + \frac{\partial x_{2}}{\partial p_{1}} & + \frac{\partial x_{2}}{\partial p_{2}} & \cdots & \frac{\partial x_{2}}{\partial p_{m}}\\ \vdots & \vdots & \ddots & \vdots \\ - \frac{\partial x_{n}}{\partial p_{1}} & - \frac{\partial x_{n}}{\partial p_{2}} & + \frac{\partial x_{n}}{\partial p_{1}} & + \frac{\partial x_{n}}{\partial p_{2}} & \cdots & \frac{\partial x_{n}}{\partial p_{m}} - \end{array}\right] + \end{array}\right] * * \f] * */ virtual const JacobianType & GetJacobian(const InputPointType &) const { itkExceptionMacro( << "Subclass should override this method" ); - // Next line is needed to avoid errors due to: + // Next line is needed to avoid errors due to: // "function must return a value" . return this->m_Jacobian; - } + } /** Return the number of parameters that completely define the Transfom */ - virtual unsigned int GetNumberOfParameters(void) const + virtual unsigned int GetNumberOfParameters(void) const { return this->m_Parameters.Size(); } /** Returns a boolean indicating whether it is possible or not to compute the @@ -229,9 +231,9 @@ public: * the transform is returned in the inverseTransform variable passed by the * user. The inverse is recomputed if this current transform has been modified. * This method is intended to be overriden by derived classes. - * + * */ - bool GetInverse(Self * inverseTransform) const {return false;} + bool GetInverse(Self * itkNotUsed(inverseTransform) ) const {return false;} /** Return an inverse of this transform. If the inverse has not been * implemented, return NULL. The type of the inverse transform @@ -251,16 +253,16 @@ public: * points P and Q, and scalar coefficients a and b, then * * T( a*P + b*Q ) = a * T(P) + b * T(Q) - * + * * By default, we assume this to NOT be the case for most transforms. * However, transforms for which this is true will overload and reimplement * this method accordingly. - * + * */ virtual bool IsLinear() const { return false; } protected: - Transform(); + Transform(); Transform(unsigned int Dimension, unsigned int NumberOfParameters); virtual ~Transform() {} diff --git a/Utilities/ITK/Code/Common/itkTreeIteratorBase.h b/Utilities/ITK/Code/Common/itkTreeIteratorBase.h index b81731d478b9bde4646a5e2f7d3aa0e255f69396..6a2b94341624d4b498c761762eca6faed06a746d 100644 --- a/Utilities/ITK/Code/Common/itkTreeIteratorBase.h +++ b/Utilities/ITK/Code/Common/itkTreeIteratorBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTreeIteratorBase.h,v $ Language: C++ - Date: $Date: 2009-03-03 15:10:36 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-06-14 11:55:05 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -179,7 +179,7 @@ public: void operator++(int) { - assert( !IsAtEnd() ); + // assert( !IsAtEnd() ); this->Next(); } /** operator = */ diff --git a/Utilities/ITK/Code/Common/itkTreeIteratorBase.txx b/Utilities/ITK/Code/Common/itkTreeIteratorBase.txx index 6491b75087d7d0694c228d242c608d95e57f995d..78b63f44e75eaf18cdf04eb7e69d6f70d5fd0640 100644 --- a/Utilities/ITK/Code/Common/itkTreeIteratorBase.txx +++ b/Utilities/ITK/Code/Common/itkTreeIteratorBase.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTreeIteratorBase.txx,v $ Language: C++ - Date: $Date: 2009-03-03 15:10:37 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-06-14 11:55:05 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -73,7 +73,7 @@ template <class TTreeType> void TreeIteratorBase<TTreeType>::Set(ValueType element) { - assert(m_Position); +// assert(m_Position); m_Position->Set(element); m_Tree->Modified(); m_Tree->InvokeEvent( TreeNodeChangeEvent<TTreeType>(*this) ); diff --git a/Utilities/ITK/Code/Common/itkVersion.cxx b/Utilities/ITK/Code/Common/itkVersion.cxx index 9761a33ff61fe84d8e2886b7903724855980595f..d861f95e28784b63bf3ffd3b4d042a9414127930 100644 --- a/Utilities/ITK/Code/Common/itkVersion.cxx +++ b/Utilities/ITK/Code/Common/itkVersion.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVersion.cxx,v $ Language: C++ - Date: $Date: 2005-03-22 18:25:15 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-07-28 19:00:40 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -30,4 +30,34 @@ Version::~Version() { } +const char * +Version::GetITKVersion() +{ + return ITK_VERSION; +} + +int +Version::GetITKMajorVersion() +{ + return ITK_VERSION_MAJOR; +} + +int +Version::GetITKMinorVersion() +{ + return ITK_VERSION_MINOR; +} + +int +Version::GetITKBuildVersion() +{ + return ITK_VERSION_PATCH; +} + +const char * +Version::GetITKSourceVersion() +{ + return ITK_SOURCE_VERSION; +} + } // end namespace itk diff --git a/Utilities/ITK/Code/Common/itkVersion.h b/Utilities/ITK/Code/Common/itkVersion.h index 73b39a4110cf7dc7d5ebeeaa3a4d03a93ef04b72..ffdcedb32611a32b5e0ce96a98adba68189c54aa 100644 --- a/Utilities/ITK/Code/Common/itkVersion.h +++ b/Utilities/ITK/Code/Common/itkVersion.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVersion.h,v $ Language: C++ - Date: $Date: 2009-05-26 02:00:07 $ - Version: $Revision: 1.3044 $ + Date: $Date: 2009-09-15 02:00:06 $ + Version: $Revision: 1.3157 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -28,7 +28,7 @@ #define ITK_VERSION ITK_VERSION_TO_STRING(ITK_VERSION_MAJOR) "." \ ITK_VERSION_TO_STRING(ITK_VERSION_MINOR) "." \ ITK_VERSION_TO_STRING(ITK_VERSION_PATCH) -#define ITK_SOURCE_VERSION "itk version " ITK_VERSION ", itk source $Revision: 1.3044 $, $Date: 2009-05-26 02:00:07 $ (GMT)" +#define ITK_SOURCE_VERSION "itk version " ITK_VERSION ", itk source $Revision: 1.3157 $, $Date: 2009-09-15 02:00:06 $ (GMT)" namespace itk { @@ -62,11 +62,11 @@ public: /** Return the version of itk this object is a part of. * A variety of methods are included. GetITKSourceVersion returns a string * with an identifier which timestamps a particular source tree. */ - static const char *GetITKVersion() { return ITK_VERSION; } - static int GetITKMajorVersion() { return ITK_VERSION_MAJOR; } - static int GetITKMinorVersion() { return ITK_VERSION_MINOR; } - static int GetITKBuildVersion() { return ITK_VERSION_PATCH; } - static const char *GetITKSourceVersion() { return ITK_SOURCE_VERSION; } + static const char *GetITKVersion(); + static int GetITKMajorVersion(); + static int GetITKMinorVersion(); + static int GetITKBuildVersion(); + static const char *GetITKSourceVersion(); protected: Version(); diff --git a/Utilities/ITK/Code/Common/itkVersor.h b/Utilities/ITK/Code/Common/itkVersor.h index 0ce39b4cc270be7db5596cf386fd53e446cf64fb..c42cfce12bc96f13802073d792a44d55cd70a1c9 100644 --- a/Utilities/ITK/Code/Common/itkVersor.h +++ b/Utilities/ITK/Code/Common/itkVersor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVersor.h,v $ Language: C++ - Date: $Date: 2007-12-20 19:19:18 $ - Version: $Revision: 1.22 $ + Date: $Date: 2009-06-14 10:20:48 $ + Version: $Revision: 1.23 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -95,13 +95,13 @@ public: quaternion where "w" is positive, since this is implicitly assumed in other sections of the code, in particular when "w" is computed from (x,y,z) via normalization. The reason why it is valid to negate all the components is - that the rotation by angle \theta, is represented by \sin(\frac{\theta}{2}) - in the (x,y,z) components and by \cos(\frac{\theta}{2}) in the "w" - component. The rotation by any \theta should be equivalent to a rotation by - \theta + n \times \pi, therefore we should be able to replace - \sin(\frac{\theta}{2}) with \sin(\frac{\theta}{2} + n \times \pi ) and - \cos(\frac{\theta}{2}) with \cos(\frac{\theta}{2} + n \times \pi ). - Considering that \cos( n \times \pi ) = (-1)^{n} we can conclude that if we + that the rotation by angle \f$\theta\f$, is represented by \f$\sin(\frac{\theta}{2})\f$ + in the (x,y,z) components and by \f$\cos(\frac{\theta}{2})\f$ in the "w" + component. The rotation by any \f$\theta\f$ should be equivalent to a rotation by + \f$\theta + n \times \pi\f$, therefore we should be able to replace + \f$\sin(\frac{\theta}{2})\f$ with \f$\sin(\frac{\theta}{2} + n \times \pi )\f$ and + \f$\cos(\frac{\theta}{2})\f$ with \f$\cos(\frac{\theta}{2} + n \times \pi )\f$. + Considering that \f$\cos( n \times \pi ) = (-1)^{n}\f$ we can conclude that if we simultaneously change the signs of all the Versor components, the rotation that it represents remains unchanged. */ diff --git a/Utilities/ITK/Code/Common/itkVersorTransform.h b/Utilities/ITK/Code/Common/itkVersorTransform.h index 44cda470d19baf781ff39c5457a2aa90b17c13c9..530d5a7a3f3bdf398ff25cb7646b3a49ebb83ed5 100644 --- a/Utilities/ITK/Code/Common/itkVersorTransform.h +++ b/Utilities/ITK/Code/Common/itkVersorTransform.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVersorTransform.h,v $ Language: C++ - Date: $Date: 2009-03-03 15:11:51 $ - Version: $Revision: 1.18 $ + Date: $Date: 2009-06-14 12:30:09 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -39,7 +39,7 @@ namespace itk * The serialization of the fixed parameters is an array of 3 elements defining * the center of rotation. * - * \TODO Need to make sure that the translation parameters in the baseclass + * TODO: Need to make sure that the translation parameters in the baseclass * cannot be set to non-zero values. * * \ingroup Transforms diff --git a/Utilities/ITK/Code/Common/itk_hashtable.h b/Utilities/ITK/Code/Common/itk_hashtable.h index 624670ea208a7b3750e1b3d61c1880258330fd83..e166f493f50c1b378b3380f5de29fd5dde44ea2e 100644 --- a/Utilities/ITK/Code/Common/itk_hashtable.h +++ b/Utilities/ITK/Code/Common/itk_hashtable.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itk_hashtable.h,v $ Language: C++ - Date: $Date: 2009-04-05 10:56:47 $ - Version: $Revision: 1.32 $ + Date: $Date: 2009-08-16 20:30:38 $ + Version: $Revision: 1.34 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -174,6 +174,14 @@ struct hash<unsigned long> size_t operator()(unsigned long x) const { return x; } }; +#ifdef _WIN64 +template<> +struct hash<size_t> +{ + size_t operator()(size_t x) const { return x; } +}; +#endif + template <class Value> struct hashtable_node { diff --git a/Utilities/ITK/Code/IO/itkBMPImageIO.cxx b/Utilities/ITK/Code/IO/itkBMPImageIO.cxx index 2877c1ad9d11a8e4dd5f051c6ab3dee23407f3d0..2d6e6d4f9bede96226621df67cddcae4b4a3aa9e 100644 --- a/Utilities/ITK/Code/IO/itkBMPImageIO.cxx +++ b/Utilities/ITK/Code/IO/itkBMPImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBMPImageIO.cxx,v $ Language: C++ - Date: $Date: 2009-05-26 23:45:03 $ - Version: $Revision: 1.31 $ + Date: $Date: 2009-06-16 07:58:47 $ + Version: $Revision: 1.32 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -877,17 +877,10 @@ BMPImageIO // The specification calls for a signed integer, but // here we force it to be an unsigned integer to avoid // dealing with directions in a subterraneous way. -#ifdef ITK_USE_PORTABLE_ROUND const unsigned int horizontalResolution = static_cast<unsigned int>( Math::Round( 1000.0 / m_Spacing[0] ) ); const unsigned int verticalResolution = static_cast<unsigned int>( Math::Round( 1000.0 / m_Spacing[1] ) ); -#else - const unsigned int horizontalResolution = - static_cast<unsigned int>( vnl_math_rnd( 1000.0 / m_Spacing[0] ) ); - const unsigned int verticalResolution = - static_cast<unsigned int>( vnl_math_rnd( 1000.0 / m_Spacing[1] ) ); -#endif this->Write32BitsInteger( horizontalResolution ); this->Write32BitsInteger( verticalResolution ); diff --git a/Utilities/ITK/Code/IO/itkConvertPixelBuffer.h b/Utilities/ITK/Code/IO/itkConvertPixelBuffer.h index 9b241d01ceee612dc8613b0f3b46c7de6bd064d0..4079f400489ad40e057e6c48e0d788cfdf59bd7d 100644 --- a/Utilities/ITK/Code/IO/itkConvertPixelBuffer.h +++ b/Utilities/ITK/Code/IO/itkConvertPixelBuffer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkConvertPixelBuffer.h,v $ Language: C++ - Date: $Date: 2008-03-29 19:33:14 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-08-11 12:45:11 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -47,44 +47,44 @@ public: /** General method converts from one type to another. */ static void Convert(InputPixelType* inputData, int inputNumberOfComponents, - OutputPixelType* outputData , int size); + OutputPixelType* outputData , size_t size); static void ConvertVectorImage(InputPixelType* inputData, int inputNumberOfComponents, - OutputPixelType* outputData , int size); + OutputPixelType* outputData , size_t size); protected: /** Convert to Gray output. */ /** Input values are cast to output values. */ static void ConvertGrayToGray(InputPixelType* inputData, - OutputPixelType* outputData , int size); + OutputPixelType* outputData , size_t size); /** Weights convert from linear RGB to CIE luminance assuming a * modern monitor. See Charles Poynton's Colour FAQ * * http://www.inforamp.net/~poynton/notes/colour_and_gamma/ColorFAQ.html */ static void ConvertRGBToGray(InputPixelType* inputData, - OutputPixelType* outputData , int size); + OutputPixelType* outputData , size_t size); /** Weights convert from linear RGB to CIE luminance assuming a * modern monitor. Values are attentuated by the Alpha channel. See * Charles Poynton's Colour FAQ * http://www.inforamp.net/~poynton/notes/colour_and_gamma/ColorFAQ.html */ static void ConvertRGBAToGray(InputPixelType* inputData, - OutputPixelType* outputData , int size); + OutputPixelType* outputData , size_t size); static void ConvertMultiComponentToGray(InputPixelType* inputData, int inputNumberOfComponents, OutputPixelType* outputData , - int size); + size_t size); /** Convert to RGB output. */ /** Each RGB output component is set the the * input Gray value. */ static void ConvertGrayToRGB(InputPixelType* inputData, - OutputPixelType* outputData , int size); + OutputPixelType* outputData , size_t size); /** Input values are cast component by component to output values. */ static void ConvertRGBToRGB(InputPixelType* inputData, - OutputPixelType* outputData , int size); + OutputPixelType* outputData , size_t size); /** Input values are attenuated by the Alpha channel. */ static void ConvertRGBAToRGB(InputPixelType* inputData, - OutputPixelType* outputData , int size); + OutputPixelType* outputData , size_t size); /** Conversion depends upon the number of components in the * input. If the number of input components is 2, the output * components are each set to the first input component attenuated @@ -96,35 +96,35 @@ protected: static void ConvertMultiComponentToRGB(InputPixelType* inputData, int inputNumberOfComponents, OutputPixelType* outputData , - int size); + size_t size); /** Convert to RGBA output. */ static void ConvertGrayToRGBA(InputPixelType* inputData, - OutputPixelType* outputData , int size); + OutputPixelType* outputData , size_t size); static void ConvertRGBToRGBA(InputPixelType* inputData, - OutputPixelType* outputData , int size); + OutputPixelType* outputData , size_t size); static void ConvertRGBAToRGBA(InputPixelType* inputData, - OutputPixelType* outputData , int size); + OutputPixelType* outputData , size_t size); static void ConvertMultiComponentToRGBA(InputPixelType* inputData, int inputNumberOfComponents, OutputPixelType* outputData , - int size); + size_t size); /** Convert tensor output. */ /** Each input is made into a 6 component symmetric pixel */ static void ConvertTensor6ToTensor6(InputPixelType* inputData, - OutputPixelType* outputData , int size); + OutputPixelType* outputData , size_t size); static void ConvertTensor9ToTensor6(InputPixelType* inputData, - OutputPixelType* outputData , int size); + OutputPixelType* outputData , size_t size); /** Convertions related to complex */ static void ConvertGrayToComplex(InputPixelType * inputData, - OutputPixelType * OutputData, int size); + OutputPixelType * OutputData, size_t size); static void ConvertComplexToComplex(InputPixelType* inputData, - OutputPixelType* outputData , int size); + OutputPixelType* outputData , size_t size); static void ConvertMultiComponentToComplex(InputPixelType* inputData, int inputNumberOfComponents, - OutputPixelType* outputData , int size); + OutputPixelType* outputData , size_t size); private: ConvertPixelBuffer(); diff --git a/Utilities/ITK/Code/IO/itkConvertPixelBuffer.txx b/Utilities/ITK/Code/IO/itkConvertPixelBuffer.txx index 54f496dad7b4267bdddebcffd227eba659f9af1e..5b61f9629345bdca510e646389177ddcde496d6f 100644 --- a/Utilities/ITK/Code/IO/itkConvertPixelBuffer.txx +++ b/Utilities/ITK/Code/IO/itkConvertPixelBuffer.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkConvertPixelBuffer.txx,v $ Language: C++ - Date: $Date: 2008-03-29 19:33:14 $ - Version: $Revision: 1.25 $ + Date: $Date: 2009-08-11 12:45:09 $ + Version: $Revision: 1.26 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -30,7 +30,7 @@ void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> ::Convert(InputPixelType* inputData, int inputNumberOfComponents, - OutputPixelType* outputData , int size) + OutputPixelType* outputData , size_t size) { switch(OutputConvertTraits::GetNumberOfComponents()) { @@ -150,7 +150,7 @@ template < typename InputPixelType, void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> ::ConvertGrayToGray(InputPixelType* inputData, - OutputPixelType* outputData , int size) + OutputPixelType* outputData , size_t size) { InputPixelType* endInput = inputData + size; while(inputData != endInput) @@ -170,7 +170,7 @@ template < typename InputPixelType, void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> ::ConvertRGBToGray(InputPixelType* inputData, - OutputPixelType* outputData , int size) + OutputPixelType* outputData , size_t size) { // Weights convert from linear RGB to CIE luminance assuming a // modern monitor. See Charles Pontyon's Colour FAQ @@ -198,7 +198,7 @@ template < typename InputPixelType, void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> ::ConvertRGBAToGray(InputPixelType* inputData, - OutputPixelType* outputData , int size) + OutputPixelType* outputData , size_t size) { // Weights convert from linear RGB to CIE luminance assuming a // modern monitor. See Charles Pontyon's Colour FAQ @@ -229,7 +229,7 @@ void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> ::ConvertMultiComponentToGray(InputPixelType* inputData, int inputNumberOfComponents, - OutputPixelType* outputData , int size) + OutputPixelType* outputData , size_t size) { // 2 components assumed intensity and alpha if(inputNumberOfComponents == 2) @@ -252,7 +252,7 @@ ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> // http://www.inforamp.net/~poynton/notes/colour_and_gamma/ColorFAQ.html // NOTE: The scale factors are converted to whole numbers for // precision - int diff = inputNumberOfComponents - 4; + ptrdiff_t diff = inputNumberOfComponents - 4; InputPixelType* endInput = inputData + size*inputNumberOfComponents; while(inputData != endInput) { @@ -278,7 +278,7 @@ template < typename InputPixelType, void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> ::ConvertGrayToRGB(InputPixelType* inputData, - OutputPixelType* outputData , int size) + OutputPixelType* outputData , size_t size) { InputPixelType* endInput = inputData + size; while(inputData != endInput) @@ -305,7 +305,7 @@ template < typename InputPixelType, void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> ::ConvertRGBToRGB(InputPixelType* inputData, - OutputPixelType* outputData , int size) + OutputPixelType* outputData , size_t size) { InputPixelType* endInput = inputData + size * 3; while(inputData != endInput) @@ -331,7 +331,7 @@ template < typename InputPixelType, void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> ::ConvertRGBAToRGB(InputPixelType* inputData, - OutputPixelType* outputData , int size) + OutputPixelType* outputData , size_t size) { InputPixelType* endInput = inputData + size* 4; while(inputData != endInput) @@ -360,7 +360,7 @@ ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> ::ConvertMultiComponentToRGB(InputPixelType* inputData, int inputNumberOfComponents, OutputPixelType* outputData , - int size) + size_t size) { // assume intensity alpha if(inputNumberOfComponents == 2) @@ -381,7 +381,7 @@ ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> // just skip the rest of the data else { - int diff = inputNumberOfComponents - 3; + ptrdiff_t diff = inputNumberOfComponents - 3; InputPixelType* endInput = inputData + size * inputNumberOfComponents; while(inputData != endInput) { @@ -409,7 +409,7 @@ template < typename InputPixelType, void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> ::ConvertGrayToRGBA(InputPixelType* inputData, - OutputPixelType* outputData , int size) + OutputPixelType* outputData , size_t size) { InputPixelType* endInput = inputData + size; @@ -439,7 +439,7 @@ template < typename InputPixelType, void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> ::ConvertRGBToRGBA(InputPixelType* inputData, - OutputPixelType* outputData , int size) + OutputPixelType* outputData , size_t size) { InputPixelType* endInput = inputData + size * 3; while(inputData != endInput) @@ -469,7 +469,7 @@ template < typename InputPixelType, void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> ::ConvertRGBAToRGBA(InputPixelType* inputData, - OutputPixelType* outputData , int size) + OutputPixelType* outputData , size_t size) { InputPixelType* endInput = inputData + size*4; while(inputData != endInput) @@ -500,7 +500,7 @@ ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> ::ConvertMultiComponentToRGBA(InputPixelType* inputData, int inputNumberOfComponents, OutputPixelType* outputData , - int size) + size_t size) { // equal weights for 2 components?? if(inputNumberOfComponents == 2) @@ -519,7 +519,7 @@ ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> } else { - int diff = inputNumberOfComponents - 4; + ptrdiff_t diff = inputNumberOfComponents - 4; InputPixelType* endInput = inputData + size * inputNumberOfComponents; while(inputData != endInput) { @@ -548,9 +548,9 @@ template < typename InputPixelType, void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> ::ConvertTensor6ToTensor6(InputPixelType* inputData, - OutputPixelType* outputData , int size) + OutputPixelType* outputData , size_t size) { - for( int i=0; i< size; i++ ) + for( size_t i=0; i< size; i++ ) { OutputConvertTraits::SetNthComponent( 0, *outputData, static_cast<OutputComponentType>(*inputData)); @@ -579,7 +579,7 @@ template < typename InputPixelType, void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> ::ConvertGrayToComplex(InputPixelType* inputData, - OutputPixelType* outputData , int size) + OutputPixelType* outputData , size_t size) { InputPixelType* endInput = inputData + size; while(inputData != endInput) @@ -603,7 +603,7 @@ template < typename InputPixelType, void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> ::ConvertComplexToComplex(InputPixelType* inputData, - OutputPixelType* outputData , int size) + OutputPixelType* outputData , size_t size) { InputPixelType* endInput = inputData + size*2; while(inputData != endInput) @@ -628,9 +628,9 @@ template < typename InputPixelType, void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> ::ConvertTensor9ToTensor6(InputPixelType* inputData, - OutputPixelType* outputData , int size) + OutputPixelType* outputData , size_t size) { - for( int i=0; i< size; i++ ) + for( size_t i=0; i< size; i++ ) { OutputConvertTraits::SetNthComponent( 0, *outputData, static_cast < OutputComponentType >( *inputData )); @@ -659,9 +659,9 @@ ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> ::ConvertMultiComponentToComplex(InputPixelType* inputData, int inputNumberOfComponents, OutputPixelType* outputData , - int size) + size_t size) { - int diff = inputNumberOfComponents - 2; + ptrdiff_t diff = inputNumberOfComponents - 2; InputPixelType* endInput = inputData + size * inputNumberOfComponents; while(inputData != endInput) { @@ -685,10 +685,10 @@ void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits> ::ConvertVectorImage(InputPixelType* inputData, int inputNumberOfComponents, - OutputPixelType* outputData , int size) + OutputPixelType* outputData , size_t size) { - unsigned long length = static_cast< unsigned long >(size* inputNumberOfComponents); - for( unsigned long i=0; i< length; i++ ) + size_t length = static_cast< size_t >(size* inputNumberOfComponents); + for( size_t i=0; i< length; i++ ) { OutputConvertTraits::SetNthComponent( 0, *outputData, static_cast < OutputComponentType >( *inputData )); diff --git a/Utilities/ITK/Code/IO/itkDICOMSeriesFileNames.cxx b/Utilities/ITK/Code/IO/itkDICOMSeriesFileNames.cxx index 483ea5a8cfdeff33f3dcb36bb22618596ee2badc..e11fc34f6578801e159fd290821aa6cefc168a56 100644 --- a/Utilities/ITK/Code/IO/itkDICOMSeriesFileNames.cxx +++ b/Utilities/ITK/Code/IO/itkDICOMSeriesFileNames.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDICOMSeriesFileNames.cxx,v $ Language: C++ - Date: $Date: 2007-03-22 14:28:48 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-07-28 22:12:10 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -43,7 +43,7 @@ DICOMSeriesFileNames { } -const std::vector<std::string> & +const DICOMSeriesFileNames::FileNamesArrayType & DICOMSeriesFileNames ::GetFileNames(bool recursive) { @@ -62,7 +62,7 @@ DICOMSeriesFileNames } -const std::vector<std::string> & +const DICOMSeriesFileNames::FileNamesArrayType & DICOMSeriesFileNames ::GetFileNames(const std::string &seriesUID, bool recursive) { @@ -129,7 +129,7 @@ DICOMSeriesFileNames void DICOMSeriesFileNames -::RecurseDirectory( std::string directory, std::vector<std::string> &filenames) +::RecurseDirectory( std::string directory, FileNamesArrayType &filenames) { itksys::Directory dicomDir; if (!dicomDir.Load (directory.c_str())) @@ -164,7 +164,7 @@ DICOMSeriesFileNames } -const std::vector<std::string> & +const DICOMSeriesFileNames::FileNamesArrayType & DICOMSeriesFileNames ::GetSeriesUIDs(bool recursive) { @@ -190,7 +190,7 @@ DICOMSeriesFileNames m_AppHelper.Clear(); // Scan directory for files - std::vector<std::string> filenames; + FileNamesArrayType filenames; for (unsigned long i = 0; i < dicomDir.GetNumberOfFiles(); i++) { // Only read files @@ -209,7 +209,7 @@ DICOMSeriesFileNames } // Scan the header of each file - std::vector<std::string>::iterator iter; + FileNamesArrayType::iterator iter; for (iter = filenames.begin(); iter != filenames.end(); iter++) { const char* fn = (*iter).c_str(); diff --git a/Utilities/ITK/Code/IO/itkDICOMSeriesFileNames.h b/Utilities/ITK/Code/IO/itkDICOMSeriesFileNames.h index 714a4a4ddd8f6730a2bf3030c8369f555bcdf110..a1bb935de07751ec5a6aea626fe196cc4bd54cc3 100644 --- a/Utilities/ITK/Code/IO/itkDICOMSeriesFileNames.h +++ b/Utilities/ITK/Code/IO/itkDICOMSeriesFileNames.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDICOMSeriesFileNames.h,v $ Language: C++ - Date: $Date: 2009-04-25 12:25:41 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-07-28 22:12:11 $ + Version: $Revision: 1.15 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -100,27 +100,30 @@ public: itkGetConstMacro(Ascending, bool); itkBooleanMacro(Ascending); + /** Type of the array used for returning filenames */ + typedef std::vector<std::string> FileNamesArrayType; + /** Returns a vector containing the UIDs for each series in the * directory. If parameter "recursive" is true, subdirectories will * be scanned. */ - const std::vector<std::string> &GetSeriesUIDs(bool recursive = false); + const FileNamesArrayType & GetSeriesUIDs(bool recursive = false); /** Returns a vector containing the Descriptions for each series in the * directory. GetSeriesUIDs() should be called before */ - const std::vector<std::string> &GetSeriesDescriptions(){return m_SeriesDescriptions;} - const std::vector<std::string> &GetSeriesBodyParts(){return m_BodyParts;} - const std::vector<std::string> &GetSeriesScanOptions(){return m_ScanOptions;} + const FileNamesArrayType & GetSeriesDescriptions(){return m_SeriesDescriptions;} + const FileNamesArrayType & GetSeriesBodyParts(){return m_BodyParts;} + const FileNamesArrayType & GetSeriesScanOptions(){return m_ScanOptions;} /** Returns a vector containing the series file names. The file * names are sorted based on the current sorting mode. If parameter * "recursive" is true, subdirectories will be scanned. */ - const std::vector<std::string> &GetFileNames (bool recursive = false); + const FileNamesArrayType & GetFileNames (bool recursive = false); /** Returns a vector containing the file names for a specified * series UID. The file names are sorted based on the current * sorting mode. If parameter "recursive" is true, subdirectories * will be scanned. */ - const std::vector<std::string> &GetFileNames (const std::string& seriesUID, + const FileNamesArrayType & GetFileNames (const std::string& seriesUID, bool recursive = false); /** Set the filename sorting order to sorting images based on the @@ -153,23 +156,23 @@ private: void operator=(const Self&); //purposely not implemented int CanReadFile(const char* fname); - void RecurseDirectory( std::string directory, std::vector<std::string> &filenames); + void RecurseDirectory( std::string directory, FileNamesArrayType &filenames); itkdicomparser::DICOMParser m_Parser; itkdicomparser::DICOMAppHelper m_AppHelper; bool m_Ascending; std::string m_Directory; - std::vector<std::string> m_FileNames; - std::vector<std::string> m_SeriesUIDs; - std::vector<std::string> m_SeriesDescriptions; - std::vector<std::string> m_BodyParts; - std::vector<std::string> m_ScanOptions; + FileNamesArrayType m_FileNames; + FileNamesArrayType m_SeriesUIDs; + FileNamesArrayType m_SeriesDescriptions; + FileNamesArrayType m_BodyParts; + FileNamesArrayType m_ScanOptions; FileNameSortingOrderType m_FileNameSortingOrder; - TimeStamp m_DirectorySetTime; - TimeStamp m_DirectoryScanTime; + TimeStamp m_DirectorySetTime; + TimeStamp m_DirectoryScanTime; }; } //namespace ITK diff --git a/Utilities/ITK/Code/IO/itkGDCMImageIO.cxx b/Utilities/ITK/Code/IO/itkGDCMImageIO.cxx index 8ac89de051310b38dc15cc9c8ee18ef7e672b97a..99d0e39ac8fb25b27124ee3b9a4a6cdde079a377 100644 --- a/Utilities/ITK/Code/IO/itkGDCMImageIO.cxx +++ b/Utilities/ITK/Code/IO/itkGDCMImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGDCMImageIO.cxx,v $ Language: C++ - Date: $Date: 2009-04-29 22:31:37 $ - Version: $Revision: 1.159 $ + Date: $Date: 2009-08-20 08:20:53 $ + Version: $Revision: 1.161 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -79,7 +79,7 @@ public: * Because it is required by the standard that DICOM file reader can read file where Group Length attribute value * would be invalid, turning this flag to off, on the one hand might lead to some speed improvement, but on the * other hand will make your DICOM implementation non-standard. - * Technically Group Length value could be incorrect and GDCM might even skipped over some public element and not + * Technically Group Length value could be incorrect and GDCM might even seek over some public element and not * just the desired current group of attributes. Do not turn this option to false unless you understand the * consequences. * @@ -1113,6 +1113,9 @@ void GDCMImageIO::InternalReadImageInformation(std::ifstream& file) case gdcm::PixelFormat::FLOAT32: m_ComponentType = ImageIOBase::FLOAT; break; + case gdcm::PixelFormat::FLOAT64: + m_ComponentType = ImageIOBase::DOUBLE; + break; default: itkExceptionMacro( "Unhandled PixelFormat: " << outputpt ); } @@ -1195,7 +1198,7 @@ void GDCMImageIO::InternalReadImageInformation(std::ifstream& file) { // assert( vr & gdcm::VR::VRBINARY ); /* - * Old bahavior was to skip SQ, Pixel Data element. I decided that it is not safe to mime64 + * Old behavior was to skip SQ, Pixel Data element. I decided that it is not safe to mime64 * VR::UN element. There used to be a bug in gdcm 1.2.0 and VR:UN element. */ if ( tag.IsPublic() && vr != gdcm::VR::SQ && tag != gdcm::Tag(0x7fe0,0x0010) /* && vr != gdcm::VR::UN*/ ) diff --git a/Utilities/ITK/Code/IO/itkGE4ImageIO.h b/Utilities/ITK/Code/IO/itkGE4ImageIO.h index 5039cebf7ec8e10e56c2d7199cdc08e11c52622e..30ca87126c61fe3f0247020468aede03c4badad2 100644 --- a/Utilities/ITK/Code/IO/itkGE4ImageIO.h +++ b/Utilities/ITK/Code/IO/itkGE4ImageIO.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGE4ImageIO.h,v $ Language: C++ - Date: $Date: 2007-12-03 13:13:08 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-06-14 12:30:10 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -90,20 +90,20 @@ public: /*-------- This part of the interfaces deals with writing data. ----- */ - /** Determine if the file can be written with this ImageIO implementation. + /* * Determine if the file can be written with this ImageIO implementation. * \param FileNameToWrite The name of the file to test for writing. * \author Hans J. Johnson * \post Sets classes ImageIOBase::m_FileName variable to be FileNameToWrite * \return Returns true if this ImageIO can write the file specified. - */ + */ // Implemented in superclass // virtual bool CanWriteFile(const char * FileNameToWrite); - /** Set the spacing and dimension information for the set filename. */ + /* * Set the spacing and dimension information for the set filename. */ // Implemented in superclass // virtual void WriteImageInformation(); - /** Writes the data to disk from the memory buffer provided. Make sure + /* * Writes the data to disk from the memory buffer provided. Make sure * that the IORegions has been set properly. */ // Implemented in superclass // virtual void Write(const void* buffer); diff --git a/Utilities/ITK/Code/IO/itkGE5ImageIO.h b/Utilities/ITK/Code/IO/itkGE5ImageIO.h index 2ae01c60c1b0374f97d508bb2d326b53dce72873..637674f7c198f0b506aa8c094999fc374dc4fcf9 100644 --- a/Utilities/ITK/Code/IO/itkGE5ImageIO.h +++ b/Utilities/ITK/Code/IO/itkGE5ImageIO.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGE5ImageIO.h,v $ Language: C++ - Date: $Date: 2007-12-03 13:13:08 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-06-14 12:30:11 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -72,22 +72,22 @@ public: */ virtual bool CanReadFile(const char* FileNameToRead); - /** Set the spacing and dimension information for the set filename. */ + /* * Set the spacing and dimension information for the set filename. */ // Implemented in superclass // virtual void ReadImageInformation(); /** Modify Origin and direction */ void ModifyImageInformation(); - /** Get the type of the pixel. */ + /* * Get the type of the pixel. */ // Implemented in superclass // virtual const std::type_info& GetPixelType() const; - /** Reads the data from disk into the memory buffer provided. */ + /* * Reads the data from disk into the memory buffer provided. */ // Implemented in superclass // virtual void Read(void* buffer); - /** Compute the size (in bytes) of the components of a pixel. For + /* * Compute the size (in bytes) of the components of a pixel. For * example, and RGB pixel of unsigned char would have a * component size of 1 byte. */ // Implemented in superclass @@ -95,20 +95,20 @@ public: /*-------- This part of the interfaces deals with writing data. ----- */ - /** Determine if the file can be written with this ImageIO implementation. + /* * Determine if the file can be written with this ImageIO implementation. * \param FileNameToWrite The name of the file to test for writing. * \author Hans J. Johnson * \post Sets classes ImageIOBase::m_FileName variable to be FileNameToWrite * \return Returns true if this ImageIO can write the file specified. - */ + */ // Implemented in superclass // virtual bool CanWriteFile(const char * FileNameToWrite); - /** Set the spacing and dimension information for the set filename. */ + /* * Set the spacing and dimension information for the set filename. */ // Implemented in superclass // virtual void WriteImageInformation(); - /** Writes the data to disk from the memory buffer provided. Make sure + /* * Writes the data to disk from the memory buffer provided. Make sure * that the IORegions has been set properly. */ // Implemented in superclass // virtual void Write(const void* buffer); diff --git a/Utilities/ITK/Code/IO/itkGEAdwImageIO.h b/Utilities/ITK/Code/IO/itkGEAdwImageIO.h index b98f55e16c002ff63046f542cb5857d79eb83e0d..d2792661d5f9b8d8cb21b8eaa5df7274b24a9da0 100644 --- a/Utilities/ITK/Code/IO/itkGEAdwImageIO.h +++ b/Utilities/ITK/Code/IO/itkGEAdwImageIO.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGEAdwImageIO.h,v $ Language: C++ - Date: $Date: 2008-10-06 16:57:07 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-06-14 12:30:12 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -70,19 +70,19 @@ public: */ virtual bool CanReadFile(const char* FileNameToRead); - /** Set the spacing and dimension information for the set filename. */ + /* * Set the spacing and dimension information for the set filename. */ // Implemented in superclass // virtual void ReadImageInformation(); - /** Get the type of the pixel. */ + /* * Get the type of the pixel. */ // Implemented in superclass // virtual const std::type_info& GetPixelType() const; - /** Reads the data from disk into the memory buffer provided. */ + /* * Reads the data from disk into the memory buffer provided. */ // Implemented in superclass // virtual void Read(void* buffer); - /** Compute the size (in bytes) of the components of a pixel. For + /* * Compute the size (in bytes) of the components of a pixel. For * example, and RGB pixel of unsigned char would have a * component size of 1 byte. */ // Implemented in superclass @@ -90,7 +90,7 @@ public: /*-------- This part of the interfaces deals with writing data. ----- */ - /** Determine if the file can be written with this ImageIO implementation. + /* * Determine if the file can be written with this ImageIO implementation. * \param FileNameToWrite The name of the file to test for writing. * \author Hans J. Johnson * \post Sets classes ImageIOBase::m_FileName variable to be FileNameToWrite @@ -99,11 +99,11 @@ public: // Implemented in superclass // virtual bool CanWriteFile(const char * FileNameToWrite); - /** Set the spacing and dimension information for the set filename. */ + /* * Set the spacing and dimension information for the set filename. */ // Implemented in superclass // virtual void WriteImageInformation(); - /** Writes the data to disk from the memory buffer provided. Make sure + /* * Writes the data to disk from the memory buffer provided. Make sure * that the IORegions has been set properly. */ // Implemented in superclass // virtual void Write(const void* buffer); diff --git a/Utilities/ITK/Code/IO/itkImageFileReader.h b/Utilities/ITK/Code/IO/itkImageFileReader.h index 9f9f2f112f8a4e9dbe95b4d29e892b9314e2dd2d..6ed501ff5b9400b66d6fc87e713a374b985474d4 100644 --- a/Utilities/ITK/Code/IO/itkImageFileReader.h +++ b/Utilities/ITK/Code/IO/itkImageFileReader.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageFileReader.h,v $ Language: C++ - Date: $Date: 2007-09-06 18:31:36 $ - Version: $Revision: 1.31 $ + Date: $Date: 2009-08-11 12:45:08 $ + Version: $Revision: 1.33 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -151,7 +151,7 @@ protected: void PrintSelf(std::ostream& os, Indent indent) const; /** Convert a block of pixels from one type to another. */ - void DoConvertBuffer(void* buffer, unsigned long numberOfPixels); + void DoConvertBuffer(void* buffer, size_t numberOfPixels); /** Test whether the given filename exist and it is readable, this * is intended to be called before attempting to use ImageIO @@ -176,9 +176,9 @@ private: void operator=(const Self&); //purposely not implemented std::string m_ExceptionMessage; - // The region that the ImageIO class will return when we ask it to produce a - // requested region. - ImageRegionType m_StreamableRegion; + // The region that the ImageIO class will return when we ask to + // produce the requested region. + ImageIORegion m_ActualIORegion; }; diff --git a/Utilities/ITK/Code/IO/itkImageFileReader.txx b/Utilities/ITK/Code/IO/itkImageFileReader.txx index c4d91f4fcf6b61ca3586932be7d4b1d469c387b1..a708ea8369f2e7eb500e9b66045d620b5c029771 100644 --- a/Utilities/ITK/Code/IO/itkImageFileReader.txx +++ b/Utilities/ITK/Code/IO/itkImageFileReader.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageFileReader.txx,v $ Language: C++ - Date: $Date: 2009-05-19 19:26:25 $ - Version: $Revision: 1.85 $ + Date: $Date: 2009-08-11 12:45:07 $ + Version: $Revision: 1.88 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -100,9 +100,11 @@ ImageFileReader<TOutputImage, ConvertPixelTraits> throw ImageFileReaderException(__FILE__, __LINE__, "FileName must be specified", ITK_LOCATION); } - // Test if the file exists and if it can be open. + // Test if the file exists and if it can be opened. // An exception will be thrown otherwise. - // + // We catch the exception because some ImageIO's may not actually + // open a file. Still reports file error if no ImageIO is loaded. + try { m_ExceptionMessage = ""; @@ -293,58 +295,59 @@ ImageFileReader<TOutputImage, ConvertPixelTraits> itkDebugMacro (<< "Starting EnlargeOutputRequestedRegion() "); typename TOutputImage::Pointer out = dynamic_cast<TOutputImage*>(output); typename TOutputImage::RegionType largestRegion = out->GetLargestPossibleRegion(); + ImageRegionType streamableRegion; - // Delegate to the ImageIO the computation of how much the - // requested region must be enlarged. - // // The following code converts the ImageRegion (templated over dimension) // into an ImageIORegion (not templated over dimension). - // ImageRegionType imageRequestedRegion = out->GetRequestedRegion(); - ImageIORegion ioRequestedRegion( TOutputImage::ImageDimension ); typedef ImageIORegionAdaptor< TOutputImage::ImageDimension > ImageIOAdaptor; ImageIOAdaptor::Convert( imageRequestedRegion, ioRequestedRegion, largestRegion.GetIndex() ); + // Tell the IO if we should use streaming while reading m_ImageIO->SetUseStreamedReading(m_UseStreaming); - - ImageIORegion ioStreamableRegion = + + + // Delegate to the ImageIO the computation of how the + // requested region must be enlarged. + m_ActualIORegion = m_ImageIO->GenerateStreamableReadRegionFromRequestedRegion( ioRequestedRegion ); - // if the ImageIO must read a higher dimension, we can't read the file - if (ioStreamableRegion.GetImageDimension() > TOutputImage::ImageDimension ) + // the m_ActualIORegion may be more dimensions then the output + // Image, in which case we still need to read this larger region to + // support reading the "first slice" of a larger image + // see bug 9212 + + + // convert the IORegion to a ImageRegion (which is dimension templated) + // if the ImageIO must read a higher dimension region, this will + // truncate the last dimensions + ImageIOAdaptor::Convert( m_ActualIORegion, streamableRegion, largestRegion.GetIndex() ); + + // Check whether the imageRequestedRegion is fully contained inside the + // streamable region + if( !streamableRegion.IsInside( imageRequestedRegion ) ) { + // we must use a InvalidRequestedRegionError since + // DataObject::PropagateRequestedRegion() has an exception + // specification ::itk::OStringStream message; - message << "ImageIO returns IO region that does is not fully contain by the largest possible region\n" - << "Largest region: " << largestRegion - << "StreamableRegion region: " << ioStreamableRegion; + message << "ImageIO returns IO region that does not fully contain the requested region" + << "Requested region: " << imageRequestedRegion + << "StreamableRegion region: " << streamableRegion; InvalidRequestedRegionError e(__FILE__, __LINE__); e.SetLocation(ITK_LOCATION); e.SetDescription(message.str().c_str()); throw e; } - - ImageIOAdaptor::Convert( ioStreamableRegion, this->m_StreamableRegion, largestRegion.GetIndex() ); - - // - // Check whether the imageRequestedRegion is fully contained inside the - // streamable region or not. - if( !this->m_StreamableRegion.IsInside( imageRequestedRegion ) ) - { - itkExceptionMacro( - << "ImageIO returns IO region that does not fully contain the requested region" - << "Requested region: " << imageRequestedRegion - << "StreamableRegion region: " << this->m_StreamableRegion - ); - } - itkDebugMacro (<< "StreamableRegion set to =" << this->m_StreamableRegion ); + itkDebugMacro (<< "RequestedRegion is set to:" << streamableRegion << " while the m_ActualIORegion is: " << m_ActualIORegion); - out->SetRequestedRegion(this->m_StreamableRegion); + out->SetRequestedRegion( streamableRegion ); } @@ -354,16 +357,21 @@ void ImageFileReader<TOutputImage, ConvertPixelTraits> { typename TOutputImage::Pointer output = this->GetOutput(); - typename TOutputImage::RegionType largestRegion = output->GetLargestPossibleRegion(); + typename TOutputImage::RegionType requestedRegion = output->GetRequestedRegion(); itkDebugMacro ( << "ImageFileReader::GenerateData() \n" - << "Allocating the buffer with the StreamableRegion \n" - << this->m_StreamableRegion << "\n"); + << "Allocating the buffer with the EnlargedRequestedRegion \n" + << output->GetRequestedRegion() << "\n"); + // allocated the output image to the size of the enlarge requested region this->AllocateOutputs(); - // Test if the file exist and if it can be open. - // and exception will be thrown otherwise. + // Test if the file exists and if it can be opened. + // An exception will be thrown otherwise, since we can't + // successfully read the file. We catch the exception because some + // ImageIO's may not actually open a file. Still + // reports file error if no ImageIO is loaded. + try { m_ExceptionMessage = ""; @@ -375,56 +383,94 @@ void ImageFileReader<TOutputImage, ConvertPixelTraits> } // Tell the ImageIO to read the file - // - OutputImagePixelType *buffer = output->GetPixelContainer()->GetBufferPointer(); - m_ImageIO->SetFileName(m_FileName.c_str()); - ImageIORegion ioRegion(TOutputImage::ImageDimension); - - typedef ImageIORegionAdaptor< TOutputImage::ImageDimension > ImageIOAdaptor; + itkDebugMacro (<< "Setting imageIO IORegion to: " << m_ActualIORegion ); + m_ImageIO->SetIORegion( m_ActualIORegion ); - // Convert the m_StreamableRegion from ImageRegion type to ImageIORegion type - ImageIOAdaptor::Convert( this->m_StreamableRegion, ioRegion, largestRegion.GetIndex() ); + char *loadBuffer = 0; + // the size of the buffer is computed based on the actual number of + // pixels to be read and the actual size of the pixels to be read + // (as opposed to the sizes of the output) + size_t sizeOfActualIORegion = m_ActualIORegion.GetNumberOfPixels() * (m_ImageIO->GetComponentSize()*m_ImageIO->GetNumberOfComponents()); - itkDebugMacro (<< "ioRegion: " << ioRegion); - - m_ImageIO->SetIORegion( ioRegion ); - - if ( m_ImageIO->GetComponentTypeInfo() - == typeid(ITK_TYPENAME ConvertPixelTraits::ComponentType) - && (m_ImageIO->GetNumberOfComponents() - == ConvertPixelTraits::GetNumberOfComponents())) + try { - itkDebugMacro(<< "No buffer conversion required."); - // allocate a buffer and have the ImageIO read directly into it - m_ImageIO->Read(buffer); - return; + + if ( (m_ImageIO->GetComponentTypeInfo() != typeid(ITK_TYPENAME ConvertPixelTraits::ComponentType) ) + || (m_ImageIO->GetNumberOfComponents() != ConvertPixelTraits::GetNumberOfComponents() )) + { + // the pixel types don't match so a type conversion needs to be + // performed + itkDebugMacro(<< "Buffer conversion required from: " + << m_ImageIO->GetComponentTypeInfo().name() + << " to: " + << typeid(ITK_TYPENAME ConvertPixelTraits::ComponentType).name()); + + + loadBuffer = new char[ sizeOfActualIORegion ]; + m_ImageIO->Read( static_cast< void *>(loadBuffer) ); + + this->DoConvertBuffer(static_cast< void *>(loadBuffer), m_ActualIORegion.GetNumberOfPixels() ); + } + else if ( m_ActualIORegion.GetNumberOfPixels() != requestedRegion.GetNumberOfPixels() ) + { + // for the number of pixels read and the number of pixels + // requested to not match, the dimensions of the two regions may + // be different, therefore we buffer and copy the pixels + + itkDebugMacro(<< "Buffer required because file dimension is greater then image dimension"); + + OutputImagePixelType *outputBuffer = output->GetPixelContainer()->GetBufferPointer(); + + loadBuffer = new char[ sizeOfActualIORegion ]; + m_ImageIO->Read( static_cast< void *>(loadBuffer) ); + + // we use std::copy here as it should be optimized to memcpy for + // plain old data, but still is oop + std::copy( reinterpret_cast<const OutputImagePixelType *>(loadBuffer), + reinterpret_cast<const OutputImagePixelType *>(loadBuffer) + output->GetBufferedRegion().GetNumberOfPixels(), + outputBuffer ); + } + else + { + itkDebugMacro(<< "No buffer conversion required."); + + OutputImagePixelType *outputBuffer = output->GetPixelContainer()->GetBufferPointer(); + m_ImageIO->Read(outputBuffer); + } + } - else // a type conversion is necessary + catch (...) { - itkDebugMacro(<< "Buffer conversion required."); - // note: char is used here because the buffer is read in bytes - // regardles of the actual type of the pixels. - ImageRegionType region = output->GetBufferedRegion(); - std::vector<char> loadBuffer(m_ImageIO->GetImageSizeInBytes()); - - m_ImageIO->Read(static_cast<void *>(&loadBuffer[0])); + // if an exception is thrown catch it - itkDebugMacro(<< "Buffer conversion required from: " - << m_ImageIO->GetComponentTypeInfo().name() - << " to: " - << typeid(ITK_TYPENAME ConvertPixelTraits::ComponentType).name()); + if (loadBuffer) + { + // clean up + delete [] loadBuffer; + loadBuffer = 0; + } + + // then rethrow + throw; + } + - this->DoConvertBuffer(static_cast<void *>(&loadBuffer[0]), region.GetNumberOfPixels()); + // clean up + if (loadBuffer) + { + delete [] loadBuffer; + loadBuffer = 0; } + } template <class TOutputImage, class ConvertPixelTraits> void ImageFileReader<TOutputImage, ConvertPixelTraits> ::DoConvertBuffer(void* inputData, - unsigned long numberOfPixels) + size_t numberOfPixels) { // get the pointer to the destination buffer OutputImagePixelType *outputData = @@ -461,7 +507,7 @@ ImageFileReader<TOutputImage, ConvertPixelTraits> static_cast<type*>(inputData), \ m_ImageIO->GetNumberOfComponents(), \ outputData, \ - static_cast<int>(numberOfPixels)); \ + numberOfPixels); \ } \ else \ { \ @@ -474,7 +520,7 @@ ImageFileReader<TOutputImage, ConvertPixelTraits> static_cast<type*>(inputData), \ m_ImageIO->GetNumberOfComponents(), \ outputData, \ - static_cast<int>(numberOfPixels)); \ + numberOfPixels); \ } \ } if(0) diff --git a/Utilities/ITK/Code/IO/itkImageFileWriter.txx b/Utilities/ITK/Code/IO/itkImageFileWriter.txx index c8bfbe01792804f328c060d692bac003ce39ed47..cf7ccf17e0abf2751292b62358bbf9e0401ff784 100644 --- a/Utilities/ITK/Code/IO/itkImageFileWriter.txx +++ b/Utilities/ITK/Code/IO/itkImageFileWriter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageFileWriter.txx,v $ Language: C++ - Date: $Date: 2009-02-11 15:37:05 $ - Version: $Revision: 1.59 $ + Date: $Date: 2009-08-24 18:08:39 $ + Version: $Revision: 1.62 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -338,7 +338,7 @@ ImageFileWriter<TInputImage> // write the data this->GenerateData(); - this->UpdateProgress((float) piece / numDivisions ); + this->UpdateProgress((float) (piece+1) / numDivisions ); } diff --git a/Utilities/ITK/Code/IO/itkImageIOBase.h b/Utilities/ITK/Code/IO/itkImageIOBase.h index c05956cc6ca041f0cf5a443362bda4e4bd68e483..575163a2a6d1325795687857d3316852e9f528d8 100644 --- a/Utilities/ITK/Code/IO/itkImageIOBase.h +++ b/Utilities/ITK/Code/IO/itkImageIOBase.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageIOBase.h,v $ Language: C++ - Date: $Date: 2009-05-19 19:26:25 $ - Version: $Revision: 1.53 $ + Date: $Date: 2009-07-02 13:16:48 $ + Version: $Revision: 1.54 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -249,7 +249,11 @@ public: typedef std::streamoff SizeType; /** Convenient method for accessing the number of bytes to get to - * the next pixel. Returns m_Strides[1]; */ + * the next pixel. Returns m_Strides[1]; + * + * Please note that this methods depends the private methods + * ComputeStrides being called, otherwise this is the incorrect value. + */ virtual SizeType GetPixelStride () const; /** Return the number of pixels in the image. */ @@ -262,6 +266,14 @@ public: * of components in the image. */ SizeType GetImageSizeInComponents() const; + + /** Compute the size (in bytes) of the components of a pixel. For + * example, and RGB pixel of unsigned char would have a + * component size of 1 byte. This method can be invoked only after + * the component type is set. */ + virtual unsigned int GetComponentSize() const; + + /*-------- This part of the interfaces deals with reading data ----- */ /** Determine the file type. Returns true if this ImageIO can read the @@ -447,6 +459,10 @@ protected: void Resize(const unsigned int numDimensions, const unsigned int* dimensions); + /** Compute the size (in bytes) of the pixel. For + * example, and RGB pixel of unsigned char would have size 3 bytes. */ + virtual unsigned int GetPixelSize() const; + /** Calculates the different strides (distance from one thing to the next). * Upon return, * strides[0] = bytes to get to the next component of a pixel, @@ -455,16 +471,6 @@ protected: * strides[3] = bytes to get to the next slice in z direction, etc. */ void ComputeStrides(); - /** Compute the size (in bytes) of the pixel. For - * example, and RGB pixel of unsigned char would have size 3 bytes. */ - virtual unsigned int GetPixelSize() const; - - /** Compute the size (in bytes) of the components of a pixel. For - * example, and RGB pixel of unsigned char would have a - * component size of 1 byte. This method can be invoked only after - * the component type is set. */ - virtual unsigned int GetComponentSize() const; - /** Convenient method for accessing number of bytes to get to the next pixel * component. Returns m_Strides[0]. */ SizeType GetComponentStride() const; diff --git a/Utilities/ITK/Code/IO/itkImageIORegion.cxx b/Utilities/ITK/Code/IO/itkImageIORegion.cxx index bdd3c5dbea2283e2476ba2cc886d04ed99bc4dfd..c0145005967fa0a3d29ac109ee382b1be03d965a 100644 --- a/Utilities/ITK/Code/IO/itkImageIORegion.cxx +++ b/Utilities/ITK/Code/IO/itkImageIORegion.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageIORegion.cxx,v $ Language: C++ - Date: $Date: 2009-05-18 15:22:16 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-08-11 12:37:19 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -234,6 +234,22 @@ ImageIORegion return true; } +/** Get the number of pixels contained in this region. This just + * multiplies the size components. */ +ImageIORegion::SizeValueType +ImageIORegion +::GetNumberOfPixels( void ) const +{ + size_t numPixels=1; + + for ( unsigned int d = 0; d < this->GetImageDimension(); ++d ) + { + numPixels *= m_Size[d]; + } + + return numPixels; +} + bool ImageIORegion diff --git a/Utilities/ITK/Code/IO/itkImageIORegion.h b/Utilities/ITK/Code/IO/itkImageIORegion.h index 75de1d41ceacfb3440b06b0c0dd8229c6ab83ea7..5cb37bf0de9876e86e27d66721857ea98c92d51f 100644 --- a/Utilities/ITK/Code/IO/itkImageIORegion.h +++ b/Utilities/ITK/Code/IO/itkImageIORegion.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageIORegion.h,v $ Language: C++ - Date: $Date: 2009-02-24 15:36:27 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-07-12 10:52:54 $ + Version: $Revision: 1.25 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -57,9 +57,10 @@ public: typedef ImageIORegion Self; typedef Region Superclass; - /** these types correspond to those of itk::Size and itk::Index */ - typedef unsigned long SizeValueType; - typedef long IndexValueType; + /** these types correspond to those of itk::Size, itk::Offset and itk::Index */ + typedef size_t SizeValueType; + typedef ptrdiff_t IndexValueType; + typedef ptrdiff_t OffsetValueType; /** Index typedef support. An index is used to access pixel values. */ @@ -138,6 +139,9 @@ public: /** Test if a region (the argument) is completly inside of this region */ bool IsInside(const Self ®ion) const; + /** Get the number of pixels contained in this region. This just + * multiplies the size components. */ + SizeValueType GetNumberOfPixels( void ) const; protected: /** Methods invoked by Print() to print information about the object diff --git a/Utilities/ITK/Code/IO/itkImageSeriesReader.h b/Utilities/ITK/Code/IO/itkImageSeriesReader.h index e424ca7f26b308082adb66eea88a3592e5e9fcff..4eb791bb243a81c10e903b09082d85238416f136 100755 --- a/Utilities/ITK/Code/IO/itkImageSeriesReader.h +++ b/Utilities/ITK/Code/IO/itkImageSeriesReader.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageSeriesReader.h,v $ Language: C++ - Date: $Date: 2009-04-25 12:25:42 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-07-30 20:00:00 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -25,6 +25,7 @@ #include <vector> #include <string> #include "itkMetaDataDictionary.h" +#include "itkImageFileReader.h" namespace itk { @@ -160,7 +161,10 @@ protected: FileNamesContainer m_FileNames; /** The number of independent variables in the images that comprise - * the series. */ + * the series. This is also used as the slice moving dimension + * index for the output image. That is for reading a series of 2D + * images into a 3D image, the moving dimension index is 2. + */ int m_NumberOfDimensionsInImage; /** Array of MetaDataDictionaries. This allows to hold information from the @@ -172,6 +176,10 @@ protected: private: ImageSeriesReader(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented + + typedef ImageFileReader<TOutputImage> ReaderType; + + int ComputeMovingDimensionIndex( ReaderType * reader ); }; } //namespace ITK diff --git a/Utilities/ITK/Code/IO/itkImageSeriesReader.txx b/Utilities/ITK/Code/IO/itkImageSeriesReader.txx index 22518ea992f45aea0c5d21ac2f581a939e3e9097..457a1d2a986e8b178900a5c62c3b73dd40a1308e 100755 --- a/Utilities/ITK/Code/IO/itkImageSeriesReader.txx +++ b/Utilities/ITK/Code/IO/itkImageSeriesReader.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageSeriesReader.txx,v $ Language: C++ - Date: $Date: 2009-04-06 00:19:17 $ - Version: $Revision: 1.35 $ + Date: $Date: 2009-07-30 20:00:00 $ + Version: $Revision: 1.38 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -16,9 +16,9 @@ =========================================================================*/ #ifndef __itkImageSeriesReader_txx #define __itkImageSeriesReader_txx + #include "itkImageSeriesReader.h" -#include "itkImageFileReader.h" #include "itkImageRegion.h" #include "itkImageRegionIterator.h" #include "itkImageRegionConstIterator.h" @@ -70,12 +70,39 @@ void ImageSeriesReader<TOutputImage> } +template <class TOutputImage> +int ImageSeriesReader<TOutputImage> +::ComputeMovingDimensionIndex( ReaderType * reader ) +{ + // This method computes the the diminesion index which we are going + // to be moving in for slices + + int movingDimension = reader->GetImageIO()->GetNumberOfDimensions(); + + if (movingDimension > TOutputImage::ImageDimension - 1) + { + movingDimension = TOutputImage::ImageDimension - 1; + } + + SizeType dimSize = reader->GetOutput()->GetLargestPossibleRegion().GetSize(); + + // collapse the number of dimensions in image if any of the last + // dimensions are one + while (movingDimension > 0 && dimSize[movingDimension-1] == 1) + { + --movingDimension; + } + + return movingDimension; +} + + template <class TOutputImage> void ImageSeriesReader<TOutputImage> ::GenerateOutputInformation(void) { typename TOutputImage::Pointer output = this->GetOutput(); - typedef ImageFileReader<TOutputImage> ReaderType; + Array<float> position1(TOutputImage::ImageDimension); position1.Fill(0.0f); Array<float> position2(TOutputImage::ImageDimension); position2.Fill(0.0f); @@ -136,35 +163,31 @@ void ImageSeriesReader<TOutputImage> origin = reader->GetOutput()->GetOrigin(); direction = reader->GetOutput()->GetDirection(); largestRegion = reader->GetOutput()->GetLargestPossibleRegion(); - - m_NumberOfDimensionsInImage = reader->GetImageIO()->GetNumberOfDimensions(); + // the slice moving direction for a single image can be the + // output image dimensions, since this will indicate that we can + // not move in the slice moving direction + this->m_NumberOfDimensionsInImage = reader->GetImageIO()->GetNumberOfDimensions(); + if ( this->m_NumberOfDimensionsInImage > TOutputImage::ImageDimension ) + { + this->m_NumberOfDimensionsInImage = TOutputImage::ImageDimension; + } + } else if (i == 0) { // ---------------------------- // first of multiple slices - - m_NumberOfDimensionsInImage = reader->GetImageIO()->GetNumberOfDimensions(); + spacing = reader->GetOutput()->GetSpacing(); direction = reader->GetOutput()->GetDirection(); SizeType dimSize = reader->GetOutput()->GetLargestPossibleRegion().GetSize(); - // collapse the number of dimensions in image if any of the last - // dimensions are one - int d; - for (d = static_cast<int>(m_NumberOfDimensionsInImage)-1; d >= 0; --d) - { - if (dimSize[d] == 1) - { - m_NumberOfDimensionsInImage--; - } - else - { - break; - } - } - dimSize[m_NumberOfDimensionsInImage] = m_FileNames.size(); + // compute the moving dimensions index, or the number of image + // dimensions we are going to use + this->m_NumberOfDimensionsInImage = ComputeMovingDimensionIndex( reader ); + + dimSize[this->m_NumberOfDimensionsInImage] = m_FileNames.size(); IndexType start; start.Fill(0); @@ -223,7 +246,7 @@ void ImageSeriesReader<TOutputImage> } // set interslice spacing - spacing[m_NumberOfDimensionsInImage] = interSliceSpacing; + spacing[this->m_NumberOfDimensionsInImage] = interSliceSpacing; } @@ -251,7 +274,7 @@ ImageSeriesReader<TOutputImage> { out->SetRequestedRegion( requestedRegion ); } - else + else { out->SetRequestedRegion( largestRegion ); } @@ -262,14 +285,11 @@ template <class TOutputImage> void ImageSeriesReader<TOutputImage> ::GenerateData() { - typedef ImageFileReader<TOutputImage> ReaderType; - TOutputImage * output = this->GetOutput(); - ImageRegionType requestedRegion = output->GetRequestedRegion(); ImageRegionType largestRegion = output->GetLargestPossibleRegion(); - ImageRegionType sliceRequestedRegion = output->GetRequestedRegion(); + ImageRegionType sliceRegionToRequest = output->GetRequestedRegion(); // Each file must have the same size. SizeType validSize = largestRegion.GetSize(); @@ -278,12 +298,12 @@ void ImageSeriesReader<TOutputImage> // will be less than the output dimension. In this case, set // the last dimension that is other than 1 of validSize to 1. However, if the // input and output have the same number of dimensions, this should - // not be done because it will lower the dimension of the image. - if (TOutputImage::ImageDimension != m_NumberOfDimensionsInImage) + // not be done because it will lower the dimension of the output image. + if (TOutputImage::ImageDimension != this->m_NumberOfDimensionsInImage) { - validSize[m_NumberOfDimensionsInImage] = 1; - sliceRequestedRegion.SetSize( m_NumberOfDimensionsInImage, 1 ); - sliceRequestedRegion.SetIndex( m_NumberOfDimensionsInImage, 0 ); + validSize[this->m_NumberOfDimensionsInImage] = 1; + sliceRegionToRequest.SetSize( this->m_NumberOfDimensionsInImage, 1 ); + sliceRegionToRequest.SetIndex( this->m_NumberOfDimensionsInImage, 0 ); } // Allocate the output buffer @@ -307,13 +327,16 @@ void ImageSeriesReader<TOutputImage> } m_MetaDataDictionaryArray.clear(); - ImageRegionIterator<TOutputImage> ot (output, requestedRegion ); IndexType sliceStartIndex = requestedRegion.GetIndex(); const int numberOfFiles = static_cast<int>(m_FileNames.size()); for ( int i = 0; i != numberOfFiles; ++i ) { - sliceStartIndex[m_NumberOfDimensionsInImage] = i; + + if (TOutputImage::ImageDimension != this->m_NumberOfDimensionsInImage) + { + sliceStartIndex[this->m_NumberOfDimensionsInImage] = i; + } // if this slice in not in the requested region then skip this file if( !requestedRegion.IsInside(sliceStartIndex) ) @@ -330,7 +353,7 @@ void ImageSeriesReader<TOutputImage> reader->SetImageIO( m_ImageIO ); } reader->SetUseStreaming( m_UseStreaming ); - reader->GetOutput()->SetRequestedRegion( sliceRequestedRegion ); + reader->GetOutput()->SetRequestedRegion( sliceRegionToRequest ); reader->Update(); // Deep copy the MetaDataDictionary into the array @@ -358,7 +381,7 @@ void ImageSeriesReader<TOutputImage> ot.SetIndex( sliceStartIndex ); ImageRegionConstIterator<TOutputImage> it (reader->GetOutput(), - sliceRequestedRegion); + sliceRegionToRequest); while (!it.IsAtEnd()) { ot.Set(it.Get()); diff --git a/Utilities/ITK/Code/IO/itkMetaImageIO.cxx b/Utilities/ITK/Code/IO/itkMetaImageIO.cxx index 96a6a81c55a1a3e03b5c11bf8eb674573b4cba6a..eedb4b91e51c6dc5685cf07f64a1181a99f30dc9 100644 --- a/Utilities/ITK/Code/IO/itkMetaImageIO.cxx +++ b/Utilities/ITK/Code/IO/itkMetaImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaImageIO.cxx,v $ Language: C++ - Date: $Date: 2009-05-20 12:16:44 $ - Version: $Revision: 1.100 $ + Date: $Date: 2009-07-07 22:03:39 $ + Version: $Revision: 1.102 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,6 +26,7 @@ #include "itkSpatialOrientationAdapter.h" #include "itkMetaDataObject.h" #include "itkIOCommon.h" +#include <itksys/SystemTools.hxx> namespace itk { @@ -903,7 +904,7 @@ void MetaImageIO::Read(void* buffer) << itksys::SystemTools::GetLastSystemError()); } - m_MetaImage.ElementByteOrderFix(); + m_MetaImage.ElementByteOrderFix( m_IORegion.GetNumberOfPixels() ); } MetaImage * MetaImageIO::GetMetaImagePointer(void) diff --git a/Utilities/ITK/Code/IO/itkMetaImageIO.h b/Utilities/ITK/Code/IO/itkMetaImageIO.h index fa0a6bca9660a67e0b148b6a45e80462ef29749d..962ed245bfa4f94c762d312b6b899a8992b3e77f 100644 --- a/Utilities/ITK/Code/IO/itkMetaImageIO.h +++ b/Utilities/ITK/Code/IO/itkMetaImageIO.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMetaImageIO.h,v $ Language: C++ - Date: $Date: 2009-04-25 12:25:44 $ - Version: $Revision: 1.37 $ + Date: $Date: 2009-06-14 12:30:13 $ + Version: $Revision: 1.38 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -145,7 +145,7 @@ public: /** Determing the subsampling factor in case * we want a coarse version of the image/ - * \Warning this is only used when streaming is on. */ + * \warning this is only used when streaming is on. */ itkSetMacro(SubSamplingFactor,unsigned int); itkGetConstMacro(SubSamplingFactor,unsigned int); diff --git a/Utilities/ITK/Code/IO/itkNiftiImageIO.cxx b/Utilities/ITK/Code/IO/itkNiftiImageIO.cxx index f7c10c0305ee81bd39c817c3639af149c7c4eca0..0b486f86ceeddc28a0f80813e3ffa68d71136c90 100644 --- a/Utilities/ITK/Code/IO/itkNiftiImageIO.cxx +++ b/Utilities/ITK/Code/IO/itkNiftiImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkNiftiImageIO.cxx,v $ Language: C++ - Date: $Date: 2009-04-30 15:37:01 $ - Version: $Revision: 1.84 $ + Date: $Date: 2009-07-29 02:41:20 $ + Version: $Revision: 1.85 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -1173,7 +1173,7 @@ NiftiImageIO std::string FName(this->GetFileName()); // // set the file type - char * tempextension=nifti_find_file_extension(FName.c_str()); + const char * tempextension=nifti_find_file_extension(FName.c_str()); if(tempextension == NULL) { itkExceptionMacro( << diff --git a/Utilities/ITK/Code/IO/itkSiemensVisionImageIO.h b/Utilities/ITK/Code/IO/itkSiemensVisionImageIO.h index 43219c1a8ac7b45edd83865394b620de8cf2ce9d..503579e53b4f506c7e30d0ba22cfab61f6d6cd75 100644 --- a/Utilities/ITK/Code/IO/itkSiemensVisionImageIO.h +++ b/Utilities/ITK/Code/IO/itkSiemensVisionImageIO.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSiemensVisionImageIO.h,v $ Language: C++ - Date: $Date: 2007-12-03 13:13:11 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-06-14 12:30:13 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -69,19 +69,19 @@ public: */ virtual bool CanReadFile(const char* FileNameToRead); - /** Set the spacing and dimension information for the set filename. */ + /* * Set the spacing and dimension information for the set filename. */ // Implemented in superclass // virtual void ReadImageInformation(); - /** Get the type of the pixel. */ + /* * Get the type of the pixel. */ // Implemented in superclass // virtual const std::type_info& GetPixelType() const; - /** Reads the data from disk into the memory buffer provided. */ + /* * Reads the data from disk into the memory buffer provided. */ // Implemented in superclass // virtual void Read(void* buffer); - /** Compute the size (in bytes) of the components of a pixel. For + /* * Compute the size (in bytes) of the components of a pixel. For * example, and RGB pixel of unsigned char would have a * component size of 1 byte. */ // Implemented in superclass @@ -89,7 +89,7 @@ public: /*-------- This part of the interfaces deals with writing data. ----- */ - /** Determine if the file can be written with this ImageIO implementation. + /* * Determine if the file can be written with this ImageIO implementation. * \param FileNameToWrite The name of the file to test for writing. * \author Hans J. Johnson * \post Sets classes ImageIOBase::m_FileName variable to be FileNameToWrite @@ -98,11 +98,11 @@ public: // Implemented in superclass // virtual bool CanWriteFile(const char * FileNameToWrite); - /** Set the spacing and dimension information for the set filename. */ + /* * Set the spacing and dimension information for the set filename. */ // Implemented in superclass // virtual void WriteImageInformation(); - /** Writes the data to disk from the memory buffer provided. Make sure + /* * Writes the data to disk from the memory buffer provided. Make sure * that the IORegions has been set properly. */ // Implemented in superclass // virtual void Write(const void* buffer); diff --git a/Utilities/ITK/Code/IO/itkStimulateImageIO.cxx b/Utilities/ITK/Code/IO/itkStimulateImageIO.cxx index 15308d2a5e5db52e101bf1a56dfacd3aa69c7434..195f304937f080b116c69ffdcada003a2232fcb0 100755 --- a/Utilities/ITK/Code/IO/itkStimulateImageIO.cxx +++ b/Utilities/ITK/Code/IO/itkStimulateImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkStimulateImageIO.cxx,v $ Language: C++ - Date: $Date: 2009-03-23 16:50:04 $ - Version: $Revision: 1.26 $ + Date: $Date: 2009-05-27 17:48:12 $ + Version: $Revision: 1.27 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -295,6 +295,15 @@ void StimulateImageIO::InternalReadImageInformation(std::ifstream& file) while((file.getline(line, 255), file.gcount() > 0)) { text = line; +#ifdef __CYGWIN__ + // If terminated with \r\n, getline only removes \n. Explictly + // strip \r. + if (text.size() > 0 + && (text[text.size() - 1] == '\r')) + { + text.resize(text.size() - 1); + } +#endif if ( text.find("numDim") < text.length()) { diff --git a/Utilities/ITK/Code/IO/itkTIFFImageIO.cxx b/Utilities/ITK/Code/IO/itkTIFFImageIO.cxx index 042dc49643dada68fc7a233699a7013c3f18f0d5..43f3b16ad20f1117515b6d7b5aa904e9f8ff923a 100644 --- a/Utilities/ITK/Code/IO/itkTIFFImageIO.cxx +++ b/Utilities/ITK/Code/IO/itkTIFFImageIO.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTIFFImageIO.cxx,v $ Language: C++ - Date: $Date: 2009-04-05 10:56:48 $ - Version: $Revision: 1.65 $ + Date: $Date: 2009-07-03 18:41:50 $ + Version: $Revision: 1.67 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -1729,6 +1729,11 @@ void TIFFImageIO::InternalWrite(const void* buffer) TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, scomponents); TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps); // Fix for stype TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); + if(this->GetComponentType() == SHORT + || this->GetComponentType() == CHAR) + { + TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT); + } TIFFSetField(tif, TIFFTAG_SOFTWARE, "InsightToolkit"); if ( scomponents > 3 ) diff --git a/Utilities/ITK/Code/IO/itkTestDriver.cxx b/Utilities/ITK/Code/IO/itkTestDriver.cxx index b55b8a7b21ae5a44f237e57059445e9e66efd308..68562e8f038e9f50e9fb1c6752e93faa51c85af2 100644 --- a/Utilities/ITK/Code/IO/itkTestDriver.cxx +++ b/Utilities/ITK/Code/IO/itkTestDriver.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTestDriver.cxx,v $ Language: C++ - Date: $Date: 2008-11-09 18:18:52 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-07-28 18:30:04 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -333,8 +333,6 @@ int main(int ac, char* av[] ) std::vector< char* > args; typedef std::pair< char *, char *> ComparePairType; std::vector< ComparePairType > compareList; - // with putenv(), we must keep the string allocated - std::vector< std::string > envList; // parse the command line int i = 1; @@ -357,8 +355,24 @@ int main(int ac, char* av[] ) libpath += KWSYS_SHARED_FORWARD_PATH_SEP; libpath += oldenv; } - envList.push_back( libpath ); - putenv( const_cast<char *>( envList.back().c_str() ) ); + itksys::SystemTools::PutEnv( libpath.c_str() ); + // on some 64 bit systems, LD_LIBRARY_PATH_64 is used before + // LD_LIBRARY_PATH if it is set. It can lead the test to load + // the system library instead of the expected one, so this + // var must also be set + if( std::string(KWSYS_SHARED_FORWARD_LDPATH) == "LD_LIBRARY_PATH" ) + { + std::string libpath = "LD_LIBRARY_PATH_64"; + libpath += "="; + libpath += av[i+1]; + char * oldenv = getenv("LD_LIBRARY_PATH_64"); + if( oldenv ) + { + libpath += KWSYS_SHARED_FORWARD_PATH_SEP; + libpath += oldenv; + } + itksys::SystemTools::PutEnv( libpath.c_str() ); + } i += 2; } else if( !skip && strcmp(av[i], "--add-before-env") == 0 ) @@ -377,8 +391,7 @@ int main(int ac, char* av[] ) env += KWSYS_SHARED_FORWARD_PATH_SEP; env += oldenv; } - envList.push_back( env ); - putenv( const_cast<char *>( envList.back().c_str() ) ); + itksys::SystemTools::PutEnv( env.c_str() ); i += 3; } else if( !skip && strcmp(av[i], "--compare") == 0 ) diff --git a/Utilities/ITK/Code/Numerics/FEM/CMakeLists.txt b/Utilities/ITK/Code/Numerics/FEM/CMakeLists.txt index 4c8f8fc7e8e50e5f40a1ca0b1be98a8ea07e68fa..7a295544f405d4e9887cb17e3f2497b252cc1abd 100644 --- a/Utilities/ITK/Code/Numerics/FEM/CMakeLists.txt +++ b/Utilities/ITK/Code/Numerics/FEM/CMakeLists.txt @@ -183,7 +183,25 @@ SOURCE_GROUP("Source Files Template" REGULAR_EXPRESSION ./*.txx) INCLUDE_DIRECTORIES(${VXL_NETLIB_INCLUDE_DIR}) # Some .cxx files need f2c.h. # Build the library -ADD_LIBRARY(ITKFEM ${FEM_SRCS}) +# For cygwin and mingw, there are issues with the ITKFEM shared library +# Force ITKFEM on these platforms to be static until these issues are resolved +# +IF(WIN32) + IF(CMAKE_COMPILER_IS_GNUCXX) + IF(MINGW) + ADD_LIBRARY(ITKFEM STATIC ${FEM_SRCS}) + ELSEIF(CYGWIN) + ADD_LIBRARY(ITKFEM STATIC ${FEM_SRCS}) + ELSE (MINGW) + ADD_LIBRARY(ITKFEM ${FEM_SRCS}) + ENDIF (MINGW) + ELSE(CMAKE_COMPILER_IS_GNUCXX) + ADD_LIBRARY(ITKFEM ${FEM_SRCS}) + ENDIF(CMAKE_COMPILER_IS_GNUCXX) +ELSE(WIN32) + ADD_LIBRARY(ITKFEM ${FEM_SRCS}) +ENDIF(WIN32) + TARGET_LINK_LIBRARIES(ITKFEM ITKBasicFilters ITKIO) diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkDenseFrequencyContainer.cxx b/Utilities/ITK/Code/Numerics/Statistics/itkDenseFrequencyContainer.cxx index 851b8b315791b3459947d627aa0fbbbca537379a..837ba8da4711fe1b344f3fca7b10fd51e596cf6c 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkDenseFrequencyContainer.cxx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkDenseFrequencyContainer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkDenseFrequencyContainer.cxx,v $ Language: C++ - Date: $Date: 2009-03-04 15:23:44 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-08-08 20:19:11 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -76,8 +76,20 @@ DenseFrequencyContainer return false; } FrequencyType frequency = this->GetFrequency(id); - (*m_FrequencyContainer)[id] = frequency + value; + + const FrequencyType largestIntegerThatFitsInFloat = 16777216; + + if( largestIntegerThatFitsInFloat - frequency < value ) + { + itkExceptionMacro("Frequency container saturated for Instance "); + } + else + { + (*m_FrequencyContainer)[id] = frequency + value; + } + m_TotalFrequency += value; + return true; } diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDistribution.cxx b/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDistribution.cxx index edf0f5f659018d8e8cef1f478bab19440f436780..f344005044a957f432e7f8947582ada9cd298192 100644 --- a/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDistribution.cxx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkGaussianDistribution.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianDistribution.cxx,v $ Language: C++ - Date: $Date: 2009-04-05 10:56:50 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-08-07 15:27:37 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -181,20 +181,16 @@ double GaussianDistribution ::PDF(double x) { - static const double oneonsqrttwopi = 1.0 / vcl_sqrt( 2.0 * vnl_math::pi ); - - return oneonsqrttwopi * vcl_exp(-0.5*x*x); + return vnl_math::one_over_sqrt2pi * vcl_exp(-0.5*x*x); } double GaussianDistribution ::PDF(double x, double mean, double variance) { - static const double oneonsqrttwopi = 1.0 / vcl_sqrt( 2.0 * vnl_math::pi ); - double xminusmean = x - mean; - return (oneonsqrttwopi / vcl_sqrt(variance)) + return (vnl_math::one_over_sqrt2pi / vcl_sqrt(variance)) * vcl_exp(-0.5*xminusmean*xminusmean / variance); } @@ -301,7 +297,7 @@ GaussianDistribution for( newt=0; newt < 3; newt++ ) { - dq = 0.5e+0 * vnl_erfc( dx / 1.414213562373095e+0 ) - dp; + dq = 0.5e+0 * vnl_erfc( dx * vnl_math::sqrt1_2 ) - dp; ddq = vcl_exp( -0.5e+0 * dx * dx ) / 2.506628274631000e+0; dx = dx + dq / ddq; } diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramGenerator.h b/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramGenerator.h index fa20b5de41d2537a5cb482125c4c231c1e3cc336..29596c5ec7b175fabf0ea9d72f0910690514d41f 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramGenerator.h +++ b/Utilities/ITK/Code/Numerics/Statistics/itkListSampleToHistogramGenerator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkListSampleToHistogramGenerator.h,v $ Language: C++ - Date: $Date: 2009-03-04 15:23:55 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-08-11 01:31:57 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -43,7 +43,7 @@ namespace Statistics { * * The upper bound and lower bound of the histogram will be automatically * determined by the FindSampleBound funtion in itkStatisticsAlgorithm.h & - * .txx. The hitogram object's upper bound will be slightly bigger than + * .txx. The histogram object's upper bound will be slightly bigger than * the uppper bound from the FindSampleBound to include the maximum values * in the Histogram object. To extend the upper bound of the histogram. this * class internally uses the intervals between two bins and the marginal scale @@ -52,10 +52,10 @@ namespace Statistics { * upper bound of Histogram will be upper bound of the list sample + * (bin interval) / 100 ( = marginal scale). * - * The result historam has equi-size bins along each axe. + * The result histogram has equi-size bins along each axes. * * NOTE: The second template argument, THistogramMeasurement should be - * float-point type (float or double). + * floating-point type (float or double). * * <b> Recent API changes </b> * The class is templated over the list sample, the frequency measurement diff --git a/Utilities/ITK/Code/Numerics/Statistics/itkSparseFrequencyContainer.cxx b/Utilities/ITK/Code/Numerics/Statistics/itkSparseFrequencyContainer.cxx index 80185d68f4466ac66f6b651f167905db9d653c92..baa1403e2938ca045b8d0dd80c2be8ddf5cf3c9e 100755 --- a/Utilities/ITK/Code/Numerics/Statistics/itkSparseFrequencyContainer.cxx +++ b/Utilities/ITK/Code/Numerics/Statistics/itkSparseFrequencyContainer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSparseFrequencyContainer.cxx,v $ Language: C++ - Date: $Date: 2009-03-04 19:29:54 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-08-08 20:19:11 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -81,8 +81,20 @@ SparseFrequencyContainer // No need to test for bounds because in a map container the // element is allocated if the key doesn't exist yet FrequencyType frequency = this->GetFrequency(id); - m_FrequencyContainer[id] = frequency + value; + + const FrequencyType largestIntegerThatFitsInFloat = 16777216; + + if( largestIntegerThatFitsInFloat - frequency < value ) + { + itkExceptionMacro("Frequency container saturated for Instance "); + } + else + { + m_FrequencyContainer[id] = frequency + value; + } + m_TotalFrequency += value; + return true; } diff --git a/Utilities/ITK/Code/Numerics/itkAmoebaOptimizer.cxx b/Utilities/ITK/Code/Numerics/itkAmoebaOptimizer.cxx index 823dd857e6f3cb6cd47a77c8147f42bde25065f5..60b634d73c00ed6a71389b28ef16897c179dffc0 100644 --- a/Utilities/ITK/Code/Numerics/itkAmoebaOptimizer.cxx +++ b/Utilities/ITK/Code/Numerics/itkAmoebaOptimizer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAmoebaOptimizer.cxx,v $ Language: C++ - Date: $Date: 2009-01-26 13:33:10 $ - Version: $Revision: 1.31 $ + Date: $Date: 2009-09-12 20:00:29 $ + Version: $Revision: 1.33 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -48,6 +48,12 @@ AmoebaOptimizer delete m_VnlOptimizer; } +const std::string +AmoebaOptimizer +::GetStopConditionDescription() const +{ + return m_StopConditionDescription.str(); +} /** * PrintSelf @@ -67,7 +73,6 @@ AmoebaOptimizer << (m_AutomaticInitialSimplex ? "On" : "Off") << std::endl; os << indent << "InitialSimplexDelta: " << m_InitialSimplexDelta << std::endl; - } /** Return Current Value */ @@ -164,6 +169,7 @@ AmoebaOptimizer CostFunctionAdaptorType * adaptor = new CostFunctionAdaptorType( numberOfParameters ); + SingleValuedNonLinearOptimizer::SetCostFunction( costFunction ); adaptor->SetCostFunction( costFunction ); if( m_OptimizerInitialized ) @@ -193,6 +199,8 @@ AmoebaOptimizer { this->InvokeEvent( StartEvent() ); + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": Running"; if( this->GetMaximize() ) { @@ -245,6 +253,26 @@ AmoebaOptimizer this->SetCurrentPosition( parameters ); + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": "; + if (static_cast<unsigned int>(m_VnlOptimizer->get_num_evaluations()) + < m_MaximumNumberOfIterations) + { + m_StopConditionDescription << "Both parameters convergence tolerance (" + << m_ParametersConvergenceTolerance + << ") and function convergence tolerance (" + << m_FunctionConvergenceTolerance + << ") have been met in " + << m_VnlOptimizer->get_num_evaluations() + << " iterations."; + } + else + { + m_StopConditionDescription << "Maximum number of iterations exceeded." + << " Number of iterations is " + << m_MaximumNumberOfIterations; + + } this->InvokeEvent( EndEvent() ); } diff --git a/Utilities/ITK/Code/Numerics/itkAmoebaOptimizer.h b/Utilities/ITK/Code/Numerics/itkAmoebaOptimizer.h index 907a4c9893fc52499b1fd1220a7139c12941c226..2f06b86c9c806cd452837f44054a00dee32cb0de 100644 --- a/Utilities/ITK/Code/Numerics/itkAmoebaOptimizer.h +++ b/Utilities/ITK/Code/Numerics/itkAmoebaOptimizer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAmoebaOptimizer.h,v $ Language: C++ - Date: $Date: 2007-03-22 14:29:13 $ - Version: $Revision: 1.25 $ + Date: $Date: 2009-06-24 12:02:50 $ + Version: $Revision: 1.26 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -85,7 +85,7 @@ public: * terminate after the maximum number of iterations has been reached. * The default value is 500. */ virtual void SetMaximumNumberOfIterations( unsigned int n ); - itkGetMacro( MaximumNumberOfIterations, unsigned int ); + itkGetConstMacro( MaximumNumberOfIterations, unsigned int ); /** Set/Get the mode which determines how the amoeba algorithm * defines the initial simplex. Default is @@ -97,12 +97,12 @@ public: * x0[d-1]]. */ itkSetMacro(AutomaticInitialSimplex, bool); itkBooleanMacro(AutomaticInitialSimplex); - itkGetMacro(AutomaticInitialSimplex, bool); + itkGetConstMacro(AutomaticInitialSimplex, bool); /** Set/Get the deltas that are used to define the initial simplex * when AutomaticInitialSimplex is off. */ itkSetMacro(InitialSimplexDelta, ParametersType); - itkGetMacro(InitialSimplexDelta, ParametersType); + itkGetConstMacro(InitialSimplexDelta, ParametersType); /** The optimization algorithm will terminate when the simplex * diameter and the difference in cost function at the corners of @@ -113,9 +113,12 @@ public: * SetFunctionConvergenceTolerance() with the default value being * 1e-4. */ virtual void SetParametersConvergenceTolerance( double tol ); - itkGetMacro( ParametersConvergenceTolerance, double ); + itkGetConstMacro( ParametersConvergenceTolerance, double ); virtual void SetFunctionConvergenceTolerance( double tol ); - itkGetMacro( FunctionConvergenceTolerance, double ); + itkGetConstMacro( FunctionConvergenceTolerance, double ); + + /** Report the reason for stopping. */ + const std::string GetStopConditionDescription() const; /** Return Current Value */ MeasureType GetValue() const; @@ -139,6 +142,8 @@ private: bool m_AutomaticInitialSimplex; ParametersType m_InitialSimplexDelta; + + OStringStream m_StopConditionDescription; }; } // end namespace itk diff --git a/Utilities/ITK/Code/Numerics/itkCumulativeGaussianOptimizer.cxx b/Utilities/ITK/Code/Numerics/itkCumulativeGaussianOptimizer.cxx index 07e7a51aeb2602ec251d15c8f09a69802f8cea8a..b7e2b8cc982ee7294c0d201188f3b38e3602f9f5 100644 --- a/Utilities/ITK/Code/Numerics/itkCumulativeGaussianOptimizer.cxx +++ b/Utilities/ITK/Code/Numerics/itkCumulativeGaussianOptimizer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCumulativeGaussianOptimizer.cxx,v $ Language: C++ - Date: $Date: 2009-04-05 10:56:48 $ - Version: $Revision: 1.17 $ + Date: $Date: 2009-08-07 15:27:39 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -38,6 +38,7 @@ CumulativeGaussianOptimizer::CumulativeGaussianOptimizer() m_FitError = 0; m_FinalSampledArray = NULL; m_CumulativeGaussianArray = NULL; + m_StopConditionDescription << this->GetNameOfClass() << ": Constructed"; } CumulativeGaussianOptimizer::~CumulativeGaussianOptimizer() @@ -111,11 +112,13 @@ CumulativeGaussianOptimizer extendedArray = ExtendGaussian(sampledGaussianArray, extendedArray, sampledGaussianArraySize); MeasureGaussianParameters(extendedArray); + bool smallChangeBetweenIterations = false; while (averageSumOfSquaredDifferences >= m_DifferenceTolerance) { - for(int j = 0; j < extendedArraySize; j++) + for(int j = 0; j < extendedArraySize; j++) + { extendedArrayCopy->put(j, extendedArray->get(j)); - + } extendedArray = RecalculateExtendedArrayFromGaussianParameters(sampledGaussianArray, extendedArray, sampledGaussianArraySize); @@ -130,8 +133,28 @@ CumulativeGaussianOptimizer // Stop if there is a very very very small change between iterations. if(vcl_fabs(temp - averageSumOfSquaredDifferences) <= m_DifferenceTolerance) + { + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": " + << "Change between iterations (" + << vcl_fabs(temp - averageSumOfSquaredDifferences) + << ") is less than DifferenceTolerance (" + << m_DifferenceTolerance + << ")."; break; + } } + if (!smallChangeBetweenIterations) + { + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": " + << "Average sum of squared differences (" + << averageSumOfSquaredDifferences + << ") is less than DifferenceTolerance (" + << m_DifferenceTolerance + << ")."; + } + // Update the mean calculation. m_ComputedMean = m_ComputedMean - m_OffsetForMean; @@ -163,15 +186,16 @@ void CumulativeGaussianOptimizer // Calculate the standard deviation for(int i = 0; i < (int)(array->GetNumberOfElements()); i++) + { m_ComputedStandardDeviation += array->get(i) * vcl_pow((i - m_ComputedMean), 2); - + } m_ComputedStandardDeviation = vcl_sqrt(m_ComputedStandardDeviation/sum ); // For the ERF, sum is the difference between the lower and upper intensities. m_ComputedTransitionHeight = sum; // Calculate the amplitude. - m_ComputedAmplitude = sum / (m_ComputedStandardDeviation * vcl_sqrt(2*3.14159265)); + m_ComputedAmplitude = sum / (m_ComputedStandardDeviation * vcl_sqrt(2*vnl_math::pi)); } void @@ -226,6 +250,10 @@ void CumulativeGaussianOptimizer ::StartOptimization() { + this->InvokeEvent( StartEvent() ); + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": Running"; + // Declare arrays. int cumGaussianArraySize = m_CumulativeGaussianArray->GetNumberOfElements(); int sampledGaussianArraySize = cumGaussianArraySize; @@ -239,15 +267,17 @@ CumulativeGaussianOptimizer // Make a copy of the Cumulative Gaussian sampled data array. for(int j = 0; j < cumGaussianArraySize; j++) + { cumGaussianArrayCopy->put(j, m_CumulativeGaussianArray->get(j)); - + } // Take the derivative of the data array resulting in a Gaussian array. MeasureType * derivative = new MeasureType(); derivative->SetSize(cumGaussianArraySize - 1); for(int i=1; i < (int)(derivative->GetNumberOfElements()+1); i++) + { derivative->put(i-1, m_CumulativeGaussianArray->get(i) - m_CumulativeGaussianArray->get(i-1) ); - + } m_CumulativeGaussianArray = derivative; // Iteratively recalculate and resample the Gaussian array. @@ -255,15 +285,17 @@ CumulativeGaussianOptimizer // Generate new Gaussian array with final parameters. for(int i = 0; i < sampledGaussianArraySize; i++) + { sampledGaussianArray->put(i, m_ComputedAmplitude * vcl_exp(- ( vcl_pow((i-m_ComputedMean),2) / (2*vcl_pow(m_ComputedStandardDeviation,2)) ) )); - + } // Add 0.5 to the mean of the sampled Gaussian curve to make up for the 0.5 // shift during derivation, then take the integral of the Gaussian sample // to produce a Cumulative Gaussian. for(int i = sampledGaussianArraySize-1; i > 0; i--) + { sampledGaussianArray->put(i-1, sampledGaussianArray->get(i) - sampledGaussianArray->get(i-1)); - + } m_ComputedMean += 0.5; // Find the best vertical shift that minimizes the least square error. @@ -271,8 +303,9 @@ CumulativeGaussianOptimizer // Add constant c to array. for(int i = 0; i < (int)(sampledGaussianArray->GetNumberOfElements()); i++) + { sampledGaussianArray->put(i, sampledGaussianArray->get(i) + c); - + } // Calculate the mean, standard deviation, lower and upper asymptotes of the // sampled Cumulative Gaussian. int floorOfMean = (int)(m_ComputedMean); @@ -327,38 +360,49 @@ CumulativeGaussianOptimizer double c = 0; int size = originalArray->GetNumberOfElements(); for(int i=0; i<size; i++) + { c += originalArray->get(i); + } for(int i=0; i<size; i++) + { c -= newArray->get(i); + } return (c/size); } +const std::string +CumulativeGaussianOptimizer +::GetStopConditionDescription() const +{ + return m_StopConditionDescription.str(); +} + void CumulativeGaussianOptimizer ::PrintSelf(std::ostream &os, Indent indent) const { Superclass::PrintSelf(os,indent); - os << indent << "Difference Tolerance = " << m_DifferenceTolerance - << "Computed Mean = " << m_ComputedMean - << "Computed Standard Deviation = " << m_ComputedStandardDeviation - << "Computed Amplitude = " << m_ComputedAmplitude - << "Computed Transition Height = " << m_ComputedTransitionHeight - << std::endl; - - os << indent << "Upper Asymptote = " << m_UpperAsymptote - << "Lower Asymptote = " << m_LowerAsymptote - << "Offset For Mean = " << m_OffsetForMean - << "Verbose = " << m_Verbose - << "Fit Error = " << m_FitError - << std::endl; + os << indent << "Difference Tolerance = " << m_DifferenceTolerance << std::endl; + os << indent << "Computed Mean = " << m_ComputedMean << std::endl; + os << indent << "Computed Standard Deviation = " << m_ComputedStandardDeviation << std::endl; + os << indent << "Computed Amplitude = " << m_ComputedAmplitude << std::endl; + os << indent << "Computed Transition Height = " << m_ComputedTransitionHeight << std::endl; + + os << indent << "Upper Asymptote = " << m_UpperAsymptote << std::endl; + os << indent << "Lower Asymptote = " << m_LowerAsymptote << std::endl; + os << indent << "Offset For Mean = " << m_OffsetForMean << std::endl; + os << indent << "Verbose = " << m_Verbose << std::endl; + os << indent << "Fit Error = " << m_FitError << std::endl; + + os << indent << "StopConditionDescription: " << m_StopConditionDescription << std::endl; if(m_FinalSampledArray) { - os << indent << "FinalSampledArray = " << m_FinalSampledArray << std::endl; + os << indent << "Final Sampled Array = " << m_FinalSampledArray << std::endl; } else { - os << indent << "FinalSampledArray = [not defined] " << std::endl; + os << indent << "Final Sampled Array = [not defined] " << std::endl; } } diff --git a/Utilities/ITK/Code/Numerics/itkCumulativeGaussianOptimizer.h b/Utilities/ITK/Code/Numerics/itkCumulativeGaussianOptimizer.h index 5eb68fe38a9a976b5ace6dc71372733df59308e9..de0b63bf91f4d7fcae7f9282489c846b119b97b8 100644 --- a/Utilities/ITK/Code/Numerics/itkCumulativeGaussianOptimizer.h +++ b/Utilities/ITK/Code/Numerics/itkCumulativeGaussianOptimizer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkCumulativeGaussianOptimizer.h,v $ Language: C++ - Date: $Date: 2007-03-29 19:37:00 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-06-24 12:02:50 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -86,6 +86,9 @@ public: /** Print an array. */ void PrintArray(MeasureType * array); + /** Report the reason for stopping. */ + const std::string GetStopConditionDescription() const; + protected: CumulativeGaussianOptimizer(); virtual ~CumulativeGaussianOptimizer(); @@ -157,6 +160,10 @@ private: /** Find the constant of the integrated sample. */ double VerticalBestShift(MeasureType * originalArray, MeasureType * newArray); + + /** Describe the stop condition */ + OStringStream m_StopConditionDescription; + }; } // end namespace itk diff --git a/Utilities/ITK/Code/Numerics/itkExhaustiveOptimizer.cxx b/Utilities/ITK/Code/Numerics/itkExhaustiveOptimizer.cxx index 145d5dcc856e6ce94e3a97cc39e36ce639484084..f40178b64265eb0d1f86944d5d2d998551c99325 100644 --- a/Utilities/ITK/Code/Numerics/itkExhaustiveOptimizer.cxx +++ b/Utilities/ITK/Code/Numerics/itkExhaustiveOptimizer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkExhaustiveOptimizer.cxx,v $ Language: C++ - Date: $Date: 2008-05-06 09:42:44 $ - Version: $Revision: 1.10 $ + Date: $Date: 2009-06-24 23:35:49 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -37,6 +37,8 @@ ExhaustiveOptimizer m_CurrentIndex.Fill(0); m_Stop = false; m_NumberOfSteps.Fill(0); + + m_StopConditionDescription.str(""); } @@ -56,6 +58,9 @@ ExhaustiveOptimizer { itkDebugMacro("StartWalking"); this->InvokeEvent( StartEvent() ); + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": Running"; + ParametersType initialPos = this->GetInitialPosition(); m_MinimumMetricValuePosition = initialPos; @@ -143,6 +148,10 @@ ExhaustiveOptimizer break; } + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": Running. "; + m_StopConditionDescription << "@ index " << this->GetCurrentIndex() << " value is " << this->GetCurrentValue(); + this->InvokeEvent( IterationEvent() ); this->AdvanceOneStep(); m_CurrentIteration++; @@ -203,6 +212,9 @@ ExhaustiveOptimizer if( idx==spaceDimension ) { m_Stop = true; + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": "; + m_StopConditionDescription << "Completed sampling of parametric space of size " << spaceDimension; } for(unsigned int i=0; i<spaceDimension; i++) @@ -214,6 +226,13 @@ ExhaustiveOptimizer } +const std::string +ExhaustiveOptimizer +::GetStopConditionDescription() const +{ + return m_StopConditionDescription.str(); +} + void ExhaustiveOptimizer ::PrintSelf(std::ostream& os, Indent indent) const diff --git a/Utilities/ITK/Code/Numerics/itkExhaustiveOptimizer.h b/Utilities/ITK/Code/Numerics/itkExhaustiveOptimizer.h index a7ae6d9d601c2170fc4ea43fa14965652ad0495a..88bfde76a92a375b3bee376b7f4bd8cec30c8cae 100644 --- a/Utilities/ITK/Code/Numerics/itkExhaustiveOptimizer.h +++ b/Utilities/ITK/Code/Numerics/itkExhaustiveOptimizer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkExhaustiveOptimizer.h,v $ Language: C++ - Date: $Date: 2009-01-24 21:04:35 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-06-24 23:35:49 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -92,7 +92,7 @@ public: itkNewMacro(Self); /** Run-time type information (and related methods). */ - itkTypeMacro( ExhaustiveOptimizer, SingleValuedNonLinearOptimizer ); + itkTypeMacro( ExhaustiveOptimizer, SingleValuedNonLinearOptimizer ); virtual void StartOptimization( void ); @@ -112,6 +112,8 @@ public: itkGetConstReferenceMacro( CurrentIndex, ParametersType ); itkGetConstReferenceMacro( MaximumNumberOfIterations, unsigned long ); + /** Get the reason for termination */ + const std::string GetStopConditionDescription() const; protected: ExhaustiveOptimizer(); @@ -141,6 +143,7 @@ private: ExhaustiveOptimizer(const Self&); //purposely not implemented void operator=(const Self&);//purposely not implemented + OStringStream m_StopConditionDescription; }; } // end namespace itk diff --git a/Utilities/ITK/Code/Numerics/itkGradientDescentOptimizer.cxx b/Utilities/ITK/Code/Numerics/itkGradientDescentOptimizer.cxx index fcacbc6e21dcefe34906be1ad91881d5ef11004a..c7f0f7199b6b519ebbe5ae4af4dabe311c921240 100644 --- a/Utilities/ITK/Code/Numerics/itkGradientDescentOptimizer.cxx +++ b/Utilities/ITK/Code/Numerics/itkGradientDescentOptimizer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGradientDescentOptimizer.cxx,v $ Language: C++ - Date: $Date: 2007-03-29 19:37:01 $ - Version: $Revision: 1.30 $ + Date: $Date: 2009-06-24 12:02:51 $ + Version: $Revision: 1.31 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -39,6 +39,14 @@ GradientDescentOptimizer m_Maximize = false; m_Value = 0.0; m_StopCondition = MaximumNumberOfIterations; + m_StopConditionDescription << this->GetNameOfClass() << ": "; +} + +const std::string +GradientDescentOptimizer +::GetStopConditionDescription() const +{ + return m_StopConditionDescription.str(); } void @@ -100,6 +108,8 @@ GradientDescentOptimizer m_Stop = false; + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": "; InvokeEvent( StartEvent() ); while( !m_Stop ) { @@ -114,6 +124,7 @@ GradientDescentOptimizer // An exception has occurred. // Terminate immediately. m_StopCondition = MetricError; + m_StopConditionDescription << "Metric error"; StopOptimization(); // Pass exception to caller @@ -123,6 +134,7 @@ GradientDescentOptimizer if( m_Stop ) { + m_StopConditionDescription << "StopOptimization() called"; break; } @@ -132,17 +144,16 @@ GradientDescentOptimizer if( m_CurrentIteration >= m_NumberOfIterations ) { + m_StopConditionDescription << "Maximum number of iterations (" + << m_NumberOfIterations + << ") exceeded."; m_StopCondition = MaximumNumberOfIterations; StopOptimization(); break; } - } - - } - /** * Stop optimization */ diff --git a/Utilities/ITK/Code/Numerics/itkGradientDescentOptimizer.h b/Utilities/ITK/Code/Numerics/itkGradientDescentOptimizer.h index dd162b12b3ce48f02e7a637103d6e003da4c61e8..c3560de30e9e8f29ce5ad4dca65f0b18aa8c1d6c 100644 --- a/Utilities/ITK/Code/Numerics/itkGradientDescentOptimizer.h +++ b/Utilities/ITK/Code/Numerics/itkGradientDescentOptimizer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGradientDescentOptimizer.h,v $ Language: C++ - Date: $Date: 2007-03-22 21:39:37 $ - Version: $Revision: 1.30 $ + Date: $Date: 2009-06-24 12:02:51 $ + Version: $Revision: 1.31 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -18,7 +18,7 @@ #define __itkGradientDescentOptimizer_h #include "itkSingleValuedNonLinearOptimizer.h" - +#include <string> namespace itk { @@ -109,18 +109,18 @@ public: itkGetConstReferenceMacro( NumberOfIterations, unsigned long ); /** Get the current iteration number. */ - itkGetConstMacro( CurrentIteration, unsigned int ); + itkGetConstMacro( CurrentIteration, unsigned long ); /** Get the current value. */ itkGetConstReferenceMacro( Value, double ); /** Get Stop condition. */ itkGetConstReferenceMacro( StopCondition, StopConditionType ); + const std::string GetStopConditionDescription() const; - /** Get Stop condition. */ + /** Get Gradient condition. */ itkGetConstReferenceMacro( Gradient, DerivativeType ); - protected: GradientDescentOptimizer(); virtual ~GradientDescentOptimizer() {}; @@ -141,7 +141,7 @@ private: StopConditionType m_StopCondition; unsigned long m_NumberOfIterations; unsigned long m_CurrentIteration; - + OStringStream m_StopConditionDescription; }; } // end namespace itk diff --git a/Utilities/ITK/Code/Numerics/itkLBFGSBOptimizer.cxx b/Utilities/ITK/Code/Numerics/itkLBFGSBOptimizer.cxx index 218cff7a3a924407b6b65fc39b3b8661e5557988..713f3b0b9589b221fc2aad8fa28e9cea241bc8f4 100644 --- a/Utilities/ITK/Code/Numerics/itkLBFGSBOptimizer.cxx +++ b/Utilities/ITK/Code/Numerics/itkLBFGSBOptimizer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLBFGSBOptimizer.cxx,v $ Language: C++ - Date: $Date: 2009-01-24 21:04:35 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-06-24 12:02:51 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,6 +21,9 @@ #include "vnl/algo/vnl_lbfgsb.h" #include <vnl/vnl_math.h> +extern "C" { + extern double v3p_netlib_dpmeps_(); +} namespace itk { @@ -47,7 +50,7 @@ public: virtual bool report_iter(); private: - LBFGSBOptimizer* m_ItkObj; + LBFGSBOptimizer* m_ItkObj; }; @@ -74,6 +77,7 @@ LBFGSBOptimizer m_CurrentIteration = 0; m_Value = 0.0; m_InfinityNormOfProjectedGradient = 0.0; + m_StopConditionDescription.str(""); } @@ -386,6 +390,9 @@ LBFGSBOptimizer ParametersType parameters( this->GetInitialPosition() ); + // Clear the description + m_StopConditionDescription.str(""); + // vnl optimizers return the solution by reference // in the variable provided as initial position m_VnlOptimizer->minimize( parameters ); @@ -436,6 +443,9 @@ LBFGSBOptimizerHelper // Return true to terminate the optimization loop. if( this->num_iterations_ > m_ItkObj->m_MaximumNumberOfIterations ) { + m_ItkObj->m_StopConditionDescription << + "Too many iterations. Iterations = " << + m_ItkObj->m_MaximumNumberOfIterations; return true; } else @@ -444,6 +454,68 @@ LBFGSBOptimizerHelper } } +const std::string +LBFGSBOptimizer:: +GetStopConditionDescription() const +{ + if (m_VnlOptimizer) + { + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": "; + switch (m_VnlOptimizer->get_failure_code()) + { + case vnl_nonlinear_minimizer::ERROR_FAILURE: + m_StopConditionDescription << "Failure"; + break; + case vnl_nonlinear_minimizer::ERROR_DODGY_INPUT: + m_StopConditionDescription << "Dodgy input"; + break; + case vnl_nonlinear_minimizer::CONVERGED_FTOL: + m_StopConditionDescription << "Function tolerance reached after " + << m_CurrentIteration + << " iterations. " + << "The relative reduction of the cost function <= " + << m_CostFunctionConvergenceFactor * v3p_netlib_dpmeps_() + << " = CostFunctionConvergenceFactor (" + << m_CostFunctionConvergenceFactor + << ") * machine precision (" + << v3p_netlib_dpmeps_() + << ")."; + break; + case vnl_nonlinear_minimizer::CONVERGED_XTOL: + m_StopConditionDescription << "Solution tolerance reached"; + break; + case vnl_nonlinear_minimizer::CONVERGED_XFTOL: + m_StopConditionDescription << "Solution and Function tolerance both reached"; + break; + case vnl_nonlinear_minimizer::CONVERGED_GTOL: + m_StopConditionDescription << "Gradient tolerance reached. " + << "Projected gradient tolerance is " + << m_ProjectedGradientTolerance; + break; + case vnl_nonlinear_minimizer::FAILED_TOO_MANY_ITERATIONS: + m_StopConditionDescription << "Too many iterations. Iterations = " + << m_MaximumNumberOfEvaluations; + break; + case vnl_nonlinear_minimizer::FAILED_FTOL_TOO_SMALL: + m_StopConditionDescription << "Function tolerance too small"; + break; + case vnl_nonlinear_minimizer::FAILED_XTOL_TOO_SMALL: + m_StopConditionDescription << "Solution tolerance too small"; + break; + case vnl_nonlinear_minimizer::FAILED_GTOL_TOO_SMALL: + m_StopConditionDescription << "Gradient tolerance too small"; + break; + case vnl_nonlinear_minimizer::FAILED_USER_REQUEST: + break; + } + return m_StopConditionDescription.str(); + } + else + { + return std::string(""); + } +} } // end namespace itk diff --git a/Utilities/ITK/Code/Numerics/itkLBFGSBOptimizer.h b/Utilities/ITK/Code/Numerics/itkLBFGSBOptimizer.h index 2830f0ad5baa1f7e293c6e68dea7936fcbcce467..e6dc263f0b6bf6107b6f5ebf24c6909ff42e4347 100644 --- a/Utilities/ITK/Code/Numerics/itkLBFGSBOptimizer.h +++ b/Utilities/ITK/Code/Numerics/itkLBFGSBOptimizer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLBFGSBOptimizer.h,v $ Language: C++ - Date: $Date: 2007-11-13 14:56:49 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-06-24 12:02:52 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -159,6 +159,9 @@ public: * function. */ itkGetConstReferenceMacro( InfinityNormOfProjectedGradient, double ); + /** Get the reason for termination */ + const std::string GetStopConditionDescription() const; + protected: LBFGSBOptimizer(); virtual ~LBFGSBOptimizer(); @@ -176,7 +179,7 @@ private: bool m_OptimizerInitialized; InternalOptimizerType * m_VnlOptimizer; - + mutable OStringStream m_StopConditionDescription; BoundValueType m_LowerBound; BoundValueType m_UpperBound; BoundSelectionType m_BoundSelection; diff --git a/Utilities/ITK/Code/Numerics/itkLBFGSOptimizer.cxx b/Utilities/ITK/Code/Numerics/itkLBFGSOptimizer.cxx index dc7191f576bb2cc293a31d2a3ac8620b262a7889..60a7ab039dec06847c6ed91c4dcbdc67eb1db221 100644 --- a/Utilities/ITK/Code/Numerics/itkLBFGSOptimizer.cxx +++ b/Utilities/ITK/Code/Numerics/itkLBFGSOptimizer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLBFGSOptimizer.cxx,v $ Language: C++ - Date: $Date: 2007-03-22 21:39:37 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-06-24 12:02:52 $ + Version: $Revision: 1.22 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -56,17 +56,22 @@ LBFGSOptimizer { Superclass::PrintSelf( os, indent ); os << indent << "Trace: "; - if ( m_Trace ) { os << "On"; } else { os << "Off"; } + if ( m_Trace ) + { + os << "On"; + } + else + { os << "Off"; + } os << std::endl; - os << indent << "MaximumNumberOfFunctionEvaluations: "; - os << m_MaximumNumberOfFunctionEvaluations << std::endl; - os << indent << "GradientConvergenceTolerance: "; - os << m_GradientConvergenceTolerance << std::endl; - os << indent << "LineSearchAccuracy: "; - os << m_LineSearchAccuracy << std::endl; - os << indent << "DefaultStepLength: "; - os << m_DefaultStepLength << std::endl; - + os << indent << "MaximumNumberOfFunctionEvaluations: " + << m_MaximumNumberOfFunctionEvaluations << std::endl; + os << indent << "GradientConvergenceTolerance: " + << m_GradientConvergenceTolerance << std::endl; + os << indent << "LineSearchAccuracy: " + << m_LineSearchAccuracy << std::endl; + os << indent << "DefaultStepLength: " + << m_DefaultStepLength << std::endl; } /** @@ -289,6 +294,58 @@ LBFGSOptimizer return m_VnlOptimizer; } +const std::string +LBFGSOptimizer:: +GetStopConditionDescription() const +{ + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": "; + if (m_VnlOptimizer) + { + switch (m_VnlOptimizer->get_failure_code()) + { + case vnl_nonlinear_minimizer::ERROR_FAILURE: + m_StopConditionDescription << "Failure"; + break; + case vnl_nonlinear_minimizer::ERROR_DODGY_INPUT: + m_StopConditionDescription << "Dodgy input"; + break; + case vnl_nonlinear_minimizer::CONVERGED_FTOL: + m_StopConditionDescription << "Function tolerance reached"; + break; + case vnl_nonlinear_minimizer::CONVERGED_XTOL: + m_StopConditionDescription << "Solution tolerance reached"; + break; + case vnl_nonlinear_minimizer::CONVERGED_XFTOL: + m_StopConditionDescription << "Solution and Function tolerance both reached"; + break; + case vnl_nonlinear_minimizer::CONVERGED_GTOL: + m_StopConditionDescription << "Gradient tolerance reached"; + break; + case vnl_nonlinear_minimizer::FAILED_TOO_MANY_ITERATIONS: + m_StopConditionDescription << "Too many function evaluations. Function evaluations = " + << m_MaximumNumberOfFunctionEvaluations; + break; + case vnl_nonlinear_minimizer::FAILED_FTOL_TOO_SMALL: + m_StopConditionDescription << "Function tolerance too small"; + break; + case vnl_nonlinear_minimizer::FAILED_XTOL_TOO_SMALL: + m_StopConditionDescription << "Solution tolerance too small"; + break; + case vnl_nonlinear_minimizer::FAILED_GTOL_TOO_SMALL: + m_StopConditionDescription << "Gradient tolerance too small"; + break; + case vnl_nonlinear_minimizer::FAILED_USER_REQUEST: + m_StopConditionDescription << "User requested"; + break; + } + return m_StopConditionDescription.str(); + } + else + { + return std::string(""); + } +} } // end namespace itk #endif diff --git a/Utilities/ITK/Code/Numerics/itkLBFGSOptimizer.h b/Utilities/ITK/Code/Numerics/itkLBFGSOptimizer.h index b7c6dba39cfbefdb62c09bea1bb88ec5555f951f..0c1860301cf547b4ca0587a662045d61af3384ec 100644 --- a/Utilities/ITK/Code/Numerics/itkLBFGSOptimizer.h +++ b/Utilities/ITK/Code/Numerics/itkLBFGSOptimizer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLBFGSOptimizer.h,v $ Language: C++ - Date: $Date: 2007-03-29 19:37:01 $ - Version: $Revision: 1.20 $ + Date: $Date: 2009-06-24 12:02:52 $ + Version: $Revision: 1.21 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -97,6 +97,9 @@ public: /** Return Current Value */ MeasureType GetValue(); + /** Get the reason for termination */ + const std::string GetStopConditionDescription() const; + protected: LBFGSOptimizer(); virtual ~LBFGSOptimizer(); @@ -110,6 +113,7 @@ private: bool m_OptimizerInitialized; InternalOptimizerType * m_VnlOptimizer; + mutable OStringStream m_StopConditionDescription; bool m_Trace; unsigned int m_MaximumNumberOfFunctionEvaluations; diff --git a/Utilities/ITK/Code/Numerics/itkLevenbergMarquardtOptimizer.cxx b/Utilities/ITK/Code/Numerics/itkLevenbergMarquardtOptimizer.cxx index e6dd6203bbac815df358ae9b1004a1b1af3ca73f..5476b1c9413d3e2b8e855753726ee756904f62dc 100644 --- a/Utilities/ITK/Code/Numerics/itkLevenbergMarquardtOptimizer.cxx +++ b/Utilities/ITK/Code/Numerics/itkLevenbergMarquardtOptimizer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLevenbergMarquardtOptimizer.cxx,v $ Language: C++ - Date: $Date: 2007-04-16 10:50:37 $ - Version: $Revision: 1.26 $ + Date: $Date: 2009-06-24 12:02:52 $ + Version: $Revision: 1.27 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -228,11 +228,25 @@ LevenbergMarquardtOptimizer /** Get the Optimizer */ vnl_levenberg_marquardt * LevenbergMarquardtOptimizer -::GetOptimizer() +::GetOptimizer() const { return m_VnlOptimizer; } +const std::string +LevenbergMarquardtOptimizer +::GetStopConditionDescription() const +{ + OStringStream reason, outcome; + outcome.str(""); + if (GetOptimizer()) + { + GetOptimizer()->diagnose_outcome(outcome); + } + reason << this->GetNameOfClass() << ": " << (outcome.str().size() > 0) ? outcome.str().c_str() : ""; + return reason.str(); +} + } // end namespace itk #endif diff --git a/Utilities/ITK/Code/Numerics/itkLevenbergMarquardtOptimizer.h b/Utilities/ITK/Code/Numerics/itkLevenbergMarquardtOptimizer.h index 0df34f7187ca66635dc71a2d59f63178d5eaa4cd..8c42e58ad5fb05901c924c6b04a3f92548d48263 100644 --- a/Utilities/ITK/Code/Numerics/itkLevenbergMarquardtOptimizer.h +++ b/Utilities/ITK/Code/Numerics/itkLevenbergMarquardtOptimizer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLevenbergMarquardtOptimizer.h,v $ Language: C++ - Date: $Date: 2007-04-16 10:50:37 $ - Version: $Revision: 1.23 $ + Date: $Date: 2009-06-24 12:02:52 $ + Version: $Revision: 1.24 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -51,7 +51,7 @@ public: typedef vnl_levenberg_marquardt InternalOptimizerType; /** Method for getting access to the internal optimizer. */ - vnl_levenberg_marquardt * GetOptimizer(void); + vnl_levenberg_marquardt * GetOptimizer(void) const; /** Start optimization with an initial value. */ void StartOptimization( void ); @@ -67,6 +67,8 @@ public: /** Get the current value */ MeasureType GetValue() const; + const std::string GetStopConditionDescription() const; + protected: LevenbergMarquardtOptimizer(); virtual ~LevenbergMarquardtOptimizer(); diff --git a/Utilities/ITK/Code/Numerics/itkOnePlusOneEvolutionaryOptimizer.cxx b/Utilities/ITK/Code/Numerics/itkOnePlusOneEvolutionaryOptimizer.cxx index 5b9c3e5141520d27b22e8b44822835a02979ef96..275400f9d764bb79f0d2f0ee4fee51453ea3ecb9 100644 --- a/Utilities/ITK/Code/Numerics/itkOnePlusOneEvolutionaryOptimizer.cxx +++ b/Utilities/ITK/Code/Numerics/itkOnePlusOneEvolutionaryOptimizer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOnePlusOneEvolutionaryOptimizer.cxx,v $ Language: C++ - Date: $Date: 2008-08-06 16:14:46 $ - Version: $Revision: 1.37 $ + Date: $Date: 2009-06-24 12:02:52 $ + Version: $Revision: 1.38 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -39,6 +39,7 @@ OnePlusOneEvolutionaryOptimizer m_InitialRadius = 1.01; m_MaximumIteration = 100; m_Stop = false; + m_StopConditionDescription.str(""); m_CurrentCost = 0; m_CurrentIteration = 0; m_FrobeniusNorm = 0.0; @@ -156,6 +157,9 @@ OnePlusOneEvolutionaryOptimizer { if ( m_Stop ) { + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": "; + m_StopConditionDescription << "StopOptimization() called"; break; } @@ -256,6 +260,11 @@ OnePlusOneEvolutionaryOptimizer if (m_FrobeniusNorm <= m_Epsilon) { itkDebugMacro(<< "converges at iteration = " << iter); + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": "; + m_StopConditionDescription << "Fnorm (" << m_FrobeniusNorm + << ") is less than Epsilon (" << m_Epsilon + << " at iteration # " << iter; break; } @@ -284,10 +293,24 @@ OnePlusOneEvolutionaryOptimizer this->InvokeEvent( IterationEvent() ); itkDebugMacro(<< "Current position: " << this->GetCurrentPosition()); } + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": "; + m_StopConditionDescription << "Maximum number of iterations (" + << m_MaximumIteration + << ") exceeded. "; this->InvokeEvent( EndEvent() ); } +/** + * + */ +const std::string +OnePlusOneEvolutionaryOptimizer +::GetStopConditionDescription() const +{ + return m_StopConditionDescription.str(); +} /** * @@ -296,7 +319,6 @@ void OnePlusOneEvolutionaryOptimizer ::PrintSelf(std::ostream& os, Indent indent) const { - Superclass::PrintSelf(os,indent); if (m_RandomGenerator) diff --git a/Utilities/ITK/Code/Numerics/itkOnePlusOneEvolutionaryOptimizer.h b/Utilities/ITK/Code/Numerics/itkOnePlusOneEvolutionaryOptimizer.h index fef2d9bd9aff971b5fb59995dc1c7e554f173439..25037ca137cebd9153fe323ffe093ce39b3cf229 100644 --- a/Utilities/ITK/Code/Numerics/itkOnePlusOneEvolutionaryOptimizer.h +++ b/Utilities/ITK/Code/Numerics/itkOnePlusOneEvolutionaryOptimizer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOnePlusOneEvolutionaryOptimizer.h,v $ Language: C++ - Date: $Date: 2008-08-05 11:15:49 $ - Version: $Revision: 1.24 $ + Date: $Date: 2009-06-24 12:02:53 $ + Version: $Revision: 1.25 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,6 +19,7 @@ #include <itkSingleValuedNonLinearOptimizer.h> #include <itkRandomVariateGeneratorBase.h> +#include <string> namespace itk { @@ -151,6 +152,8 @@ public: itkGetMacro(MetricWorstPossibleValue, double); itkSetMacro(MetricWorstPossibleValue, double); + const std::string GetStopConditionDescription() const; + protected: OnePlusOneEvolutionaryOptimizer(); OnePlusOneEvolutionaryOptimizer(const OnePlusOneEvolutionaryOptimizer&); @@ -199,6 +202,9 @@ private: * optimization will stop at the next iteration. */ bool m_Stop; + /** Stop description */ + OStringStream m_StopConditionDescription; + /** Cache variable for reporting the Frobenius Norm */ double m_FrobeniusNorm; diff --git a/Utilities/ITK/Code/Numerics/itkOptimizer.cxx b/Utilities/ITK/Code/Numerics/itkOptimizer.cxx index 2a1a0e42340a51d1d070f85ac19546a1074f9ac5..2593a23fdc0b09df1551aa34d186f160d436a9cd 100644 --- a/Utilities/ITK/Code/Numerics/itkOptimizer.cxx +++ b/Utilities/ITK/Code/Numerics/itkOptimizer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptimizer.cxx,v $ Language: C++ - Date: $Date: 2007-03-22 14:29:14 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-06-24 12:02:54 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -68,6 +68,15 @@ Optimizer this->Modified(); } +const std::string +Optimizer +::GetStopConditionDescription() const +{ + OStringStream description; + description << this->GetNameOfClass() << ": " + << "Optimizer did not provide a stop condition description"; + return description.str(); +} /** * Print Self method @@ -93,6 +102,9 @@ Optimizer os << indent << "Scales: not defined (default 1)" << std::endl; } + + os << indent << "StopConditionDescription: " + << this->GetStopConditionDescription() << std::endl; } } // end namespace itk diff --git a/Utilities/ITK/Code/Numerics/itkOptimizer.h b/Utilities/ITK/Code/Numerics/itkOptimizer.h index 270efa48daee986243ed9241e352b9e63aacf4c1..a743252dc501ba4dbf44690804ff3b2e0547353f 100644 --- a/Utilities/ITK/Code/Numerics/itkOptimizer.h +++ b/Utilities/ITK/Code/Numerics/itkOptimizer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptimizer.h,v $ Language: C++ - Date: $Date: 2008-04-23 12:49:10 $ - Version: $Revision: 1.38 $ + Date: $Date: 2009-06-24 12:02:54 $ + Version: $Revision: 1.39 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -79,6 +79,9 @@ public: /** Start optimization. */ virtual void StartOptimization() {}; + /** Get the reason for termination */ + virtual const std::string GetStopConditionDescription() const; + protected: Optimizer(); virtual ~Optimizer() {}; @@ -100,7 +103,6 @@ private: ParametersType m_InitialPosition; ScalesType m_Scales; - }; } // end namespace itk diff --git a/Utilities/ITK/Code/Numerics/itkPowellOptimizer.cxx b/Utilities/ITK/Code/Numerics/itkPowellOptimizer.cxx index 342042429e87a9c76950a51d05a187836b98ef3b..71056bcd279476e27f3c79bcb2bb7f1676737f7d 100755 --- a/Utilities/ITK/Code/Numerics/itkPowellOptimizer.cxx +++ b/Utilities/ITK/Code/Numerics/itkPowellOptimizer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPowellOptimizer.cxx,v $ Language: C++ - Date: $Date: 2009-04-05 10:56:50 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-06-24 12:02:54 $ + Version: $Revision: 1.22 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -46,6 +46,8 @@ PowellOptimizer m_MaximumLineIteration = 100; m_SpaceDimension = 0; + + m_StopConditionDescription << this->GetNameOfClass() << ": "; } PowellOptimizer @@ -320,15 +322,15 @@ PowellOptimizer if( vcl_fabs(p) < vcl_fabs(new_step*q) && p > q*(a-x+2*tolerance1) && p < q*(b-x-2*tolerance1) ) - { - new_step = p/q; /* it is accepted */ - } + { + new_step = p/q; /* it is accepted */ + } /* If p/q is too large then the gold section procedure can reduce [a,b] range to more extent */ } - /* Adjust the step to be not less than tolerance*/ + /* Adjust the step to be not less than tolerance*/ if( vcl_fabs(new_step) < tolerance1 ) { if ( new_step > 0.0 ) @@ -350,7 +352,7 @@ PowellOptimizer functionValueOft = this->GetLineValue(t, tempCoord); if( functionValueOft <= functionValueOfX ) - { + { if( t < x ) /* Reduce the range so that */ { b = x; /* t would fall within it */ @@ -360,25 +362,25 @@ PowellOptimizer a = x; } - /* assing the best approximation to x */ - v = w; - w = x; - x = t; + /* assing the best approximation to x */ + v = w; + w = x; + x = t; - functionValueOfV = functionValueOfW; - functionValueOfW = functionValueOfX; - functionValueOfX = functionValueOft; - } - else /* x remains the better approx */ - { - if( t < x ) /* Reduce the range enclosing x */ - { - a = t; + functionValueOfV = functionValueOfW; + functionValueOfW = functionValueOfX; + functionValueOfX = functionValueOft; } - else + else /* x remains the better approx */ { - b = t; - } + if( t < x ) /* Reduce the range enclosing x */ + { + a = t; + } + else + { + b = t; + } if( functionValueOft <= functionValueOfW || w==x ) { @@ -392,8 +394,8 @@ PowellOptimizer v = t; functionValueOfV=functionValueOft; } - } - } + } + } *extX = x; *extVal = functionValueOfX; @@ -414,6 +416,9 @@ PowellOptimizer return; } + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": "; + this->InvokeEvent( StartEvent() ); m_Stop = false; @@ -481,6 +486,12 @@ PowellOptimizer if (2.0*vcl_fabs(fp-fx) <= m_ValueTolerance*(vcl_fabs(fp)+vcl_fabs(fx))) { + m_StopConditionDescription << "Cost function values at the current parameter (" + << fx + << ") and at the local extrema (" + << fp + << ") are within Value Tolerance (" + << m_ValueTolerance << ")"; this->InvokeEvent( EndEvent() ); return; } @@ -497,8 +508,8 @@ PowellOptimizer if (fptt < fp) { double t = 2.0 * (fp - 2.0*fx + fptt) - * vnl_math_sqr(fp-fx-del) - - del * vnl_math_sqr(fp-fptt); + * vnl_math_sqr(fp-fx-del) + - del * vnl_math_sqr(fp-fptt); if (t < 0.0) { this->SetLine(p, xit); @@ -522,8 +533,20 @@ PowellOptimizer } + m_StopConditionDescription << "Maximum number of iterations exceeded. " + << "Number of iterations is " + << m_MaximumIteration; this->InvokeEvent( EndEvent() ); +} +/** + * + */ +const std::string +PowellOptimizer +::GetStopConditionDescription() const +{ + return m_StopConditionDescription.str(); } /** diff --git a/Utilities/ITK/Code/Numerics/itkPowellOptimizer.h b/Utilities/ITK/Code/Numerics/itkPowellOptimizer.h index 7764a6dff373f9b3f929ac91edadca51f904a9ba..2c25c9dffa3a377897bd30e751bb15bfae722bb6 100755 --- a/Utilities/ITK/Code/Numerics/itkPowellOptimizer.h +++ b/Utilities/ITK/Code/Numerics/itkPowellOptimizer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPowellOptimizer.h,v $ Language: C++ - Date: $Date: 2008-04-29 23:33:33 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-06-24 12:02:54 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -133,6 +133,7 @@ public: itkGetMacro(MetricWorstPossibleValue, double); itkSetMacro(MetricWorstPossibleValue, double); + const std::string GetStopConditionDescription() const; protected: PowellOptimizer(); @@ -246,6 +247,7 @@ private: * optimization will stop at the next iteration. */ bool m_Stop; + OStringStream m_StopConditionDescription; }; // end of class } // end of namespace itk diff --git a/Utilities/ITK/Code/Numerics/itkRegularStepGradientDescentBaseOptimizer.cxx b/Utilities/ITK/Code/Numerics/itkRegularStepGradientDescentBaseOptimizer.cxx index da9585d334f841b2bb777e3bf1e082802be9c2db..94783c120d3de9fea2974c9b8525f9f7a5775284 100644 --- a/Utilities/ITK/Code/Numerics/itkRegularStepGradientDescentBaseOptimizer.cxx +++ b/Utilities/ITK/Code/Numerics/itkRegularStepGradientDescentBaseOptimizer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRegularStepGradientDescentBaseOptimizer.cxx,v $ Language: C++ - Date: $Date: 2007-09-10 16:22:23 $ - Version: $Revision: 1.24 $ + Date: $Date: 2009-06-24 12:02:54 $ + Version: $Revision: 1.25 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -47,7 +47,7 @@ RegularStepGradientDescentBaseOptimizer m_Gradient.Fill( 0.0f ); m_PreviousGradient.Fill( 0.0f ); m_RelaxationFactor = 0.5; - + m_StopConditionDescription.str(""); } /** @@ -64,6 +64,8 @@ RegularStepGradientDescentBaseOptimizer m_CurrentIteration = 0; m_StopCondition = Unknown; + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": "; // validity check for the value of GradientMagnitudeTolerance if( m_GradientMagnitudeTolerance < 0.0 ) @@ -104,6 +106,9 @@ RegularStepGradientDescentBaseOptimizer if( m_CurrentIteration >= m_NumberOfIterations ) { m_StopCondition = MaximumNumberOfIterations; + m_StopConditionDescription << "Maximum number of iterations (" + << m_NumberOfIterations + << ") exceeded."; this->StopOptimization(); break; } @@ -118,6 +123,10 @@ RegularStepGradientDescentBaseOptimizer catch( ExceptionObject & excp ) { m_StopCondition = CostFunctionError; + m_StopConditionDescription << "Cost function error after " + << m_CurrentIteration + << " iterations. " + << excp.GetDescription(); this->StopOptimization(); throw excp; } @@ -207,6 +216,13 @@ RegularStepGradientDescentBaseOptimizer if( gradientMagnitude < m_GradientMagnitudeTolerance ) { m_StopCondition = GradientMagnitudeTolerance; + m_StopConditionDescription << "Gradient magnitude tolerance met after " + << m_CurrentIteration + << " iterations. Gradient magnitude (" + << gradientMagnitude + << ") is less than gradient magnitude tolerance (" + << m_GradientMagnitudeTolerance + << ")."; this->StopOptimization(); return; } @@ -229,6 +245,13 @@ RegularStepGradientDescentBaseOptimizer if( m_CurrentStepLength < m_MinimumStepLength ) { m_StopCondition = StepTooSmall; + m_StopConditionDescription << "Step too small after " + << m_CurrentIteration + << " iterations. Current step (" + << m_CurrentStepLength + << ") is less than minimum step (" + << m_MinimumStepLength + << ")."; this->StopOptimization(); return; } @@ -254,6 +277,14 @@ RegularStepGradientDescentBaseOptimizer } +const std::string +RegularStepGradientDescentBaseOptimizer +::GetStopConditionDescription() const +{ + return m_StopConditionDescription.str(); +} + + void RegularStepGradientDescentBaseOptimizer ::PrintSelf( std::ostream& os, Indent indent ) const diff --git a/Utilities/ITK/Code/Numerics/itkRegularStepGradientDescentBaseOptimizer.h b/Utilities/ITK/Code/Numerics/itkRegularStepGradientDescentBaseOptimizer.h index 3204de8ba3678d0ca25709a464489ddb5a48735c..c11c8b18751bc48bcedb0519b068da2b1f08f02e 100644 --- a/Utilities/ITK/Code/Numerics/itkRegularStepGradientDescentBaseOptimizer.h +++ b/Utilities/ITK/Code/Numerics/itkRegularStepGradientDescentBaseOptimizer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRegularStepGradientDescentBaseOptimizer.h,v $ Language: C++ - Date: $Date: 2007-08-14 17:08:31 $ - Version: $Revision: 1.22 $ + Date: $Date: 2009-06-24 12:02:54 $ + Version: $Revision: 1.23 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -96,6 +96,8 @@ public: itkGetConstReferenceMacro( Value, MeasureType ); itkGetConstReferenceMacro( Gradient, DerivativeType ); + /** Get the reason for termination */ + virtual const std::string GetStopConditionDescription() const; protected: RegularStepGradientDescentBaseOptimizer(); @@ -141,8 +143,7 @@ protected: StopConditionType m_StopCondition; unsigned long m_NumberOfIterations; unsigned long m_CurrentIteration; - - + OStringStream m_StopConditionDescription; }; } // end namespace itk diff --git a/Utilities/ITK/Code/Numerics/itkSPSAOptimizer.cxx b/Utilities/ITK/Code/Numerics/itkSPSAOptimizer.cxx index 808c58d90f60ee76e11746301ad0a16676e415d3..a0dc36041d6aa2f3b834049cffa11699c1c825f1 100644 --- a/Utilities/ITK/Code/Numerics/itkSPSAOptimizer.cxx +++ b/Utilities/ITK/Code/Numerics/itkSPSAOptimizer.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSPSAOptimizer.cxx,v $ Language: C++ - Date: $Date: 2009-05-26 23:45:04 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-06-24 12:02:54 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -349,11 +349,7 @@ void SPSAOptimizer for ( unsigned int j = 0; j < spaceDimension; j++ ) { /** Generate randomly -1 or 1. */ -#ifdef ITK_USE_PORTABLE_ROUND m_Delta[ j ] = 2 * Math::Round( this->m_Generator->GetUniformVariate (0.0f, 1.0f) ) - 1; -#else - m_Delta[ j ] = 2 * vnl_math_rnd ( this->m_Generator->GetUniformVariate (0.0f, 1.0f) ) - 1; -#endif /** * Take scales into account. The perturbation of a parameter that has a @@ -518,6 +514,34 @@ GuessParameters( } //end GuessParameters +const std::string +SPSAOptimizer:: +GetStopConditionDescription() const +{ + ::itk::OStringStream reason; + reason << this->GetNameOfClass() << ": "; + switch( m_StopCondition ) + { + case Unknown: + reason << "Unknown stop condition"; + break; + case MaximumNumberOfIterations: + reason << "Maximum number of iterations exceeded. Number of iterations is " + << m_MaximumNumberOfIterations; + break; + case BelowTolerance: + reason << "Below tolerance. " << "Tolerance is " << m_Tolerance; + break; + case MetricError: + reason << "Metric error"; + break; + default: + reason << " No reason given for termination "; + break; + } + return reason.str(); +} + } // end namespace itk diff --git a/Utilities/ITK/Code/Numerics/itkSPSAOptimizer.h b/Utilities/ITK/Code/Numerics/itkSPSAOptimizer.h index ba9eef7f3ea2fad44dd4e20118085b633d0e1f2a..9f802b2f5fc9e8bc634e1cc9fbc251d3164016f2 100644 --- a/Utilities/ITK/Code/Numerics/itkSPSAOptimizer.h +++ b/Utilities/ITK/Code/Numerics/itkSPSAOptimizer.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSPSAOptimizer.h,v $ Language: C++ - Date: $Date: 2009-05-12 17:19:52 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-06-24 12:02:54 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -193,6 +193,9 @@ public: itkSetMacro(Tolerance, double); itkGetConstMacro(Tolerance, double); + /** Get the reason for termination */ + const std::string GetStopConditionDescription() const; + protected: SPSAOptimizer(); diff --git a/Utilities/ITK/Code/Review/Statistics/CMakeLists.txt b/Utilities/ITK/Code/Review/Statistics/CMakeLists.txt index be32d4cdc6498dfa717ebda943cd5a1234485205..cb6a30ea74b1bd91628ab4347a582195a795ad70 100644 --- a/Utilities/ITK/Code/Review/Statistics/CMakeLists.txt +++ b/Utilities/ITK/Code/Review/Statistics/CMakeLists.txt @@ -32,7 +32,7 @@ IF(NOT ITK_INSTALL_NO_DEVELOPMENT) FILE(GLOB __files1 "${CMAKE_CURRENT_SOURCE_DIR}/*.h") FILE(GLOB __files2 "${CMAKE_CURRENT_SOURCE_DIR}/*.txx") INSTALL(FILES ${__files1} ${__files2} - DESTINATION ${ITK_INSTALL_INCLUDE_DIR_CM24}/Numerics/Statistics + DESTINATION ${ITK_INSTALL_INCLUDE_DIR_CM24}/Review/Statistics COMPONENT Development) ENDIF(NOT ITK_INSTALL_NO_DEVELOPMENT) diff --git a/Utilities/ITK/Code/Review/Statistics/itkChiSquareDistribution.cxx b/Utilities/ITK/Code/Review/Statistics/itkChiSquareDistribution.cxx index 641ac6cf7d7c4ad800b55cf6b3c3535605fc8fed..d10c1a3c2c57a57150ccfa2c5805034990e113e3 100644 --- a/Utilities/ITK/Code/Review/Statistics/itkChiSquareDistribution.cxx +++ b/Utilities/ITK/Code/Review/Statistics/itkChiSquareDistribution.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkChiSquareDistribution.cxx,v $ Language: C++ - Date: $Date: 2009-05-10 18:27:08 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-08-07 15:40:32 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -85,8 +85,8 @@ ChiSquareDistribution if (x >= 0.0) { - pdf = exp(-0.5*x) * pow(x, dofon2 - 1.0) - / (pow(2.0, dofon2) * dgamma_(&dofon2)); + pdf = vcl_exp(-0.5*x) * vcl_pow(x, dofon2 - 1.0) + / (vcl_pow(2.0, dofon2) * dgamma_(&dofon2)); } return pdf; @@ -162,7 +162,7 @@ ChiSquareDistribution nx = GaussianDistribution::InverseCDF(p); double f = 2.0 / (9.0*dof); - x = dof*pow(1.0 - f + nx*sqrt(f), 3.0); + x = dof*vcl_pow(1.0 - f + nx*vcl_sqrt(f), 3.0); // The approximation above is only accurate for large degrees of diff --git a/Utilities/ITK/Code/Review/Statistics/itkGaussianDistribution.cxx b/Utilities/ITK/Code/Review/Statistics/itkGaussianDistribution.cxx index b4e27bb4dfbe19c36061c07984b50dd5bb2008b6..99f31ef8e23cd62411d2adaf5c3d03bdedd04ae4 100644 --- a/Utilities/ITK/Code/Review/Statistics/itkGaussianDistribution.cxx +++ b/Utilities/ITK/Code/Review/Statistics/itkGaussianDistribution.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianDistribution.cxx,v $ Language: C++ - Date: $Date: 2009-05-10 18:27:08 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-08-07 15:40:34 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -165,20 +165,16 @@ double GaussianDistribution ::PDF(double x) { - static const double oneonsqrttwopi = 1.0 / sqrt( 2.0 * vnl_math::pi ); - - return oneonsqrttwopi * vcl_exp(-0.5*x*x); + return vnl_math::one_over_sqrt2pi * vcl_exp(-0.5*x*x); } double GaussianDistribution ::PDF(double x, double mean, double variance) { - static const double oneonsqrttwopi = 1.0 / sqrt( 2.0 * vnl_math::pi ); - double xminusmean = x - mean; - return (oneonsqrttwopi / sqrt(variance)) + return (vnl_math::one_over_sqrt2pi / vcl_sqrt(variance)) * vcl_exp(-0.5*xminusmean*xminusmean / variance); } @@ -213,7 +209,7 @@ GaussianDistribution ::CDF(double x, double mean, double variance) { // convert to zero mean unit variance - double u = (x - mean) / sqrt(variance); + double u = (x - mean) / vcl_sqrt(variance); return 0.5 * (vnl_erf(vnl_math::sqrt1_2 * u) + 1.0); } @@ -262,7 +258,7 @@ GaussianDistribution /** Step 1: use 26.2.23 from Abramowitz and Stegun */ - dt = sqrt( -2.0 * log(dp) ); + dt = vcl_sqrt( -2.0 * vcl_log(dp) ); dx = dt - ((.010328e+0*dt + .802853e+0)*dt + 2.515517e+0) /(((.001308e+0*dt + .189269e+0)*dt + 1.432788e+0)*dt + 1.e+0); @@ -271,7 +267,7 @@ GaussianDistribution for( newt=0; newt < 3; newt++ ) { - dq = 0.5e+0 * vnl_erfc( dx / 1.414213562373095e+0 ) - dp; + dq = 0.5e+0 * vnl_erfc( dx *vnl_math::sqrt1_2 ) - dp; ddq = vcl_exp( -0.5e+0 * dx * dx ) / 2.506628274631000e+0; dx = dx + dq / ddq; } @@ -306,7 +302,7 @@ GaussianDistribution { // apply the mean and variance to provide the value for the // prescribed Gaussian - x = x*sqrt(variance) + mean; + x = x*vcl_sqrt(variance) + mean; return x; } } diff --git a/Utilities/ITK/Code/Review/Statistics/itkGaussianMembershipFunction.txx b/Utilities/ITK/Code/Review/Statistics/itkGaussianMembershipFunction.txx index bf1fb0b56892447e39bc05e1c82bf21eb91b5077..4a7a931ecc3af82713daa52708feff609fff08f5 100644 --- a/Utilities/ITK/Code/Review/Statistics/itkGaussianMembershipFunction.txx +++ b/Utilities/ITK/Code/Review/Statistics/itkGaussianMembershipFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianMembershipFunction.txx,v $ Language: C++ - Date: $Date: 2009-05-02 05:43:55 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-08-08 15:48:18 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -106,8 +106,8 @@ GaussianMembershipFunction< TMeasurementVector > double det = vnl_determinant(m_Covariance.GetVnlMatrix()); // calculate coefficient C of multivariate gaussian - m_PreFactor = 1.0 / (sqrt(det) * - vcl_pow(sqrt(2.0 * vnl_math::pi), double(this->GetMeasurementVectorSize()))); + m_PreFactor = 1.0 / (vcl_sqrt(det) * + vcl_pow(vcl_sqrt(2.0 * vnl_math::pi), double(this->GetMeasurementVectorSize()))); } } diff --git a/Utilities/ITK/Code/Review/Statistics/itkImageClassifierFilter.h b/Utilities/ITK/Code/Review/Statistics/itkImageClassifierFilter.h index df9418f60549a984668da9209225574822019599..1d7dc581a089355d11687d0f795472ef1fe926d3 100644 --- a/Utilities/ITK/Code/Review/Statistics/itkImageClassifierFilter.h +++ b/Utilities/ITK/Code/Review/Statistics/itkImageClassifierFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageClassifierFilter.h,v $ Language: C++ - Date: $Date: 2009-05-02 05:43:55 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-06-15 12:40:37 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -53,7 +53,7 @@ public: typedef SmartPointer<const Self> ConstPointer; /** Standard macros */ - itkTypeMacro(ImageClassifierFilter, ProcessObject); + itkTypeMacro(ImageClassifierFilter, ImageToImagefilter); itkNewMacro(Self); /** Image pixel value typedef. */ diff --git a/Utilities/ITK/Code/Review/Statistics/itkImageToHistogramFilter.h b/Utilities/ITK/Code/Review/Statistics/itkImageToHistogramFilter.h index add1b6b98fcfe9aec5eeaf3efa7a030d38b7a81e..0e6fe29ecc63f567408ca2292d1b374e91a04a66 100644 --- a/Utilities/ITK/Code/Review/Statistics/itkImageToHistogramFilter.h +++ b/Utilities/ITK/Code/Review/Statistics/itkImageToHistogramFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkImageToHistogramFilter.h,v $ Language: C++ - Date: $Date: 2009-05-02 05:43:55 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-08-11 12:41:16 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -46,12 +46,12 @@ class ITK_EXPORT ImageToHistogramFilter : public ProcessObject public: /** Standard typedefs */ typedef ImageToHistogramFilter Self; - typedef Object Superclass; + typedef ProcessObject Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ - itkTypeMacro(ImageToHistogramFilter, Object); + itkTypeMacro(ImageToHistogramFilter, ProcessObject); /** standard New() method support */ itkNewMacro(Self); @@ -60,7 +60,7 @@ public: typedef ImageToListSampleAdaptor< ImageType > AdaptorType; typedef typename AdaptorType::Pointer AdaptorPointer; typedef typename ImageType::PixelType PixelType; - typedef typename PixelType::ValueType ValueType; + typedef typename NumericTraits< PixelType >::ValueType ValueType; typedef typename NumericTraits< ValueType >::RealType ValueRealType; typedef DenseFrequencyContainer2 FrequencyContainerType; diff --git a/Utilities/ITK/Code/Review/Statistics/itkKdTreeBasedKmeansEstimator.h b/Utilities/ITK/Code/Review/Statistics/itkKdTreeBasedKmeansEstimator.h index 86a311d71bb86a587f144949d74d1d7d300dc00d..d0c7126efab4ac9bc733f859c966cb0ecf5ccdb1 100644 --- a/Utilities/ITK/Code/Review/Statistics/itkKdTreeBasedKmeansEstimator.h +++ b/Utilities/ITK/Code/Review/Statistics/itkKdTreeBasedKmeansEstimator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkKdTreeBasedKmeansEstimator.h,v $ Language: C++ - Date: $Date: 2009-05-02 05:43:56 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-06-15 12:40:37 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -81,7 +81,7 @@ public: itkNewMacro(Self); /** Run-time type information (and related methods). */ - itkTypeMacro(KdTreeBasedKmeansEstimator, Obeject); + itkTypeMacro(KdTreeBasedKmeansEstimator, Object); /** Types for the KdTree data structure */ typedef typename TKdTree::KdTreeNodeType KdTreeNodeType; diff --git a/Utilities/ITK/Code/Review/Statistics/itkManhattanDistanceMetric.txx b/Utilities/ITK/Code/Review/Statistics/itkManhattanDistanceMetric.txx index 3a29df84a3285d223ff71bbaa082db67d892ebe0..e8642e60688a1cb3ca4734d660d55f3a5b30f4e8 100644 --- a/Utilities/ITK/Code/Review/Statistics/itkManhattanDistanceMetric.txx +++ b/Utilities/ITK/Code/Review/Statistics/itkManhattanDistanceMetric.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkManhattanDistanceMetric.txx,v $ Language: C++ - Date: $Date: 2009-05-23 04:17:05 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-08-08 15:48:18 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -39,7 +39,7 @@ ManhattanDistanceMetric< TVector > for(unsigned int i = 0; i < measurementVectorSize; i++) { - temp = fabs( this->GetOrigin()[i] - x[i] ); + temp = vcl_abs( this->GetOrigin()[i] - x[i] ); distance += temp; } return distance; @@ -59,7 +59,7 @@ ManhattanDistanceMetric< TVector > double temp, distance = NumericTraits< double >::Zero; for(unsigned int i = 0; i < measurementVectorSize; i++) { - temp = fabs( x1[i] - x2[i] ); + temp = vcl_abs( x1[i] - x2[i] ); distance += temp; } return distance; diff --git a/Utilities/ITK/Code/Review/Statistics/itkMaximumDecisionRule2.h b/Utilities/ITK/Code/Review/Statistics/itkMaximumDecisionRule2.h index 97342bb0541423495e98d4be4dccfe54bea9cf18..c559b6b79161608de9923a18fce222791ed31dd6 100644 --- a/Utilities/ITK/Code/Review/Statistics/itkMaximumDecisionRule2.h +++ b/Utilities/ITK/Code/Review/Statistics/itkMaximumDecisionRule2.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMaximumDecisionRule2.h,v $ Language: C++ - Date: $Date: 2009-05-02 05:43:58 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-06-15 12:40:37 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -38,7 +38,7 @@ public: typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods) */ - itkTypeMacro(MaximumDecisionRule2, DecisionRuleBase); + itkTypeMacro(MaximumDecisionRule2, DecisionRule); /** Standard New() method support */ itkNewMacro(Self); diff --git a/Utilities/ITK/Code/Review/Statistics/itkMeasurementVectorTraits.h b/Utilities/ITK/Code/Review/Statistics/itkMeasurementVectorTraits.h index 2fc01b3c953d231a2c35b324eadf4d980a66adc8..57b0e92c782628ff45e59a953305b1934849f4b3 100644 --- a/Utilities/ITK/Code/Review/Statistics/itkMeasurementVectorTraits.h +++ b/Utilities/ITK/Code/Review/Statistics/itkMeasurementVectorTraits.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMeasurementVectorTraits.h,v $ Language: C++ - Date: $Date: 2009-05-23 04:17:05 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-08-08 14:39:59 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -94,8 +94,7 @@ public: precision). Using double type will also ultimately fall into the same problem. Hence in the new statistics framework, InstanceIdentifier/FrequencyTypes are set to the the largest possible integer on the machine */ - //typedef typename std::vector<int>::size_type InstanceIdentifier; - typedef unsigned long InstanceIdentifier; + typedef size_t InstanceIdentifier; /** Type defined for representing the frequency of measurement vectors */ typedef InstanceIdentifier AbsoluteFrequencyType; diff --git a/Utilities/ITK/Code/Review/Statistics/itkMinimumDecisionRule2.h b/Utilities/ITK/Code/Review/Statistics/itkMinimumDecisionRule2.h index 96953eca988fa8a2e0197253e62e55e479dd52d2..7409351c12b8606b9e633460877f023b780af7a0 100644 --- a/Utilities/ITK/Code/Review/Statistics/itkMinimumDecisionRule2.h +++ b/Utilities/ITK/Code/Review/Statistics/itkMinimumDecisionRule2.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMinimumDecisionRule2.h,v $ Language: C++ - Date: $Date: 2009-05-02 05:43:58 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-06-15 12:40:37 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -38,7 +38,7 @@ public: typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods) */ - itkTypeMacro(MinimumDecisionRule2, DecisionRuleBase); + itkTypeMacro(MinimumDecisionRule2, DecisionRule); /** Standard New() method support */ itkNewMacro(Self); diff --git a/Utilities/ITK/Code/Review/Statistics/itkPointSetToListSampleAdaptor.txx b/Utilities/ITK/Code/Review/Statistics/itkPointSetToListSampleAdaptor.txx index b35b20cc66470c64f12df7f117772efcb325d0ab..9f9ef216ff3e8ea9b3732c9789e1862c9bd91df9 100644 --- a/Utilities/ITK/Code/Review/Statistics/itkPointSetToListSampleAdaptor.txx +++ b/Utilities/ITK/Code/Review/Statistics/itkPointSetToListSampleAdaptor.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPointSetToListSampleAdaptor.txx,v $ Language: C++ -Date: $Date: 2009-05-08 16:55:05 $ -Version: $Revision: 1.2 $ +Date: $Date: 2009-05-27 19:01:35 $ +Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -88,14 +88,14 @@ PointSetToListSampleAdaptor< TPointSet > template < class TPointSet > inline const typename PointSetToListSampleAdaptor< TPointSet >::MeasurementVectorType & PointSetToListSampleAdaptor< TPointSet > -::GetMeasurementVector( InstanceIdentifier id ) const +::GetMeasurementVector( InstanceIdentifier identifier ) const { if( m_PointSet.IsNull() ) { itkExceptionMacro("Point set has not been set yet"); } - m_PointSet->GetPoint(id, &m_TempPoint); + m_PointSet->GetPoint(identifier, &m_TempPoint); return (MeasurementVectorType&) m_TempPoint; } diff --git a/Utilities/ITK/Code/Review/Statistics/itkScalarImageToHistogramGenerator.h b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToHistogramGenerator.h index 1ae2745894752a3210c163b669884ebab0706b7d..b3dc93cbddf529745c6c4c58013da1fb5e160179 100644 --- a/Utilities/ITK/Code/Review/Statistics/itkScalarImageToHistogramGenerator.h +++ b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToHistogramGenerator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarImageToHistogramGenerator.h,v $ Language: C++ - Date: $Date: 2009-05-02 05:43:58 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-08-08 14:18:12 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -18,15 +18,9 @@ #define __itkScalarImageToHistogramGenerator_h -#ifdef ITK_USE_REVIEW_STATISTICS #include "itkImageToListSampleAdaptor.h" #include "itkSampleToHistogramFilter.h" #include "itkHistogram.h" -#else -#include "itkScalarImageToListAdaptor.h" -#include "itkListSampleToHistogramGenerator.h" -#endif - #include "itkObject.h" namespace itk { @@ -53,28 +47,15 @@ public: itkNewMacro(Self); typedef TImageType ImageType; -#ifdef ITK_USE_REVIEW_STATISTICS typedef itk::Statistics::ImageToListSampleAdaptor< -#else - typedef itk::Statistics::ScalarImageToListAdaptor< -#endif ImageType > AdaptorType; typedef typename AdaptorType::Pointer AdaptorPointer; typedef typename ImageType::PixelType PixelType; typedef typename NumericTraits< PixelType >::RealType RealPixelType; -#ifdef ITK_USE_REVIEW_STATISTICS typedef itk::Statistics::Histogram< double > HistogramType; typedef itk::Statistics::SampleToHistogramFilter< AdaptorType, HistogramType > GeneratorType; -#else - typedef itk::Statistics::ListSampleToHistogramGenerator< - AdaptorType, - RealPixelType, - DenseFrequencyContainer - > GeneratorType; - typedef typename GeneratorType::HistogramType HistogramType; -#endif typedef typename GeneratorType::Pointer GeneratorPointer; diff --git a/Utilities/ITK/Code/Review/Statistics/itkScalarImageToHistogramGenerator.txx b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToHistogramGenerator.txx index 90137bcb60d2df0b982ccab414711eab77deec7d..819dfc46b58539924e0d0f237001a831555ca480 100644 --- a/Utilities/ITK/Code/Review/Statistics/itkScalarImageToHistogramGenerator.txx +++ b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToHistogramGenerator.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarImageToHistogramGenerator.txx,v $ Language: C++ - Date: $Date: 2009-05-05 19:44:33 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-08-17 18:29:01 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -30,11 +30,7 @@ ScalarImageToHistogramGenerator< TImage > { m_ImageToListAdaptor = AdaptorType::New(); m_HistogramGenerator = GeneratorType::New(); -#ifdef ITK_USE_REVIEW_STATISTICS m_HistogramGenerator->SetInput( m_ImageToListAdaptor ); -#else - m_HistogramGenerator->SetListSample( m_ImageToListAdaptor ); -#endif } template < class TImage > @@ -68,14 +64,9 @@ ScalarImageToHistogramGenerator< TImage > ::SetNumberOfBins( unsigned int numberOfBins ) { typename HistogramType::SizeType size; -#ifdef ITK_USE_REVIEW_STATISTICS size.SetSize(1); size.Fill( numberOfBins ); m_HistogramGenerator->SetHistogramSize( size ); -#else - size.Fill( numberOfBins ); - m_HistogramGenerator->SetNumberOfBins( size ); -#endif } @@ -84,10 +75,10 @@ void ScalarImageToHistogramGenerator< TImage > ::SetHistogramMin( RealPixelType minimumValue ) { - typedef typename GeneratorType::MeasurementVectorType MeasurementVectorType; + typedef typename GeneratorType::HistogramMeasurementVectorType MeasurementVectorType; MeasurementVectorType minVector; minVector[0] = minimumValue; - m_HistogramGenerator->SetHistogramMin( minVector ); + m_HistogramGenerator->SetHistogramBinMinimum( minVector ); } @@ -96,10 +87,10 @@ void ScalarImageToHistogramGenerator< TImage > ::SetHistogramMax( RealPixelType maximumValue ) { - typedef typename GeneratorType::MeasurementVectorType MeasurementVectorType; + typedef typename GeneratorType::HistogramMeasurementVectorType MeasurementVectorType; MeasurementVectorType maxVector; maxVector[0] = maximumValue; - m_HistogramGenerator->SetHistogramMax( maxVector ); + m_HistogramGenerator->SetHistogramBinMaximum( maxVector ); } template < class TImage > diff --git a/Utilities/ITK/Code/Review/Statistics/itkScalarImageToTextureFeaturesFilter.h b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToTextureFeaturesFilter.h index d872a66e8da8f17ae0d4f63264ca8531acbdd077..146fb628caebf3948c5c7c6d93224a38ee56e77f 100644 --- a/Utilities/ITK/Code/Review/Statistics/itkScalarImageToTextureFeaturesFilter.h +++ b/Utilities/ITK/Code/Review/Statistics/itkScalarImageToTextureFeaturesFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarImageToTextureFeaturesFilter.h,v $ Language: C++ - Date: $Date: 2009-05-08 16:55:05 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-06-15 12:40:37 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -111,12 +111,12 @@ class ITK_EXPORT ScalarImageToTextureFeaturesFilter : public ProcessObject public: /** Standard typedefs */ typedef ScalarImageToTextureFeaturesFilter Self; - typedef Object Superclass; + typedef ProcessObject Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ - itkTypeMacro(ScalarImageToTextureFeaturesFilter, Object); + itkTypeMacro(ScalarImageToTextureFeaturesFilter, ProcessObject); /** standard New() method support */ itkNewMacro(Self); diff --git a/Utilities/ITK/Code/Review/Statistics/itkSubsample.h b/Utilities/ITK/Code/Review/Statistics/itkSubsample.h index c42a0be2ec796516665ed282c43d3eeaaec0b0d9..eb9f926c1382543fb1edf546ad43b5e276dfa1d4 100644 --- a/Utilities/ITK/Code/Review/Statistics/itkSubsample.h +++ b/Utilities/ITK/Code/Review/Statistics/itkSubsample.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSubsample.h,v $ Language: C++ - Date: $Date: 2009-05-22 12:55:07 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-06-15 12:40:37 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -46,7 +46,7 @@ public: typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ - itkTypeMacro(Subsample, Sample); + itkTypeMacro(Subsample, TSample); /** standard New() method support */ itkNewMacro(Self); diff --git a/Utilities/ITK/Code/Review/Statistics/itkTDistribution.cxx b/Utilities/ITK/Code/Review/Statistics/itkTDistribution.cxx index f567de0ad6a8f97910606e38f1292c3e609e7773..50629510f652c8863b259b65f8cebab0f4701c57 100644 --- a/Utilities/ITK/Code/Review/Statistics/itkTDistribution.cxx +++ b/Utilities/ITK/Code/Review/Statistics/itkTDistribution.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTDistribution.cxx,v $ Language: C++ - Date: $Date: 2009-05-10 18:27:08 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-08-07 15:40:35 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -85,7 +85,7 @@ TDistribution double pdf; pdf = (dgamma_(&dofplusoneon2) / dgamma_(&dofon2)) - / (sqrt(dof*vnl_math::pi) * pow(1.0 + ((x*x)/dof), dofplusoneon2)); + / (vcl_sqrt(dof*vnl_math::pi) * vcl_pow(1.0 + ((x*x)/dof), dofplusoneon2)); return pdf; } @@ -191,10 +191,10 @@ TDistribution dof4 = dof*dof3; gaussX = GaussianDistribution::InverseCDF(p); - gaussX3 = pow(gaussX, 3.0); - gaussX5 = pow(gaussX, 5.0); - gaussX7 = pow(gaussX, 7.0); - gaussX9 = pow(gaussX, 9.0); + gaussX3 = vcl_pow(gaussX, 3.0); + gaussX5 = vcl_pow(gaussX, 5.0); + gaussX7 = vcl_pow(gaussX, 7.0); + gaussX9 = vcl_pow(gaussX, 9.0); x = gaussX + (gaussX3 + gaussX) / (4.0 * dof) diff --git a/Utilities/ITK/Code/Review/itkAggregateLabelMapFilter.h b/Utilities/ITK/Code/Review/itkAggregateLabelMapFilter.h new file mode 100755 index 0000000000000000000000000000000000000000..56f93e43836c467bc750294b14a63fa926449616 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkAggregateLabelMapFilter.h @@ -0,0 +1,102 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkAggregateLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-07-10 14:15:37 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkAggregateLabelMapFilter_h +#define __itkAggregateLabelMapFilter_h + +#include "itkInPlaceLabelMapFilter.h" + +namespace itk +{ +/** \class AggregateLabelMapFilter + * \brief Collapses all labels into the first label. + * + * This filter takes a label map as input and visits the pixels of all labels + * and assigns them to the first label of the label map. At the end of the + * execution of this filter, the map will contain a single filter. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, + * INRA de Jouy-en-Josas, France. + * + * \sa ShapeLabelObject, RelabelComponentImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TImage > +class ITK_EXPORT AggregateLabelMapFilter : + public InPlaceLabelMapFilter<TImage> +{ +public: + /** Standard class typedefs. */ + typedef AggregateLabelMapFilter Self; + typedef InPlaceLabelMapFilter<TImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TImage ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::LabelObjectType LabelObjectType; + + /** ImageDimension constants */ + itkStaticConstMacro(ImageDimension, unsigned int, TImage::ImageDimension); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(AggregateLabelMapFilter, InPlaceLabelMapFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ +/* itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>));*/ + /** End concept checking */ +#endif + +protected: + AggregateLabelMapFilter() {}; + ~AggregateLabelMapFilter() {}; + + void PrintSelf(std::ostream& os, Indent indent) const; + + void GenerateData(); + +private: + AggregateLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + typedef typename Superclass::LabelObjectContainerType LabelObjectContainerType; + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkAggregateLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkAggregateLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkAggregateLabelMapFilter.txx new file mode 100755 index 0000000000000000000000000000000000000000..668cfc63a62c3a224b8686bf680f61bedfe62aca --- /dev/null +++ b/Utilities/ITK/Code/Review/itkAggregateLabelMapFilter.txx @@ -0,0 +1,78 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkAggregateLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-07-10 14:15:39 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkAggregateLabelMapFilter_txx +#define __itkAggregateLabelMapFilter_txx + +#include "itkAggregateLabelMapFilter.h" +#include "itkProgressReporter.h" + + +namespace itk { + +template <class TImage> +void +AggregateLabelMapFilter<TImage> +::GenerateData() +{ + + // Allocate the output + this->AllocateOutputs(); + + ImageType * output = this->GetOutput(); + + LabelObjectContainerType & labelObjectContainer = output->GetLabelObjectContainer(); + + ProgressReporter progress( this, 0, labelObjectContainer.size() ); + + typename LabelObjectContainerType::iterator it = labelObjectContainer.begin(); + if( it != labelObjectContainer.end() ) + { + LabelObjectType * mainLo = it->second; + progress.CompletedPixel(); + it++; + while( it != labelObjectContainer.end() ) + { + LabelObjectType * lo = it->second; + typename LabelObjectType::LineContainerType::const_iterator lit; + typename LabelObjectType::LineContainerType & lineContainer = lo->GetLineContainer(); + + for( lit = lineContainer.begin(); lit != lineContainer.end(); lit++ ) + { + mainLo->AddLine( *lit ); + } + // be sure to have the lines well organized + mainLo->Optimize(); + + progress.CompletedPixel(); + it++; + // must increment the iterator before removing the object to avoid invalidating the iterator + output->RemoveLabelObject( lo ); + + } + } +} + +template <class TImage> +void +AggregateLabelMapFilter<TImage> +::PrintSelf(std::ostream& os, Indent indent) const +{ + this->Superclass::PrintSelf(os, indent); +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkAnchorErodeDilateImageFilter.txx b/Utilities/ITK/Code/Review/itkAnchorErodeDilateImageFilter.txx index 2feb83f118dd93e890454e4ed5cf34b0d6a57575..2e13474c33855275a9e164d557da302c43217132 100644 --- a/Utilities/ITK/Code/Review/itkAnchorErodeDilateImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkAnchorErodeDilateImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAnchorErodeDilateImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-20 16:32:08 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-06-03 12:48:05 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -106,7 +106,7 @@ AnchorErodeDilateImageFilter<TImage, TKernel, TFunction1, TFunction2> for (unsigned i = 0; i < decomposition.size(); i++) { typename KernelType::LType ThisLine = decomposition[i]; - typename BresType::OffsetArray TheseOffsets = BresLine.buildLine(ThisLine, bufflength); + typename BresType::OffsetArray TheseOffsets = BresLine.BuildLine(ThisLine, bufflength); typedef typename KernelType::LType KernelLType; diff --git a/Utilities/ITK/Code/Review/itkAnchorOpenCloseImageFilter.txx b/Utilities/ITK/Code/Review/itkAnchorOpenCloseImageFilter.txx index 628afa54eacf3bdc5f75cbc14266f6e141fcb85b..66fad3149cc2da31944cd1ec45525ee151b84c52 100644 --- a/Utilities/ITK/Code/Review/itkAnchorOpenCloseImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkAnchorOpenCloseImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAnchorOpenCloseImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-05-08 19:48:04 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-06-03 12:48:05 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -103,7 +103,7 @@ AnchorOpenCloseImageFilter<TImage, TKernel, TLessThan, TGreaterThan, TLessEqual, for (unsigned i = 0; i < decomposition.size() - 1; i++) { KernelLType ThisLine = decomposition[i]; - BresOffsetArray TheseOffsets = BresLine.buildLine(ThisLine, bufflength); + BresOffsetArray TheseOffsets = BresLine.BuildLine(ThisLine, bufflength); unsigned int SELength = GetLinePixels<KernelLType>(ThisLine); // want lines to be odd if (!(SELength%2)) @@ -125,7 +125,7 @@ AnchorOpenCloseImageFilter<TImage, TKernel, TLessThan, TGreaterThan, TLessEqual, { unsigned i = decomposition.size() - 1; KernelLType ThisLine = decomposition[i]; - typename BresType::OffsetArray TheseOffsets = BresLine.buildLine(ThisLine, bufflength); + typename BresType::OffsetArray TheseOffsets = BresLine.BuildLine(ThisLine, bufflength); unsigned int SELength = GetLinePixels<KernelLType>(ThisLine); // want lines to be odd if (!(SELength%2)) @@ -148,7 +148,7 @@ AnchorOpenCloseImageFilter<TImage, TKernel, TLessThan, TGreaterThan, TLessEqual, for (int i = decomposition.size() - 2; i >= 0; --i) { KernelLType ThisLine = decomposition[i]; - typename BresType::OffsetArray TheseOffsets = BresLine.buildLine(ThisLine, bufflength); + typename BresType::OffsetArray TheseOffsets = BresLine.BuildLine(ThisLine, bufflength); unsigned int SELength = GetLinePixels<KernelLType>(ThisLine); // want lines to be odd if (!(SELength%2)) diff --git a/Utilities/ITK/Code/Review/itkAreaOpeningImageFilter.h b/Utilities/ITK/Code/Review/itkAreaOpeningImageFilter.h index 89e03c4015f698cf837ba4e8c145e4637160e0b7..b9071ed047fca58ff670802d72fea6b752cd8fb0 100644 --- a/Utilities/ITK/Code/Review/itkAreaOpeningImageFilter.h +++ b/Utilities/ITK/Code/Review/itkAreaOpeningImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkAreaOpeningImageFilter.h,v $ Language: C++ - Date: $Date: 2009-02-20 17:33:49 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-06-17 12:17:54 $ + Version: $Revision: 1.4 $ Copyright ( c ) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -45,6 +45,12 @@ namespace itk * included, but operation appears incorrect. Check the ifdefs if you * are interested. * + * This code was contributed in the Insight Journal paper + * + * http://hdl.handle.net/1926/1316 + * http://www.insight-journal.org/browse/publication/203 + * + * * \author Richard Beare. Department of Medicine, Monash University, Melbourne, Australia. * */ diff --git a/Utilities/ITK/Code/Review/itkAutoCropLabelMapFilter.h b/Utilities/ITK/Code/Review/itkAutoCropLabelMapFilter.h new file mode 100755 index 0000000000000000000000000000000000000000..ef122ecb73957f4400e0b6deecf4ce5663a8b8cc --- /dev/null +++ b/Utilities/ITK/Code/Review/itkAutoCropLabelMapFilter.h @@ -0,0 +1,122 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkAutoCropLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-07-20 23:05:58 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + Portions of this code are covered under the VTK copyright. + See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkAutoCropLabelMapFilter_h +#define __itkAutoCropLabelMapFilter_h + +#include "itkChangeRegionLabelMapFilter.h" + +namespace itk +{ + +/** \class AutoCropLabelMapFilter + * \brief Crop a LabelMap image to fit exactly the objects in the LabelMap. + * + * The CropBorder can be used to add a border which will never be larger than + * the input image. To add a border of size independent of the input image, + * PadLabelMapFilter can be used. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * \sa PadLabelMapFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template <class TInputImage> +class ITK_EXPORT AutoCropLabelMapFilter : + public ChangeRegionLabelMapFilter<TInputImage> +{ +public: + /** Standard class typedefs. */ + typedef AutoCropLabelMapFilter Self; + typedef ChangeRegionLabelMapFilter<TInputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Standard New method. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(AutoCropLabelMapFilter, ChangeRegionImageFilter); + + /** Superclass typedefs. */ + typedef typename Superclass::OutputImageType OutputImageType; + typedef typename Superclass::OutputImagePointer OutputImagePointer; + typedef typename Superclass::OutputImageRegionType OutputImageRegionType; + typedef typename Superclass::OutputImagePixelType OutputImagePixelType; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename InputImageType::LabelObjectType LabelObjectType; + + typedef typename InputImageType::PixelType PixelType; + typedef typename InputImageType::IndexType IndexType; + typedef typename InputImageType::SizeType SizeType; + typedef typename InputImageType::RegionType RegionType; + + typedef TInputImage TOutputImage; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, TOutputImage::ImageDimension); + itkStaticConstMacro(ImageDimension, unsigned int, TOutputImage::ImageDimension); + + + /** + * Set/Get the border added to the mask before the crop. The default is 0 on * all the axis. + */ + itkSetMacro(CropBorder, SizeType); + itkGetConstReferenceMacro(CropBorder, SizeType); + +protected: + AutoCropLabelMapFilter(); + ~AutoCropLabelMapFilter() {}; + + void PrintSelf(std::ostream& os, Indent indent) const; + + virtual void GenerateOutputInformation(); + +private: + AutoCropLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + void FindBoundingBox(); + void SetAndPadCropRegion(); + + SizeType m_CropBorder; + TimeStamp m_CropTimeStamp; + + IndexType m_MinIndex; + IndexType m_MaxIndex; +}; + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkAutoCropLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkAutoCropLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkAutoCropLabelMapFilter.txx new file mode 100755 index 0000000000000000000000000000000000000000..2fa2ff5d25ee55fab4f523be97cbcd1eec197566 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkAutoCropLabelMapFilter.txx @@ -0,0 +1,169 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkAutoCropLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-07-20 23:34:02 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + Portions of this code are covered under the VTK copyright. + See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkAutoCropLabelMapFilter_txx +#define __itkAutoCropLabelMapFilter_txx +#include "itkAutoCropLabelMapFilter.h" + + +namespace itk +{ + +template <class TInputImage> +AutoCropLabelMapFilter<TInputImage> +::AutoCropLabelMapFilter() +{ + m_CropBorder.Fill( 0 ); +} + +template <class TInputImage> +void +AutoCropLabelMapFilter<TInputImage> +::GenerateOutputInformation() +{ + + const InputImageType * input = this->GetInput(); + + // + // FIXME: This way of implementing a GenerateOutputInformation() method is suspicious. + // Needs to be revisited. + // + if( !(input->GetMTime() > m_CropTimeStamp) && !(this->GetMTime() > m_CropTimeStamp) ) + { + // early exit, crop sizes already computed + return; + } + + // update the input if needed + if( input->GetSource() ) + { + ProcessObject * upstream = input->GetSource(); + if (upstream) + { + upstream->Update(); + } + } + + this->FindBoundingBox(); + this->SetAndPadCropRegion(); +} + +template <class TInputImage> +void +AutoCropLabelMapFilter<TInputImage> +::FindBoundingBox() +{ + typedef typename InputImageType::IndexValueType IndexValueType; + + // find the bounding box of the objects + this->m_MinIndex.Fill( NumericTraits< IndexValueType >::max() ); + this->m_MaxIndex.Fill( NumericTraits< IndexValueType >::NonpositiveMin() ); + + const InputImageType * inputImage = this->GetInput(); + + // iterate over all the lines + typename InputImageType::LabelObjectContainerType container = inputImage->GetLabelObjectContainer(); + typename InputImageType::LabelObjectContainerType::const_iterator loit = container.begin(); + + while( loit != container.end() ) + { + const LabelObjectType * labelObject = loit->second; + typename LabelObjectType::LineContainerType::const_iterator lit; + const typename LabelObjectType::LineContainerType & lineContainer = labelObject->GetLineContainer(); + + lit = lineContainer.begin(); + + while( lit != lineContainer.end() ) + { + const IndexType & idx = lit->GetIndex(); + IndexValueType length = lit->GetLength(); + + // update the mins and maxs + for( int i=0; i<ImageDimension; i++) + { + if( idx[i] < this->m_MinIndex[i] ) + { + this->m_MinIndex[i] = idx[i]; + } + if( idx[i] > this->m_MaxIndex[i] ) + { + this->m_MaxIndex[i] = idx[i]; + } + } + // must fix the max for the axis 0 + if( idx[0] + (IndexValueType)length > this->m_MaxIndex[0] ) + { + this->m_MaxIndex[0] = idx[0] + length - 1; + } + lit++; + } + loit++; + } + +} + +template <class TInputImage> +void +AutoCropLabelMapFilter<TInputImage> +::SetAndPadCropRegion() +{ + const InputImageType * input = this->GetInput(); + + // prefetch image region and size + InputImageRegionType cropRegion = input->GetLargestPossibleRegion(); + + // final computation + SizeType regionSize; + for( int i=0; i<ImageDimension; i++ ) + { + regionSize[i] = this->m_MaxIndex[i] - this->m_MinIndex[i] + 1; + } + cropRegion.SetIndex( this->m_MinIndex ); + cropRegion.SetSize( regionSize ); + + // pad the crop border while ensuring border is not larger than the largest + // possible region of the input image + cropRegion.PadByRadius( m_CropBorder ); + cropRegion.Crop( input->GetLargestPossibleRegion() ); + + // finally set that region as the largest output region + this->SetRegion(cropRegion); + m_CropTimeStamp.Modified(); + + Superclass::GenerateOutputInformation(); + + +} + +template <class TImage> +void +AutoCropLabelMapFilter<TImage> +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "Crop Border: " << m_CropBorder << std::endl; + os << indent << "Crop Time Stamp: " << m_CropTimeStamp << std::endl; + os << indent << "Min Indexes : " << m_MinIndex << std::endl; + os << indent << "Max Indexes : " << m_MaxIndex << std::endl; +} + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkBinaryImageToLabelMapFilter.h b/Utilities/ITK/Code/Review/itkBinaryImageToLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..8835e6d8cf208bbc81923c9248a67ca31e21010f --- /dev/null +++ b/Utilities/ITK/Code/Review/itkBinaryImageToLabelMapFilter.h @@ -0,0 +1,252 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkBinaryImageToLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-07-22 21:25:55 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef __itkBinaryImageToLabelMapFilter_h +#define __itkBinaryImageToLabelMapFilter_h + +#include "itkImageToImageFilter.h" +#include "itkImage.h" +#include "itkConceptChecking.h" +#include <vector> +#include <map> +#include "itkProgressReporter.h" +#include "itkBarrier.h" + +namespace itk +{ + +/** + * \class BinaryImageToLabelMapFilter + * \brief Label the connected components in a binary image and produce a + * collection of label objects. + * + * BinaryImageToLabelMapFilter labels the objects in a binary image. + * Each distinct object is assigned a unique label. + * The final object labels start with 1 and are consecutive. Objects + * that are reached earlier by a raster order scan have a lower + * label. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * \sa ConnectedComponentImageFilter, LabelImageToLabelMapFilter, LabelMap + */ + +template <class TInputImage, + class TOutputImage = + LabelMap< LabelObject< unsigned long, ::itk::GetImageDimension<TInputImage>::ImageDimension> > > +class ITK_EXPORT BinaryImageToLabelMapFilter : + public ImageToImageFilter< TInputImage, TOutputImage > +{ +public: + /** + * Standard "Self" & Superclass typedef. + */ + typedef BinaryImageToLabelMapFilter Self; + typedef ImageToImageFilter< TInputImage, TOutputImage > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** + * Method for creation through the object factory. + */ + itkNewMacro(Self); + + /** + * Run-time type information (and related methods) + */ + itkTypeMacro(BinaryImageToLabelMapFilter, ImageToImageFilter); + + /** + * Types from the Superclass + */ + typedef typename Superclass::InputImagePointer InputImagePointer; + + /** + * Extract some information from the image types. Dimensionality + * of the two images is assumed to be the same. + */ + typedef typename TOutputImage::PixelType OutputPixelType; + typedef typename TInputImage::PixelType InputPixelType; + typedef typename TInputImage::SizeValueType SizeValueType; + typedef typename TInputImage::OffsetValueType OffsetValueType; + itkStaticConstMacro(ImageDimension, unsigned int, TOutputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, TOutputImage::ImageDimension); + itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); + + /** + * Image typedef support + */ + typedef TInputImage InputImageType; + typedef typename TInputImage::IndexType IndexType; + typedef typename TInputImage::SizeType SizeType; + typedef typename TInputImage::OffsetType OffsetType; + + typedef TOutputImage OutputImageType; + typedef typename TOutputImage::RegionType RegionType; + typedef typename TOutputImage::IndexType OutputIndexType; + typedef typename TOutputImage::SizeType OutputSizeType; + typedef typename TOutputImage::OffsetType OutputOffsetType; + typedef typename TOutputImage::PixelType OutputImagePixelType; + + typedef std::list<IndexType> ListType; + + /** + * Set/Get whether the connected components are defined strictly by + * face connectivity or by face+edge+vertex connectivity. Default is + * FullyConnectedOff. For objects that are 1 pixel wide, use + * FullyConnectedOn. + */ + itkSetMacro(FullyConnected, bool); + itkGetConstReferenceMacro(FullyConnected, bool); + itkBooleanMacro(FullyConnected); + + // only set after completion + itkGetConstReferenceMacro( NumberOfObjects, unsigned long); + + /** + * Set/Get the value used as "background" in the output image. + * Defaults to NumericTraits<OutputPixelType>::NonpositiveMin(). + */ + itkSetMacro(OutputBackgroundValue, OutputPixelType); + itkGetConstMacro(OutputBackgroundValue, OutputPixelType); + + /** + * Set/Get the value to be consider "foreground" in the input image. + * Defaults to NumericTraits<InputPixelType>::max(). + */ + itkSetMacro(InputForegroundValue, InputPixelType); + itkGetConstMacro(InputForegroundValue, InputPixelType); + + +#ifdef ITK_USE_CONCEPT_CHECKING + // Concept checking -- input and output dimensions must be the same + itkConceptMacro(SameDimension, + (Concept::SameDimension<itkGetStaticConstMacro(InputImageDimension), + itkGetStaticConstMacro(OutputImageDimension)>)); +#endif + + +protected: + BinaryImageToLabelMapFilter(); + virtual ~BinaryImageToLabelMapFilter() {} + void PrintSelf(std::ostream& os, Indent indent) const; + + /** + * Standard pipeline method. + */ + void BeforeThreadedGenerateData (); + void AfterThreadedGenerateData (); + void ThreadedGenerateData (const RegionType& outputRegionForThread, int threadId); + + /** BinaryImageToLabelMapFilter needs the entire input. Therefore + * it must provide an implementation GenerateInputRequestedRegion(). + * \sa ProcessObject::GenerateInputRequestedRegion(). */ + void GenerateInputRequestedRegion(); + + /** BinaryImageToLabelMapFilter will produce all of the output. + * Therefore it must provide an implementation of + * EnlargeOutputRequestedRegion(). + * \sa ProcessObject::EnlargeOutputRequestedRegion() */ + void EnlargeOutputRequestedRegion(DataObject *itkNotUsed(output)); + +private: + BinaryImageToLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + // some additional types + typedef typename TOutputImage::RegionType::SizeType OutSizeType; + + // types to support the run length encoding of lines + class runLength + { + public: + // run length information - may be a more type safe way of doing this + long int length; + typename InputImageType::IndexType where; // Index of the start of the run + unsigned long int label; // the initial label of the run + }; + + typedef std::vector<runLength> lineEncoding; + + // the map storing lines + typedef std::vector<lineEncoding> LineMapType; + + typedef std::vector<long> OffsetVectorType; + + // the types to support union-find operations + typedef std::vector<unsigned long int> UnionFindType; + UnionFindType m_UnionFind; + UnionFindType m_Consecutive; + // functions to support union-find operations + void InitUnion(const unsigned long int size) + { + m_UnionFind = UnionFindType(size + 1); + } + + void InsertSet(const unsigned long int label); + unsigned long int LookupSet(const unsigned long int label); + void LinkLabels(const unsigned long int lab1, const unsigned long int lab2); + unsigned long int CreateConsecutive(); + ////////////////// + bool CheckNeighbors(const OutputIndexType &A, + const OutputIndexType &B); + + void CompareLines(lineEncoding ¤t, const lineEncoding &Neighbour); + + void FillOutput(const LineMapType &LineMap, + ProgressReporter &progress); + + void SetupLineOffsets( OffsetVectorType & LineOffsets ); + + void Wait() + { + // use m_NumberOfLabels.size() to get the number of thread used + if( m_NumberOfLabels.size() > 1 ) + { + m_Barrier->Wait(); + } + } + + OutputPixelType m_OutputBackgroundValue; + InputPixelType m_InputForegroundValue; + + SizeValueType m_NumberOfObjects; + + bool m_FullyConnected; + + typename std::vector< SizeValueType > m_NumberOfLabels; + typename std::vector< SizeValueType > m_FirstLineIdToJoin; + typename Barrier::Pointer m_Barrier; + +#if !defined(CABLE_CONFIGURATION) + LineMapType m_LineMap; +#endif +}; + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#if !defined(CABLE_CONFIGURATION) +#include "itkBinaryImageToLabelMapFilter.txx" +#endif +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkBinaryImageToLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkBinaryImageToLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..b0ed794d442fbc57487af9a63b28bdcd9b78b3bc --- /dev/null +++ b/Utilities/ITK/Code/Review/itkBinaryImageToLabelMapFilter.txx @@ -0,0 +1,631 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkBinaryImageToLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-24 13:34:42 $ + Version: $Revision: 1.9 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkBinaryImageToLabelMapFilter_txx +#define __itkBinaryImageToLabelMapFilter_txx + +#include "itkBinaryImageToLabelMapFilter.h" +#include "itkNumericTraits.h" + +// don't think we need the indexed version as we only compute the +// index at the start of each run, but there isn't a choice +#include "itkImageLinearConstIteratorWithIndex.h" +#include "itkConstShapedNeighborhoodIterator.h" +#include "itkImageRegionIterator.h" +#include "itkConnectedComponentAlgorithm.h" + +namespace itk +{ + +template< class TInputImage, class TOutputImage > +BinaryImageToLabelMapFilter< TInputImage, TOutputImage > +::BinaryImageToLabelMapFilter() +{ + this->m_FullyConnected = false; + this->m_NumberOfObjects = 0; + this->m_OutputBackgroundValue = NumericTraits<OutputPixelType>::NonpositiveMin(); + this->m_InputForegroundValue = NumericTraits<InputPixelType>::max(); +} + + +template< class TInputImage, class TOutputImage > +void +BinaryImageToLabelMapFilter< TInputImage, TOutputImage > +::GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // We need all the input. + InputImagePointer input = const_cast<InputImageType *>(this->GetInput()); + if( !input ) + { + return; + } + input->SetRequestedRegion( input->GetLargestPossibleRegion() ); +} + +template< class TInputImage, class TOutputImage > +void +BinaryImageToLabelMapFilter< TInputImage, TOutputImage> +::EnlargeOutputRequestedRegion(DataObject *) +{ + this->GetOutput() + ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); +} + + +template< class TInputImage, class TOutputImage > +void +BinaryImageToLabelMapFilter< TInputImage, TOutputImage > +::BeforeThreadedGenerateData() +{ + typename TOutputImage::Pointer output = this->GetOutput(); + typename TInputImage::ConstPointer input = this->GetInput(); + + output->SetBackgroundValue( this->m_OutputBackgroundValue ); + + long nbOfThreads = this->GetNumberOfThreads(); + if( itk::MultiThreader::GetGlobalMaximumNumberOfThreads() != 0 ) + { + nbOfThreads = vnl_math_min( this->GetNumberOfThreads(), itk::MultiThreader::GetGlobalMaximumNumberOfThreads() ); + } + + // number of threads can be constrained by the region size, so call the SplitRequestedRegion + // to get the real number of threads which will be used + typename TOutputImage::RegionType splitRegion; // dummy region - just to call the following method + nbOfThreads = this->SplitRequestedRegion(0, nbOfThreads, splitRegion); + + // set up the vars used in the threads + this->m_NumberOfLabels.clear(); + this->m_NumberOfLabels.resize( nbOfThreads, 0 ); + this->m_Barrier = Barrier::New(); + this->m_Barrier->Initialize( nbOfThreads ); + + SizeValueType pixelcount = output->GetRequestedRegion().GetNumberOfPixels(); + SizeValueType xsize = output->GetRequestedRegion().GetSize()[0]; + SizeValueType linecount = pixelcount/xsize; + m_LineMap.resize( linecount ); + m_FirstLineIdToJoin.resize( nbOfThreads - 1 ); +} + + +template< class TInputImage, class TOutputImage > +void +BinaryImageToLabelMapFilter< TInputImage, TOutputImage > +::ThreadedGenerateData(const RegionType& outputRegionForThread, + int threadId) +{ + typename TOutputImage::Pointer output = this->GetOutput(); + typename TInputImage::ConstPointer input = this->GetInput(); + + long nbOfThreads = this->m_NumberOfLabels.size(); + + // create a line iterator + typedef itk::ImageLinearConstIteratorWithIndex<InputImageType> + InputLineIteratorType; + InputLineIteratorType inLineIt(input, outputRegionForThread); + inLineIt.SetDirection(0); + + // set the progress reporter to deal with the number of lines + SizeValueType pixelcountForThread = outputRegionForThread.GetNumberOfPixels(); + SizeValueType xsizeForThread = outputRegionForThread.GetSize()[0]; + SizeValueType linecountForThread = pixelcountForThread/xsizeForThread; + ProgressReporter progress(this, threadId, linecountForThread); + + // find the split axis + IndexType outputRegionIdx = output->GetRequestedRegion().GetIndex(); + IndexType outputRegionForThreadIdx = outputRegionForThread.GetIndex(); + SizeType outputRegionSize = output->GetRequestedRegion().GetSize(); + SizeType outputRegionForThreadSize = outputRegionForThread.GetSize(); + int splitAxis = 0; + for( int i=0; i<ImageDimension; i++ ) + { + if( outputRegionSize[i] != outputRegionForThreadSize[i] ) + { + splitAxis = i; + } + } + + // compute the number of pixels before that threads + outputRegionSize[splitAxis] = outputRegionForThreadIdx[splitAxis] - outputRegionIdx[splitAxis]; + SizeValueType firstLineIdForThread = RegionType( outputRegionIdx, outputRegionSize ).GetNumberOfPixels() / xsizeForThread; + SizeValueType lineId = firstLineIdForThread; + + OffsetVectorType LineOffsets; + this->SetupLineOffsets(LineOffsets); + + long nbOfLabels = 0; + for( inLineIt.GoToBegin(); + !inLineIt.IsAtEnd(); + inLineIt.NextLine() ) + { + inLineIt.GoToBeginOfLine(); + lineEncoding ThisLine; + while (! inLineIt.IsAtEndOfLine()) + { + InputPixelType PVal = inLineIt.Get(); + //std::cout << inLineIt.GetIndex() << std::endl; + if (PVal == this->m_InputForegroundValue) + { + // We've hit the start of a run + runLength thisRun; + long length=0; + IndexType thisIndex; + thisIndex = inLineIt.GetIndex(); + //std::cout << thisIndex << std::endl; + ++length; + ++inLineIt; + while( !inLineIt.IsAtEndOfLine() + && inLineIt.Get() == this->m_InputForegroundValue ) + { + ++length; + ++inLineIt; + } + // create the run length object to go in the vector + thisRun.length=length; + thisRun.label=0; // will give a real label later + thisRun.where = thisIndex; + ThisLine.push_back(thisRun); + nbOfLabels++; + } + else + { + ++inLineIt; + } + } + m_LineMap[lineId] = ThisLine; + lineId++; + progress.CompletedPixel(); + } + + this->m_NumberOfLabels[threadId] = nbOfLabels; + + // wait for the other threads to complete that part + this->Wait(); + + // compute the total number of labels + nbOfLabels = 0; + for( int i=0; i<nbOfThreads; i++ ) + { + nbOfLabels += this->m_NumberOfLabels[i]; + } + + if( threadId == 0 ) + { + // set up the union find structure + this->InitUnion(nbOfLabels); + // insert all the labels into the structure -- an extra loop but + // saves complicating the ones that come later + typename LineMapType::iterator MapBegin, MapEnd, LineIt; + MapBegin = m_LineMap.begin(); + MapEnd = m_LineMap.end(); + LineIt = MapBegin; + unsigned long label = 1; + for (LineIt = MapBegin; LineIt != MapEnd; ++LineIt) + { + typename lineEncoding::iterator cIt; + for (cIt = LineIt->begin();cIt != LineIt->end();++cIt) + { + cIt->label = label; + this->InsertSet(label); + label++; + } + } + } + + // wait for the other threads to complete that part + this->Wait(); + + // now process the map and make appropriate entries in an equivalence + // table + // assert( linecount == m_LineMap.size() ); + SizeValueType pixelcount = output->GetRequestedRegion().GetNumberOfPixels(); + SizeValueType xsize = output->GetRequestedRegion().GetSize()[0]; + OffsetValueType linecount = pixelcount/xsize; + + SizeValueType lastLineIdForThread = linecount; + long nbOfLineIdToJoin = 0; + if( threadId != nbOfThreads - 1 ) + { + SizeType localRegionSize = outputRegionForThreadSize; + localRegionSize[splitAxis] -= 1; + lastLineIdForThread = firstLineIdForThread + RegionType( outputRegionIdx, localRegionSize ).GetNumberOfPixels() / xsizeForThread; + m_FirstLineIdToJoin[threadId] = lastLineIdForThread; + // found the number of line ids to join + nbOfLineIdToJoin = RegionType( outputRegionIdx, outputRegionForThread.GetSize() ).GetNumberOfPixels() / xsizeForThread + - RegionType( outputRegionIdx, localRegionSize ).GetNumberOfPixels() / xsizeForThread; + } + + for(SizeValueType ThisIdx = firstLineIdForThread; ThisIdx < lastLineIdForThread; ++ThisIdx) + { + if( !m_LineMap[ThisIdx].empty() ) + { + OffsetVectorType::const_iterator I = LineOffsets.begin(); + while( I != LineOffsets.end() ) + { + OffsetValueType NeighIdx = ThisIdx + (*I); + // check if the neighbor is in the map + if ( NeighIdx >= 0 && NeighIdx < linecount && !m_LineMap[NeighIdx].empty() ) + { + // Now check whether they are really neighbors + bool areNeighbors = this->CheckNeighbors(m_LineMap[ThisIdx][0].where, m_LineMap[NeighIdx][0].where); + if (areNeighbors) + { + // Compare the two lines + this->CompareLines(m_LineMap[ThisIdx], m_LineMap[NeighIdx]); + } + } + ++I; + } + } + } + + // wait for the other threads to complete that part + this->Wait(); + + while( m_FirstLineIdToJoin.size() != 0 ) + { + const SizeValueType threadChunk = 2 * threadId; + if( threadChunk < (SizeValueType)m_FirstLineIdToJoin.size() ) + { + for(SizeValueType ThisIdx = m_FirstLineIdToJoin[threadChunk]; + ThisIdx < m_FirstLineIdToJoin[threadChunk] + nbOfLineIdToJoin; + ++ThisIdx) + { + if( !m_LineMap[ThisIdx].empty() ) + { + OffsetVectorType::const_iterator I = LineOffsets.begin(); + while( I != LineOffsets.end() ) + { + OffsetValueType NeighIdx = ThisIdx + (*I); + // check if the neighbor is in the map + if ( NeighIdx >= 0 && NeighIdx < linecount && !m_LineMap[NeighIdx].empty() ) + { + // Now check whether they are really neighbors + bool areNeighbors + = CheckNeighbors(m_LineMap[ThisIdx][0].where, m_LineMap[NeighIdx][0].where); + if (areNeighbors) + { + // Compare the two lines + CompareLines(m_LineMap[ThisIdx], m_LineMap[NeighIdx]); + } + } + ++I; + } + } + } + } + + this->Wait(); + + if( threadId == 0 ) + { + // remove the region already joined + typename std::vector< SizeValueType > newFirstLineIdToJoin; + for( SizeValueType i = 1; i < (SizeValueType)m_FirstLineIdToJoin.size(); i += 2 ) + { + newFirstLineIdToJoin.push_back( m_FirstLineIdToJoin[i] ); + } + m_FirstLineIdToJoin = newFirstLineIdToJoin; + } + + this->Wait(); + + } + +} + +template< class TInputImage, class TOutputImage > +void +BinaryImageToLabelMapFilter< TInputImage, TOutputImage > +::AfterThreadedGenerateData() +{ + typename TOutputImage::Pointer output = this->GetOutput(); + typename TInputImage::ConstPointer input = this->GetInput(); + SizeValueType pixelcount = output->GetRequestedRegion().GetNumberOfPixels(); + SizeValueType xsize = output->GetRequestedRegion().GetSize()[0]; + SizeValueType linecount = pixelcount/xsize; + unsigned long int totalLabs = CreateConsecutive(); + ProgressReporter progress(this, 0, linecount); + // check for overflow exception here + if( totalLabs > static_cast<unsigned long int>( + NumericTraits<OutputPixelType>::max() ) ) + { + itkExceptionMacro( + << "Number of objects greater than maximum of output pixel type " ); + } + + for (SizeValueType ThisIdx = 0; ThisIdx<linecount; ThisIdx++) + { + // now fill the labelled sections + typedef typename lineEncoding::const_iterator LineIterator; + + LineIterator cIt = m_LineMap[ThisIdx].begin(); + while( cIt != m_LineMap[ThisIdx].end() ) + { + SizeValueType Ilab = LookupSet( cIt->label); + OutputPixelType lab = m_Consecutive[Ilab]; + output->SetLine( cIt->where, cIt->length, lab ); + ++cIt; + } + progress.CompletedPixel(); + } + + this->m_NumberOfLabels.clear(); + this->m_Barrier = NULL; + + m_LineMap.clear(); +} + + +template< class TInputImage, class TOutputImage > +void +BinaryImageToLabelMapFilter< TInputImage, TOutputImage > +::SetupLineOffsets( OffsetVectorType &LineOffsets) +{ + // Create a neighborhood so that we can generate a table of offsets + // to "previous" line indexes + // We are going to mis-use the neighborhood iterators to compute the + // offset for us. All this messing around produces an array of + // offsets that will be used to index the map + typename TOutputImage::Pointer output = this->GetOutput(); + typedef Image<long, TOutputImage::ImageDimension - 1> PretendImageType; + typedef typename PretendImageType::RegionType::SizeType PretendSizeType; + typedef typename PretendImageType::RegionType::IndexType PretendIndexType; + typedef ConstShapedNeighborhoodIterator<PretendImageType> LineNeighborhoodType; + + typename PretendImageType::Pointer fakeImage; + fakeImage = PretendImageType::New(); + + typename PretendImageType::RegionType LineRegion; + //LineRegion = PretendImageType::RegionType::New(); + + OutSizeType OutSize = output->GetRequestedRegion().GetSize(); + + PretendSizeType PretendSize; + // The first dimension has been collapsed + for (unsigned int i = 0; i<PretendSize.GetSizeDimension(); i++) + { + PretendSize[i] = OutSize[i+1]; + } + + LineRegion.SetSize(PretendSize); + fakeImage->SetRegions( LineRegion ); + PretendSizeType kernelRadius; + kernelRadius.Fill(1); + LineNeighborhoodType lnit(kernelRadius, fakeImage, LineRegion); + + // only activate the indices that are "previous" to the current + // pixel and face connected (exclude the center pixel from the + // neighborhood) + // + setConnectivityPrevious( &lnit, m_FullyConnected ); + + typename LineNeighborhoodType::IndexListType ActiveIndexes; + ActiveIndexes = lnit.GetActiveIndexList(); + + typename LineNeighborhoodType::IndexListType::const_iterator LI; + + PretendIndexType idx = LineRegion.GetIndex(); + OffsetValueType offset = fakeImage->ComputeOffset( idx ); + + for (LI=ActiveIndexes.begin(); LI != ActiveIndexes.end(); LI++) + { + LineOffsets.push_back( fakeImage->ComputeOffset( idx + lnit.GetOffset( *LI ) ) - offset ); + } + + // LineOffsets is the thing we wanted. +} + + +template< class TInputImage, class TOutputImage > +bool +BinaryImageToLabelMapFilter< TInputImage, TOutputImage > +::CheckNeighbors(const OutputIndexType &A, + const OutputIndexType &B) +{ + // this checks whether the line encodings are really neighbors. The + // first dimension gets ignored because the encodings are along that + // axis + OutputOffsetType Off = A - B; + for (unsigned i = 1; i < OutputImageDimension; i++) + { + if (abs(Off[i]) > 1) + { + return(false); + } + } + return(true); +} + + +template< class TInputImage, class TOutputImage > +void +BinaryImageToLabelMapFilter< TInputImage, TOutputImage > +::CompareLines(lineEncoding ¤t, const lineEncoding &Neighbour) +{ + OffsetValueType offset = 0; + if (m_FullyConnected) + { + offset = 1; + } + + typename lineEncoding::const_iterator nIt, mIt; + typename lineEncoding::iterator cIt; + + mIt = Neighbour.begin(); // out marker iterator + + for (cIt = current.begin();cIt != current.end();++cIt) + { + //runLength cL = *cIt; + OffsetValueType cStart = cIt->where[0]; // the start x position + OffsetValueType cLast = cStart + cIt->length - 1; + + for (nIt=mIt; nIt != Neighbour.end(); ++nIt) + { + //runLength nL = *nIt; + OffsetValueType nStart = nIt->where[0]; + OffsetValueType nLast = nStart + nIt->length - 1; + // there are a few ways that neighbouring lines might overlap + // neighbor S E + // current S E + //------------------------------------------ + // neighbor S E + // current S E + //------------------------------------------ + // neighbor S E + // current S E + //------------------------------------------ + // neighbor S E + // current S E + //------------------------------------------ + OffsetValueType ss1 = nStart - offset; + // OffsetValueType ss2 = nStart + offset; + OffsetValueType ee1 = nLast - offset; + OffsetValueType ee2 = nLast + offset; + bool eq = false; + // the logic here can probably be improved a lot + if ((ss1 >= cStart) && (ee2 <= cLast)) + { + // case 1 + eq = true; + } + else + { + if ((ss1 <= cLast) && (ee2 >= cLast)) + { + // case 2 + eq = true; + } + else + { + if ((ss1 <= cStart) && (ee2 >= cStart)) + { + // case 3 + eq = true; + } + else + { + if ((ss1 <= cStart) && (ee2 >= cLast)) + { + // case 4 + eq = true; + } + } + } + } + if (eq) + { + LinkLabels(nIt->label, cIt->label); + } + + if (ee1 >= cLast) + { + // No point looking for more overlaps with the current run + // because the neighbor run is either case 2 or 4 + mIt = nIt; + break; + } + } + } + +} + +// union find related functions +template< class TInputImage, class TOutputImage > +void +BinaryImageToLabelMapFilter< TInputImage, TOutputImage > +::InsertSet(const unsigned long int label) +{ + m_UnionFind[label]=label; +} + +template< class TInputImage, class TOutputImage > +unsigned long int +BinaryImageToLabelMapFilter< TInputImage, TOutputImage > +::CreateConsecutive() +{ + m_Consecutive = UnionFindType(m_UnionFind.size()); + m_Consecutive[this->m_OutputBackgroundValue] = this->m_OutputBackgroundValue; + unsigned long int CLab = 0; + unsigned long int count = 0; + for( unsigned long int I = 1; I < m_UnionFind.size(); I++ ) + { + unsigned long int L = m_UnionFind[I]; + if( L == I ) + { + if( CLab == this->m_OutputBackgroundValue ) + { + ++CLab; + } + m_Consecutive[L] = CLab; + ++CLab; + ++count; + } + } + return count; +} + +template< class TInputImage, class TOutputImage > +unsigned long int +BinaryImageToLabelMapFilter< TInputImage, TOutputImage > +::LookupSet(const unsigned long int label) +{ + // recursively set the equivalence if necessary + if (label != m_UnionFind[label]) + { + m_UnionFind[label] = this->LookupSet(m_UnionFind[label]); + } + return(m_UnionFind[label]); +} + +template< class TInputImage, class TOutputImage > +void +BinaryImageToLabelMapFilter< TInputImage, TOutputImage > +::LinkLabels(const unsigned long int lab1, const unsigned long int lab2) +{ + unsigned long E1 = this->LookupSet(lab1); + unsigned long E2 = this->LookupSet(lab2); + + if (E1 < E2) + { + m_UnionFind[E2] = E1; + } + else + { + m_UnionFind[E1] = E2; + } +} + +template< class TInputImage, class TOutputImage > +void +BinaryImageToLabelMapFilter< TInputImage, TOutputImage > +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "FullyConnected: " << m_FullyConnected << std::endl; + os << indent << "InputForegroundValue: " + << static_cast<typename NumericTraits<InputPixelType>::PrintType>(this->m_InputForegroundValue) << std::endl; + os << indent << "OutputBackgroundValue: " + << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(this->m_OutputBackgroundValue) << std::endl; + os << indent << "Number of Objects: " << this->m_NumberOfObjects << std::endl; +} + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkBinaryImageToShapeLabelMapFilter.h b/Utilities/ITK/Code/Review/itkBinaryImageToShapeLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..0b7860706cd4aa706b4ba06442ea0ac1064b23f9 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkBinaryImageToShapeLabelMapFilter.h @@ -0,0 +1,171 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkBinaryImageToShapeLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-04 15:08:28 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkBinaryImageToShapeLabelMapFilter_h +#define __itkBinaryImageToShapeLabelMapFilter_h + +#include "itkImageToImageFilter.h" +#include "itkShapeLabelObject.h" +#include "itkLabelMap.h" +#include "itkBinaryImageToLabelMapFilter.h" +#include "itkShapeLabelMapFilter.h" + + +namespace itk { + +/** \class BinaryImageToShapeLabelMapFilter + * \brief Converts a binary image to a label map and valuate the shape attributes. + * + * A convenient class that converts a binary image to a label map and valuates the + * shape attributes at once. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * \sa ShapeLabelObject, LabelShapeOpeningImageFilter, BinaryStatisticsOpeningImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TInputImage, class TOutputImage=LabelMap< ShapeLabelObject< unsigned long, ::itk::GetImageDimension<TInputImage>::ImageDimension> > > +class ITK_EXPORT BinaryImageToShapeLabelMapFilter : + public ImageToImageFilter<TInputImage, TOutputImage> +{ +public: + /** Standard class typedefs. */ + typedef BinaryImageToShapeLabelMapFilter Self; + typedef ImageToImageFilter<TInputImage, TOutputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + + typedef TOutputImage OutputImageType; + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::ConstPointer OutputImageConstPointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + typedef typename OutputImageType::LabelObjectType LabelObjectType; + + /** ImageDimension constants */ + itkStaticConstMacro( InputImageDimension, unsigned int, TInputImage::ImageDimension ); + itkStaticConstMacro( OutputImageDimension, unsigned int, TInputImage::ImageDimension ); + itkStaticConstMacro( ImageDimension, unsigned int, TInputImage::ImageDimension ); + + typedef BinaryImageToLabelMapFilter< InputImageType, OutputImageType > LabelizerType; + typedef Image< typename OutputImageType::PixelType, itkGetStaticConstMacro(OutputImageDimension)> + ShapeLabelFilterOutput; + typedef ShapeLabelMapFilter< TOutputImage, ShapeLabelFilterOutput > LabelObjectValuatorType; + + /** Standard New method. */ + itkNewMacro( Self ); + + /** Runtime information support. */ + itkTypeMacro( BinaryImageToShapeLabelMapFilter, ImageToImageFilter ); + + /** + * Set/Get whether the connected components are defined strictly by face connectivity or + * by face+edge+vertex connectivity. Default is FullyConnectedOff. For objects that + * are 1 pixel wide, use FullyConnectedOn. + */ + itkSetMacro( FullyConnected, bool ); + itkGetConstReferenceMacro( FullyConnected, bool ); + itkBooleanMacro( FullyConnected ); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>)); + /** End concept checking */ +#endif + + /** + * Set/Get the value used as "background" in the output image. + * Defaults to NumericTraits<PixelType>::NonpositiveMin(). + */ + itkSetMacro( OutputBackgroundValue, OutputImagePixelType ); + itkGetConstMacro( OutputBackgroundValue, OutputImagePixelType ); + + /** + * Set/Get the value used as "foreground" in the output image. + * Defaults to NumericTraits<PixelType>::max(). + */ + itkSetMacro( InputForegroundValue, InputImagePixelType ); + itkGetConstMacro( InputForegroundValue, InputImagePixelType ); + + /** + * Set/Get whether the maximum Feret diameter should be computed or not. + * Default value is false, because of the high computation time required. + */ + itkSetMacro( ComputeFeretDiameter, bool ); + itkGetConstReferenceMacro( ComputeFeretDiameter, bool ); + itkBooleanMacro( ComputeFeretDiameter ); + + /** + * Set/Get whether the perimeter should be computed or not. + * Default value is false, because of the high computation time required. + */ + itkSetMacro( ComputePerimeter, bool ); + itkGetConstReferenceMacro( ComputePerimeter, bool ); + itkBooleanMacro( ComputePerimeter ); + + +protected: + BinaryImageToShapeLabelMapFilter(); + ~BinaryImageToShapeLabelMapFilter() {}; + void PrintSelf( std::ostream& os, Indent indent ) const; + + /** BinaryImageToShapeLabelMapFilter needs the entire input be available. + * Thus, it needs to provide an implementation of GenerateInputRequestedRegion(). */ + void GenerateInputRequestedRegion(); + + /** BinaryImageToShapeLabelMapFilter will produce the entire output. */ + void EnlargeOutputRequestedRegion( DataObject *itkNotUsed( output ) ); + + /** Single-threaded version of GenerateData. + * This filter delegates to GrayscaleGeodesicErodeImageFilter. */ + void GenerateData(); + + +private: + BinaryImageToShapeLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + bool m_FullyConnected; + OutputImagePixelType m_OutputBackgroundValue; + InputImagePixelType m_InputForegroundValue; + bool m_ComputeFeretDiameter; + bool m_ComputePerimeter; + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkBinaryImageToShapeLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkBinaryImageToShapeLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkBinaryImageToShapeLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..fbf68da7245c86f7f4d9e6d2b2106d2fd06f25bb --- /dev/null +++ b/Utilities/ITK/Code/Review/itkBinaryImageToShapeLabelMapFilter.txx @@ -0,0 +1,112 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkBinaryImageToShapeLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-07-29 21:44:31 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkBinaryImageToShapeLabelMapFilter_txx +#define __itkBinaryImageToShapeLabelMapFilter_txx + +#include "itkBinaryImageToShapeLabelMapFilter.h" +#include "itkProgressAccumulator.h" + + +namespace itk { + +template<class TInputImage, class TOutputImage> +BinaryImageToShapeLabelMapFilter<TInputImage, TOutputImage> +::BinaryImageToShapeLabelMapFilter() +{ + m_OutputBackgroundValue = NumericTraits<OutputImagePixelType>::NonpositiveMin(); + m_InputForegroundValue = NumericTraits<OutputImagePixelType>::max(); + m_FullyConnected = false; + m_ComputeFeretDiameter = false; + m_ComputePerimeter = false; +} + +template<class TInputImage, class TOutputImage> +void +BinaryImageToShapeLabelMapFilter<TInputImage, TOutputImage> +::GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // We need all the inputs. + InputImagePointer input = const_cast<InputImageType *>(this->GetInput()); + if( input ) + { + input->SetRequestedRegion( input->GetLargestPossibleRegion() ); + } +} + + +template<class TInputImage, class TOutputImage> +void +BinaryImageToShapeLabelMapFilter<TInputImage, TOutputImage> +::EnlargeOutputRequestedRegion(DataObject *) +{ + this->GetOutput() + ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); +} + + +template<class TInputImage, class TOutputImage> +void +BinaryImageToShapeLabelMapFilter<TInputImage, TOutputImage> +::GenerateData() +{ + // Create a process accumulator for tracking the progress of this minipipeline + ProgressAccumulator::Pointer progress = ProgressAccumulator::New(); + progress->SetMiniPipelineFilter(this); + + // Allocate the output + this->AllocateOutputs(); + + typename LabelizerType::Pointer labelizer = LabelizerType::New(); + labelizer->SetInput( this->GetInput() ); + labelizer->SetInputForegroundValue( m_InputForegroundValue ); + labelizer->SetOutputBackgroundValue( m_OutputBackgroundValue ); + labelizer->SetFullyConnected( m_FullyConnected ); + labelizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(labelizer, .5f); + + typename LabelObjectValuatorType::Pointer valuator = LabelObjectValuatorType::New(); + valuator->SetInput( labelizer->GetOutput() ); + valuator->SetNumberOfThreads( this->GetNumberOfThreads() ); + valuator->SetComputePerimeter( m_ComputePerimeter ); + valuator->SetComputeFeretDiameter( m_ComputeFeretDiameter ); + progress->RegisterInternalFilter(valuator, .5f); + + valuator->GraftOutput( this->GetOutput() ); + valuator->Update(); + this->GraftOutput( valuator->GetOutput() ); +} + + +template<class TInputImage, class TOutputImage> +void +BinaryImageToShapeLabelMapFilter<TInputImage, TOutputImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "FullyConnected: " << m_FullyConnected << std::endl; + os << indent << "BackgroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_OutputBackgroundValue) << std::endl; + os << indent << "ForegroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_InputForegroundValue) << std::endl; + os << indent << "ComputeFeretDiameter: " << m_ComputeFeretDiameter << std::endl; + os << indent << "ComputePerimeter: " << m_ComputePerimeter << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkBinaryImageToStatisticsLabelMapFilter.h b/Utilities/ITK/Code/Review/itkBinaryImageToStatisticsLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..4a8a68328697d3df0b1ad909070133e133684d25 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkBinaryImageToStatisticsLabelMapFilter.h @@ -0,0 +1,222 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkBinaryImageToStatisticsLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-11 14:24:40 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkBinaryImageToStatisticsLabelMapFilter_h +#define __itkBinaryImageToStatisticsLabelMapFilter_h + +#include "itkImageToImageFilter.h" +#include "itkStatisticsLabelObject.h" +#include "itkLabelMap.h" +#include "itkBinaryImageToLabelMapFilter.h" +#include "itkStatisticsLabelMapFilter.h" + + +namespace itk { + +/** \class BinaryImageToStatisticsLabelMapFilter + * \brief a convenient class to convert a binary image to a label map and valuate the statistics attributes at once + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \sa StatisticsLabelObject, LabelStatisticsOpeningImageFilter, BinaryStatisticsOpeningImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TInputImage, class TFeatureImage, class TOutputImage=LabelMap< StatisticsLabelObject< unsigned long, ::itk::GetImageDimension<TInputImage>::ImageDimension > > > +class ITK_EXPORT BinaryImageToStatisticsLabelMapFilter : + public ImageToImageFilter<TInputImage, TOutputImage> +{ +public: + /** Standard class typedefs. */ + typedef BinaryImageToStatisticsLabelMapFilter Self; + typedef ImageToImageFilter<TInputImage, TOutputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + + typedef TOutputImage OutputImageType; + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::ConstPointer OutputImageConstPointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + typedef typename OutputImageType::LabelObjectType LabelObjectType; + + typedef TFeatureImage FeatureImageType; + typedef typename FeatureImageType::Pointer FeatureImagePointer; + typedef typename FeatureImageType::ConstPointer FeatureImageConstPointer; + typedef typename FeatureImageType::PixelType FeatureImagePixelType; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(ImageDimension, unsigned int, + TInputImage::ImageDimension); + + typedef BinaryImageToLabelMapFilter< InputImageType, OutputImageType > LabelizerType; + typedef StatisticsLabelMapFilter< OutputImageType, FeatureImageType > LabelObjectValuatorType; + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(BinaryImageToStatisticsLabelMapFilter, + ImageToImageFilter); + + /** + * Set/Get whether the connected components are defined strictly by + * face connectivity or by face+edge+vertex connectivity. Default is + * FullyConnectedOff. For objects that are 1 pixel wide, use + * FullyConnectedOn. + */ + itkSetMacro(FullyConnected, bool); + itkGetConstReferenceMacro(FullyConnected, bool); + itkBooleanMacro(FullyConnected); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>)); + /** End concept checking */ +#endif + + /** + * Set/Get the value used as "background" in the output image. + * Defaults to NumericTraits<PixelType>::NonpositiveMin(). + */ + itkSetMacro(OutputBackgroundValue, OutputImagePixelType); + itkGetConstMacro(OutputBackgroundValue, OutputImagePixelType); + + /** + * Set/Get the value used as "foreground" in the output image. + * Defaults to NumericTraits<PixelType>::max(). + */ + itkSetMacro(InputForegroundValue, InputImagePixelType); + itkGetConstMacro(InputForegroundValue, InputImagePixelType); + + /** + * Set/Get whether the maximum Feret diameter should be computed or not. The + * defaut value is false, because of the high computation time required. + */ + itkSetMacro(ComputeFeretDiameter, bool); + itkGetConstReferenceMacro(ComputeFeretDiameter, bool); + itkBooleanMacro(ComputeFeretDiameter); + + /** + * Set/Get whether the perimeter should be computed or not. The defaut value + * is false, because of the high computation time required. + */ + itkSetMacro(ComputePerimeter, bool); + itkGetConstReferenceMacro(ComputePerimeter, bool); + itkBooleanMacro(ComputePerimeter); + + /** Set the feature image */ + void SetFeatureImage(const TFeatureImage *input) + { + // Process object is not const-correct so the const casting is required. + this->SetNthInput( 1, const_cast<TFeatureImage *>(input) ); + } + + /** Get the feature image */ + const FeatureImageType * GetFeatureImage() + { + return static_cast<const FeatureImageType*>(this->ProcessObject::GetInput(1)); + } + + /** Set the input image */ + void SetInput1(const InputImageType *input) + { + this->SetInput( input ); + } + + /** Set the feature image */ + void SetInput2(const FeatureImageType *input) + { + this->SetFeatureImage( input ); + } + + /** + * Set/Get whether the histogram should be attached to the label object or not. + * This option defaults to `true`, but because the histogram may take a lot of memory + * compared to the other attributes, this option is useful to reduce the memory usage + * when the histogram is not required. + */ + itkSetMacro(ComputeHistogram, bool); + itkGetConstReferenceMacro(ComputeHistogram, bool); + itkBooleanMacro(ComputeHistogram); + + /** + * Set/Get the number of bins in the histogram. Note that the histogram is used + * to compute the median value, and that this option may have an effect on the + * value of the median. + */ + itkSetMacro(NumberOfBins, unsigned int); + itkGetConstReferenceMacro(NumberOfBins, unsigned int); + + +protected: + BinaryImageToStatisticsLabelMapFilter(); + ~BinaryImageToStatisticsLabelMapFilter() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + + /** BinaryImageToStatisticsLabelMapFilter needs the entire input be + * available. Thus, it needs to provide an implementation of + * GenerateInputRequestedRegion(). */ + void GenerateInputRequestedRegion(); + + /** BinaryImageToStatisticsLabelMapFilter will produce the entire output. */ + void EnlargeOutputRequestedRegion(DataObject *itkNotUsed(output)); + + /** Single-threaded version of GenerateData. This filter delegates + * to GrayscaleGeodesicErodeImageFilter. */ + void GenerateData(); + + +private: + BinaryImageToStatisticsLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + bool m_FullyConnected; + OutputImagePixelType m_OutputBackgroundValue; + InputImagePixelType m_InputForegroundValue; + bool m_ComputeFeretDiameter; + bool m_ComputePerimeter; + unsigned int m_NumberOfBins; + bool m_ComputeHistogram; + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkBinaryImageToStatisticsLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkBinaryImageToStatisticsLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkBinaryImageToStatisticsLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..fc95eb047c8814a519116544ed2570f37449399a --- /dev/null +++ b/Utilities/ITK/Code/Review/itkBinaryImageToStatisticsLabelMapFilter.txx @@ -0,0 +1,120 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkBinaryImageToStatisticsLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-07 08:27:57 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkBinaryImageToStatisticsLabelMapFilter_txx +#define __itkBinaryImageToStatisticsLabelMapFilter_txx + +#include "itkBinaryImageToStatisticsLabelMapFilter.h" +#include "itkProgressAccumulator.h" + + +namespace itk { + +template<class TInputImage, class TFeatureImage, class TOutputImage> +BinaryImageToStatisticsLabelMapFilter<TInputImage, TFeatureImage, TOutputImage> +::BinaryImageToStatisticsLabelMapFilter() +{ + m_OutputBackgroundValue = NumericTraits<OutputImagePixelType>::NonpositiveMin(); + m_InputForegroundValue = NumericTraits<OutputImagePixelType>::max(); + m_FullyConnected = false; + m_ComputeFeretDiameter = false; + m_ComputePerimeter = false; + m_NumberOfBins = 128; + m_ComputeHistogram = true; + this->SetNumberOfRequiredInputs(2); +} + +template<class TInputImage, class TFeatureImage, class TOutputImage> +void +BinaryImageToStatisticsLabelMapFilter<TInputImage, TFeatureImage, TOutputImage> +::GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // We need all the input. + InputImagePointer input = const_cast<InputImageType *>(this->GetInput()); + if( input ) + { + input->SetRequestedRegion( input->GetLargestPossibleRegion() ); + } +} + + +template<class TInputImage, class TFeatureImage, class TOutputImage> +void +BinaryImageToStatisticsLabelMapFilter<TInputImage, TFeatureImage, TOutputImage> +::EnlargeOutputRequestedRegion(DataObject *) +{ + this->GetOutput() + ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); +} + + +template<class TInputImage, class TFeatureImage, class TOutputImage> +void +BinaryImageToStatisticsLabelMapFilter<TInputImage, TFeatureImage, TOutputImage> +::GenerateData() +{ + // Create a process accumulator for tracking the progress of this minipipeline + ProgressAccumulator::Pointer progress = ProgressAccumulator::New(); + progress->SetMiniPipelineFilter(this); + + // Allocate the output + this->AllocateOutputs(); + + typename LabelizerType::Pointer labelizer = LabelizerType::New(); + labelizer->SetInput( this->GetInput() ); + labelizer->SetInputForegroundValue( m_InputForegroundValue ); + labelizer->SetOutputBackgroundValue( m_OutputBackgroundValue ); + labelizer->SetFullyConnected( m_FullyConnected ); + labelizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(labelizer, .5f); + + typename LabelObjectValuatorType::Pointer valuator = LabelObjectValuatorType::New(); + valuator->SetInput( labelizer->GetOutput() ); + valuator->SetFeatureImage( this->GetFeatureImage() ); + valuator->SetNumberOfThreads( this->GetNumberOfThreads() ); + valuator->SetComputePerimeter( m_ComputePerimeter ); + valuator->SetComputeFeretDiameter( m_ComputeFeretDiameter ); + valuator->SetComputeHistogram( m_ComputeHistogram ); + valuator->SetNumberOfBins( m_NumberOfBins ); + progress->RegisterInternalFilter(valuator, .5f); + + valuator->GraftOutput( this->GetOutput() ); + valuator->Update(); + this->GraftOutput( valuator->GetOutput() ); +} + + +template<class TInputImage, class TFeatureImage, class TOutputImage> +void +BinaryImageToStatisticsLabelMapFilter<TInputImage, TFeatureImage, TOutputImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "FullyConnected: " << m_FullyConnected << std::endl; + os << indent << "OutputBackgroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_OutputBackgroundValue) << std::endl; + os << indent << "InputForegroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_InputForegroundValue) << std::endl; + os << indent << "ComputeFeretDiameter: " << m_ComputeFeretDiameter << std::endl; + os << indent << "ComputePerimeter: " << m_ComputePerimeter << std::endl; + os << indent << "ComputeHistogram: " << m_ComputeHistogram << std::endl; + os << indent << "NumberOfBins: " << m_NumberOfBins << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkBinaryShapeKeepNObjectsImageFilter.h b/Utilities/ITK/Code/Review/itkBinaryShapeKeepNObjectsImageFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..28394052b4306a40e2e823bf5e5bb8c805875c31 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkBinaryShapeKeepNObjectsImageFilter.h @@ -0,0 +1,191 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkBinaryShapeKeepNObjectsImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-08 01:21:22 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkBinaryShapeKeepNObjectsImageFilter_h +#define __itkBinaryShapeKeepNObjectsImageFilter_h + +#include "itkImageToImageFilter.h" +#include "itkShapeLabelObject.h" +#include "itkLabelMap.h" +#include "itkBinaryImageToLabelMapFilter.h" +#include "itkShapeLabelMapFilter.h" +#include "itkShapeKeepNObjectsLabelMapFilter.h" +#include "itkLabelMapToBinaryImageFilter.h" + + +namespace itk { + +/** \class BinaryShapeKeepNObjectsImageFilter + * \brief keep N objects according to their shape attributes + * + * BinaryShapeKeepNObjectsImageFilter keep the N objects in a binary image + * with the highest (or lowest) attribute value. The attributes are the ones + * of the ShapeLabelObject. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \sa ShapeLabelObject, LabelShapeKeepNObjectsImageFilter, BinaryStatisticsKeepNObjectsImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TInputImage> +class ITK_EXPORT BinaryShapeKeepNObjectsImageFilter : + public ImageToImageFilter<TInputImage, TInputImage> +{ +public: + /** Standard class typedefs. */ + typedef BinaryShapeKeepNObjectsImageFilter Self; + typedef ImageToImageFilter<TInputImage, TInputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef TInputImage OutputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::ConstPointer OutputImageConstPointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(ImageDimension, unsigned int, + TInputImage::ImageDimension); + + typedef ShapeLabelObject<unsigned long, itkGetStaticConstMacro(ImageDimension)> LabelObjectType; + typedef LabelMap< LabelObjectType > LabelMapType; + typedef BinaryImageToLabelMapFilter< InputImageType, LabelMapType > LabelizerType; + typedef Image< typename OutputImageType::PixelType, itkGetStaticConstMacro(OutputImageDimension)> + ShapeLabelFilterOutput; + typedef ShapeLabelMapFilter< LabelMapType, ShapeLabelFilterOutput > LabelObjectValuatorType; + typedef typename LabelObjectType::AttributeType AttributeType; + typedef ShapeKeepNObjectsLabelMapFilter< LabelMapType > KeepNObjectsType; + typedef LabelMapToBinaryImageFilter< LabelMapType, OutputImageType > BinarizerType; + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(BinaryShapeKeepNObjectsImageFilter, + ImageToImageFilter); + + /** + * Set/Get whether the connected components are defined strictly by + * face connectivity or by face+edge+vertex connectivity. Default is + * FullyConnectedOff. For objects that are 1 pixel wide, use + * FullyConnectedOn. + */ + itkSetMacro(FullyConnected, bool); + itkGetConstReferenceMacro(FullyConnected, bool); + itkBooleanMacro(FullyConnected); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>)); + /** End concept checking */ +#endif + + /** + * Set/Get the value used as "background" in the output image. + * Defaults to NumericTraits<PixelType>::NonpositiveMin(). + */ + itkSetMacro(BackgroundValue, OutputImagePixelType); + itkGetConstMacro(BackgroundValue, OutputImagePixelType); + + /** + * Set/Get the value used as "foreground" in the output image. + * Defaults to NumericTraits<PixelType>::max(). + */ + itkSetMacro(ForegroundValue, OutputImagePixelType); + itkGetConstMacro(ForegroundValue, OutputImagePixelType); + + /** + * Set/Get the number of objects to keep + */ + itkGetConstMacro(NumberOfObjects, unsigned long); + itkSetMacro(NumberOfObjects, unsigned long); + + /** + * Set/Get the ordering of the objects. By default, the ones with the + * highest value are kept. Turming ReverseOrdering to true make this filter + * keep the objects with the smallest values + */ + itkGetConstMacro( ReverseOrdering, bool ); + itkSetMacro( ReverseOrdering, bool ); + itkBooleanMacro( ReverseOrdering ); + + /** + * Set/Get the attribute to use to select the object to keep. The default + * is "Size". + */ + itkGetConstMacro( Attribute, AttributeType ); + itkSetMacro( Attribute, AttributeType ); + void SetAttribute( const std::string & s ) + { + this->SetAttribute( LabelObjectType::GetAttributeFromName( s ) ); + } + +protected: + BinaryShapeKeepNObjectsImageFilter(); + ~BinaryShapeKeepNObjectsImageFilter() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + + /** BinaryShapeKeepNObjectsImageFilter needs the entire input be + * available. Thus, it needs to provide an implementation of + * GenerateInputRequestedRegion(). */ + void GenerateInputRequestedRegion(); + + /** BinaryShapeKeepNObjectsImageFilter will produce the entire output. */ + void EnlargeOutputRequestedRegion(DataObject *itkNotUsed(output)); + + /** Single-threaded version of GenerateData. This filter delegates + * to GrayscaleGeodesicErodeImageFilter. */ + void GenerateData(); + +private: + BinaryShapeKeepNObjectsImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + bool m_FullyConnected; + OutputImagePixelType m_BackgroundValue; + OutputImagePixelType m_ForegroundValue; + unsigned long m_NumberOfObjects; + bool m_ReverseOrdering; + AttributeType m_Attribute; +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkBinaryShapeKeepNObjectsImageFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkBinaryShapeKeepNObjectsImageFilter.txx b/Utilities/ITK/Code/Review/itkBinaryShapeKeepNObjectsImageFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..4d9d051aab3e4520d79a644477953212c009018f --- /dev/null +++ b/Utilities/ITK/Code/Review/itkBinaryShapeKeepNObjectsImageFilter.txx @@ -0,0 +1,135 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkBinaryShapeKeepNObjectsImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-07 11:28:01 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkBinaryShapeKeepNObjectsImageFilter_txx +#define __itkBinaryShapeKeepNObjectsImageFilter_txx + +#include "itkBinaryShapeKeepNObjectsImageFilter.h" +#include "itkProgressAccumulator.h" + + +namespace itk { + +template<class TInputImage> +BinaryShapeKeepNObjectsImageFilter<TInputImage> +::BinaryShapeKeepNObjectsImageFilter() +{ + m_BackgroundValue = NumericTraits<OutputImagePixelType>::NonpositiveMin(); + m_ForegroundValue = NumericTraits<OutputImagePixelType>::max(); + m_FullyConnected = false; + m_ReverseOrdering = false; + m_Attribute = LabelObjectType::SIZE; +} + +template<class TInputImage> +void +BinaryShapeKeepNObjectsImageFilter<TInputImage> +::GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // We need all the input. + InputImagePointer input = const_cast<InputImageType *>(this->GetInput()); + if( input ) + { + input->SetRequestedRegion( input->GetLargestPossibleRegion() ); + } +} + + +template<class TInputImage> +void +BinaryShapeKeepNObjectsImageFilter<TInputImage> +::EnlargeOutputRequestedRegion(DataObject *) +{ + this->GetOutput() + ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); +} + + +template<class TInputImage> +void +BinaryShapeKeepNObjectsImageFilter<TInputImage> +::GenerateData() +{ + // Create a process accumulator for tracking the progress of this minipipeline + ProgressAccumulator::Pointer progress = ProgressAccumulator::New(); + progress->SetMiniPipelineFilter(this); + + // Allocate the output + this->AllocateOutputs(); + + typename LabelizerType::Pointer labelizer = LabelizerType::New(); + labelizer->SetInput( this->GetInput() ); + labelizer->SetInputForegroundValue( m_ForegroundValue ); + labelizer->SetOutputBackgroundValue( m_BackgroundValue ); + labelizer->SetFullyConnected( m_FullyConnected ); + labelizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(labelizer, .3f); + + typename LabelObjectValuatorType::Pointer valuator = LabelObjectValuatorType::New(); + valuator->SetInput( labelizer->GetOutput() ); + valuator->SetNumberOfThreads( this->GetNumberOfThreads() ); + if( m_Attribute == LabelObjectType::PERIMETER || m_Attribute == LabelObjectType::ROUNDNESS ) + { + valuator->SetComputePerimeter( true ); + } + if( m_Attribute == LabelObjectType::FERET_DIAMETER ) + { + valuator->SetComputeFeretDiameter( true ); + } + progress->RegisterInternalFilter(valuator, .3f); + + typename KeepNObjectsType::Pointer opening = KeepNObjectsType::New(); + opening->SetInput( valuator->GetOutput() ); + opening->SetNumberOfObjects( m_NumberOfObjects ); + opening->SetReverseOrdering( m_ReverseOrdering ); + opening->SetAttribute( m_Attribute ); + opening->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(opening, .2f); + + typename BinarizerType::Pointer binarizer = BinarizerType::New(); + binarizer->SetInput( opening->GetOutput() ); + binarizer->SetForegroundValue( m_ForegroundValue ); + binarizer->SetBackgroundValue( m_BackgroundValue ); + binarizer->SetBackgroundImage( this->GetInput() ); + binarizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(binarizer, .2f); + + binarizer->GraftOutput( this->GetOutput() ); + binarizer->Update(); + this->GraftOutput( binarizer->GetOutput() ); +} + + +template<class TInputImage> +void +BinaryShapeKeepNObjectsImageFilter<TInputImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "FullyConnected: " << m_FullyConnected << std::endl; + os << indent << "BackgroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_BackgroundValue) << std::endl; + os << indent << "ForegroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_ForegroundValue) << std::endl; + os << indent << "NumberOfObjects: " << m_NumberOfObjects << std::endl; + os << indent << "ReverseOrdering: " << m_ReverseOrdering << std::endl; + os << indent << "Attribute: " << LabelObjectType::GetNameFromAttribute(m_Attribute) << " (" << m_Attribute << ")" << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkBinaryShapeOpeningImageFilter.h b/Utilities/ITK/Code/Review/itkBinaryShapeOpeningImageFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..d8749b1807885451f3c3b76af4a49623ea206cb3 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkBinaryShapeOpeningImageFilter.h @@ -0,0 +1,189 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkBinaryShapeOpeningImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-07 11:28:01 $ + Version: $Revision: 1.4 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkBinaryShapeOpeningImageFilter_h +#define __itkBinaryShapeOpeningImageFilter_h + +#include "itkImageToImageFilter.h" +#include "itkShapeLabelObject.h" +#include "itkLabelMap.h" +#include "itkBinaryImageToLabelMapFilter.h" +#include "itkShapeLabelMapFilter.h" +#include "itkShapeOpeningLabelMapFilter.h" +#include "itkLabelMapToBinaryImageFilter.h" + + +namespace itk { + +/** \class BinaryShapeOpeningImageFilter + * \brief Remove objects based on the value of their shape attribute. + * + * The BinaryShapeOpeningImageFilter removes the objects in a binary image + * with an attribute value smaller or greater than a threshold called Lambda. + * The attributes are those of the ShapeLabelObject. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * \sa ShapeLabelObject, LabelShapeOpeningImageFilter, BinaryStatisticsOpeningImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TInputImage> +class ITK_EXPORT BinaryShapeOpeningImageFilter : + public ImageToImageFilter<TInputImage, TInputImage> +{ +public: + /** Standard class typedefs. */ + typedef BinaryShapeOpeningImageFilter Self; + typedef ImageToImageFilter<TInputImage, TInputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef TInputImage OutputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::ConstPointer OutputImageConstPointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, TInputImage::ImageDimension); + itkStaticConstMacro(ImageDimension, unsigned int, TInputImage::ImageDimension); + + typedef ShapeLabelObject<unsigned long, itkGetStaticConstMacro(ImageDimension)> LabelObjectType; + typedef LabelMap< LabelObjectType > LabelMapType; + typedef BinaryImageToLabelMapFilter< InputImageType, LabelMapType > LabelizerType; + typedef Image< typename OutputImageType::PixelType, itkGetStaticConstMacro(OutputImageDimension)> + ShapeLabelFilterOutput; + typedef ShapeLabelMapFilter< LabelMapType,ShapeLabelFilterOutput > LabelObjectValuatorType; + typedef typename LabelObjectType::AttributeType AttributeType; + typedef ShapeOpeningLabelMapFilter< LabelMapType > OpeningType; + typedef LabelMapToBinaryImageFilter< LabelMapType, OutputImageType > BinarizerType; + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(BinaryShapeOpeningImageFilter, ImageToImageFilter ); + + /** + * Set/Get whether the connected components are defined strictly by + * face connectivity or by face+edge+vertex connectivity. + * Default is FullyConnectedOff. + * For objects that are 1 pixel wide, use FullyConnectedOn. + */ + itkSetMacro( FullyConnected, bool ); + itkGetConstReferenceMacro( FullyConnected, bool ); + itkBooleanMacro( FullyConnected ); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>)); + /** End concept checking */ +#endif + + /** + * Set/Get the value used as "background" in the output image. + * Defaults to NumericTraits<PixelType>::NonpositiveMin(). + */ + itkSetMacro( BackgroundValue, OutputImagePixelType ); + itkGetConstMacro( BackgroundValue, OutputImagePixelType ); + + /** + * Set/Get the value used as "foreground" in the output image. + * Defaults to NumericTraits<PixelType>::max(). + */ + itkSetMacro( ForegroundValue, OutputImagePixelType ); + itkGetConstMacro( ForegroundValue, OutputImagePixelType); + + /** + * Set/Get the threshold used to keep or remove the objects. + */ + itkGetConstMacro( Lambda, double ); + itkSetMacro( Lambda, double ); + + /** + * Set/Get the ordering of the objects. By default, the objects with + * an attribute value smaller than Lamba are removed. Turning ReverseOrdering + * to true make this filter remove objects with an attribute value greater + * than Lambda instead. + */ + itkGetConstMacro( ReverseOrdering, bool ); + itkSetMacro( ReverseOrdering, bool ); + itkBooleanMacro( ReverseOrdering ); + + /** + * Set/Get the attribute to use to select the object to remove. + * Default is "Size". + */ + itkGetConstMacro( Attribute, AttributeType ); + itkSetMacro( Attribute, AttributeType ); + void SetAttribute( const std::string & s ) + { + this->SetAttribute( LabelObjectType::GetAttributeFromName( s ) ); + } + + +protected: + BinaryShapeOpeningImageFilter(); + ~BinaryShapeOpeningImageFilter() {} + void PrintSelf( std::ostream& os, Indent indent ) const; + + /** BinaryShapeOpeningImageFilter needs the entire input to be available. + * Thus, it needs to provide an implementation of GenerateInputRequestedRegion(). */ + void GenerateInputRequestedRegion(); + + /** BinaryShapeOpeningImageFilter will produce the entire output. */ + void EnlargeOutputRequestedRegion( DataObject *itkNotUsed(output) ); + + /** Single-threaded version of GenerateData. This filter delegates + * to GrayscaleGeodesicErodeImageFilter. */ + void GenerateData(); + + +private: + BinaryShapeOpeningImageFilter( const Self& ); //purposely not implemented + void operator=( const Self& ); //purposely not implemented + + bool m_FullyConnected; + OutputImagePixelType m_BackgroundValue; + OutputImagePixelType m_ForegroundValue; + double m_Lambda; + bool m_ReverseOrdering; + AttributeType m_Attribute; +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkBinaryShapeOpeningImageFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkBinaryShapeOpeningImageFilter.txx b/Utilities/ITK/Code/Review/itkBinaryShapeOpeningImageFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..6650d03e7af01b7fcbfb0fa984df11ff0a5fb1cb --- /dev/null +++ b/Utilities/ITK/Code/Review/itkBinaryShapeOpeningImageFilter.txx @@ -0,0 +1,136 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkBinaryShapeOpeningImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-07 11:28:02 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkBinaryShapeOpeningImageFilter_txx +#define __itkBinaryShapeOpeningImageFilter_txx + +#include "itkBinaryShapeOpeningImageFilter.h" +#include "itkProgressAccumulator.h" + + +namespace itk { + +template<class TInputImage> +BinaryShapeOpeningImageFilter<TInputImage> +::BinaryShapeOpeningImageFilter() +{ + m_BackgroundValue = NumericTraits<OutputImagePixelType>::NonpositiveMin(); + m_ForegroundValue = NumericTraits<OutputImagePixelType>::max(); + m_FullyConnected = false; + m_ReverseOrdering = false; + m_Lambda = 0.0; + m_Attribute = LabelObjectType::SIZE; +} + +template<class TInputImage> +void +BinaryShapeOpeningImageFilter<TInputImage> +::GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // We need all the input. + InputImagePointer input = const_cast<InputImageType *>( this->GetInput() ); + if( input ) + { + input->SetRequestedRegion( input->GetLargestPossibleRegion() ); + } +} + + +template<class TInputImage> +void +BinaryShapeOpeningImageFilter<TInputImage> +::EnlargeOutputRequestedRegion(DataObject *) +{ + this->GetOutput() + ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); +} + + +template<class TInputImage> +void +BinaryShapeOpeningImageFilter<TInputImage> +::GenerateData() +{ + // Create a process accumulator for tracking the progress of this minipipeline + ProgressAccumulator::Pointer progress = ProgressAccumulator::New(); + progress->SetMiniPipelineFilter( this ); + + // Allocate the output + this->AllocateOutputs(); + + typename LabelizerType::Pointer labelizer = LabelizerType::New(); + labelizer->SetInput( this->GetInput() ); + labelizer->SetInputForegroundValue( m_ForegroundValue ); + labelizer->SetOutputBackgroundValue( m_BackgroundValue ); + labelizer->SetFullyConnected( m_FullyConnected ); + labelizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(labelizer, .3f); + + typename LabelObjectValuatorType::Pointer valuator = LabelObjectValuatorType::New(); + valuator->SetInput( labelizer->GetOutput() ); + valuator->SetNumberOfThreads( this->GetNumberOfThreads() ); + if( m_Attribute == LabelObjectType::PERIMETER || m_Attribute == LabelObjectType::ROUNDNESS ) + { + valuator->SetComputePerimeter( true ); + } + if( m_Attribute == LabelObjectType::FERET_DIAMETER ) + { + valuator->SetComputeFeretDiameter( true ); + } + progress->RegisterInternalFilter(valuator, .3f); + + typename OpeningType::Pointer opening = OpeningType::New(); + opening->SetInput( valuator->GetOutput() ); + opening->SetLambda( m_Lambda ); + opening->SetReverseOrdering( m_ReverseOrdering ); + opening->SetAttribute( m_Attribute ); + opening->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(opening, .2f); + + typename BinarizerType::Pointer binarizer = BinarizerType::New(); + binarizer->SetInput( opening->GetOutput() ); + binarizer->SetForegroundValue( m_ForegroundValue ); + binarizer->SetBackgroundValue( m_BackgroundValue ); + binarizer->SetBackgroundImage( this->GetInput() ); + binarizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(binarizer, .2f); + + binarizer->GraftOutput( this->GetOutput() ); + binarizer->Update(); + this->GraftOutput( binarizer->GetOutput() ); +} + + +template<class TInputImage> +void +BinaryShapeOpeningImageFilter<TInputImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "FullyConnected: " << m_FullyConnected << std::endl; + os << indent << "BackgroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_BackgroundValue) << std::endl; + os << indent << "ForegroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_ForegroundValue) << std::endl; + os << indent << "Lambda: " << m_Lambda << std::endl; + os << indent << "ReverseOrdering: " << m_ReverseOrdering << std::endl; + os << indent << "Attribute: " << LabelObjectType::GetNameFromAttribute(m_Attribute) << " (" << m_Attribute << ")" << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkBinaryStatisticsKeepNObjectsImageFilter.h b/Utilities/ITK/Code/Review/itkBinaryStatisticsKeepNObjectsImageFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..3d11e7753abadc9c34d75583ef8038b500a3c80f --- /dev/null +++ b/Utilities/ITK/Code/Review/itkBinaryStatisticsKeepNObjectsImageFilter.h @@ -0,0 +1,219 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkBinaryStatisticsKeepNObjectsImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-08 01:21:22 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkBinaryStatisticsKeepNObjectsImageFilter_h +#define __itkBinaryStatisticsKeepNObjectsImageFilter_h + +#include "itkImageToImageFilter.h" +#include "itkStatisticsLabelObject.h" +#include "itkLabelMap.h" +#include "itkBinaryImageToLabelMapFilter.h" +#include "itkStatisticsLabelMapFilter.h" +#include "itkStatisticsKeepNObjectsLabelMapFilter.h" +#include "itkLabelMapToBinaryImageFilter.h" + + +namespace itk { + +/** \class BinaryStatisticsKeepNObjectsImageFilter + * \brief keep N objects according to their statistics attributes + * + * BinaryStatisticsKeepNObjectsImageFilter keep the N objects in a binary image + * with the highest (or lowest) attribute value. The attributes are the ones + * of the StatisticsLabelObject. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \sa StatisticsLabelObject, LabelStatisticsKeepNObjectsImageFilter, BinaryShapeKeepNObjectsImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TInputImage, class TFeatureImage> +class ITK_EXPORT BinaryStatisticsKeepNObjectsImageFilter : + public ImageToImageFilter<TInputImage, TInputImage> +{ +public: + /** Standard class typedefs. */ + typedef BinaryStatisticsKeepNObjectsImageFilter Self; + typedef ImageToImageFilter<TInputImage, TInputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef TInputImage OutputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::ConstPointer OutputImageConstPointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + + typedef TFeatureImage FeatureImageType; + typedef typename FeatureImageType::Pointer FeatureImagePointer; + typedef typename FeatureImageType::ConstPointer FeatureImageConstPointer; + typedef typename FeatureImageType::PixelType FeatureImagePixelType; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(ImageDimension, unsigned int, + TInputImage::ImageDimension); + + typedef StatisticsLabelObject<unsigned long, itkGetStaticConstMacro(ImageDimension)> LabelObjectType; + typedef LabelMap< LabelObjectType > LabelMapType; + typedef BinaryImageToLabelMapFilter< InputImageType, LabelMapType > LabelizerType; + typedef StatisticsLabelMapFilter< LabelMapType, TFeatureImage > LabelObjectValuatorType; + typedef typename LabelObjectType::AttributeType AttributeType; + typedef StatisticsKeepNObjectsLabelMapFilter< LabelMapType > KeepNObjectsType; + typedef LabelMapToBinaryImageFilter< LabelMapType, OutputImageType > BinarizerType; + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(BinaryStatisticsKeepNObjectsImageFilter, + ImageToImageFilter); + + /** + * Set/Get whether the connected components are defined strictly by + * face connectivity or by face+edge+vertex connectivity. Default is + * FullyConnectedOff. For objects that are 1 pixel wide, use + * FullyConnectedOn. + */ + itkSetMacro(FullyConnected, bool); + itkGetConstReferenceMacro(FullyConnected, bool); + itkBooleanMacro(FullyConnected); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>)); + /** End concept checking */ +#endif + + /** + * Set/Get the value used as "background" in the output image. + * Defaults to NumericTraits<PixelType>::NonpositiveMin(). + */ + itkSetMacro(BackgroundValue, OutputImagePixelType); + itkGetConstMacro(BackgroundValue, OutputImagePixelType); + + /** + * Set/Get the value used as "foreground" in the output image. + * Defaults to NumericTraits<PixelType>::max(). + */ + itkSetMacro(ForegroundValue, OutputImagePixelType); + itkGetConstMacro(ForegroundValue, OutputImagePixelType); + + /** + * Set/Get the number of objects to keep + */ + itkGetConstMacro(NumberOfObjects, unsigned long); + itkSetMacro(NumberOfObjects, unsigned long); + + /** + * Set/Get the ordering of the objects. By default, the ones with the + * highest value are kept. Turming ReverseOrdering to true make this filter + * keep the objects with the smallest values + */ + itkGetConstMacro( ReverseOrdering, bool ); + itkSetMacro( ReverseOrdering, bool ); + itkBooleanMacro( ReverseOrdering ); + + /** + * Set/Get the attribute to use to select the object to keep. The default + * is "Mean". + */ + itkGetConstMacro( Attribute, AttributeType ); + itkSetMacro( Attribute, AttributeType ); + void SetAttribute( const std::string & s ) + { + this->SetAttribute( LabelObjectType::GetAttributeFromName( s ) ); + } + + /** Set the feature image */ + void SetFeatureImage(const TFeatureImage *input) + { + // Process object is not const-correct so the const casting is required. + this->SetNthInput( 1, const_cast<TFeatureImage *>(input) ); + } + + /** Get the feature image */ + const FeatureImageType * GetFeatureImage() + { + return static_cast<const FeatureImageType*>(this->ProcessObject::GetInput(1)); + } + + /** Set the input image */ + void SetInput1(const InputImageType *input) + { + this->SetInput( input ); + } + + /** Set the feature image */ + void SetInput2(const FeatureImageType *input) + { + this->SetFeatureImage( input ); + } + +protected: + BinaryStatisticsKeepNObjectsImageFilter(); + ~BinaryStatisticsKeepNObjectsImageFilter() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + + /** BinaryStatisticsKeepNObjectsImageFilter needs the entire input be + * available. Thus, it needs to provide an implementation of + * GenerateInputRequestedRegion(). */ + void GenerateInputRequestedRegion(); + + /** BinaryStatisticsKeepNObjectsImageFilter will produce the entire output. */ + void EnlargeOutputRequestedRegion(DataObject *itkNotUsed(output)); + + /** Single-threaded version of GenerateData. This filter delegates + * to GrayscaleGeodesicErodeImageFilter. */ + void GenerateData(); + +private: + BinaryStatisticsKeepNObjectsImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + bool m_FullyConnected; + OutputImagePixelType m_BackgroundValue; + OutputImagePixelType m_ForegroundValue; + unsigned long m_NumberOfObjects; + bool m_ReverseOrdering; + AttributeType m_Attribute; +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkBinaryStatisticsKeepNObjectsImageFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkBinaryStatisticsKeepNObjectsImageFilter.txx b/Utilities/ITK/Code/Review/itkBinaryStatisticsKeepNObjectsImageFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..f4d9bb7e9d786ae325b0fd822105948f73a77563 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkBinaryStatisticsKeepNObjectsImageFilter.txx @@ -0,0 +1,138 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkBinaryStatisticsKeepNObjectsImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-07 12:12:34 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkBinaryStatisticsKeepNObjectsImageFilter_txx +#define __itkBinaryStatisticsKeepNObjectsImageFilter_txx + +#include "itkBinaryStatisticsKeepNObjectsImageFilter.h" +#include "itkProgressAccumulator.h" + + +namespace itk { + +template<class TInputImage, class TFeatureImage> +BinaryStatisticsKeepNObjectsImageFilter<TInputImage, TFeatureImage> +::BinaryStatisticsKeepNObjectsImageFilter() +{ + m_BackgroundValue = NumericTraits<OutputImagePixelType>::NonpositiveMin(); + m_ForegroundValue = NumericTraits<OutputImagePixelType>::max(); + m_FullyConnected = false; + m_ReverseOrdering = false; + m_Attribute = LabelObjectType::MEAN; + this->SetNumberOfRequiredInputs(2); +} + +template<class TInputImage, class TFeatureImage> +void +BinaryStatisticsKeepNObjectsImageFilter<TInputImage, TFeatureImage> +::GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // We need all the input. + InputImagePointer input = const_cast<InputImageType *>(this->GetInput()); + if( input ) + { + input->SetRequestedRegion( input->GetLargestPossibleRegion() ); + } +} + + +template<class TInputImage, class TFeatureImage> +void +BinaryStatisticsKeepNObjectsImageFilter<TInputImage, TFeatureImage> +::EnlargeOutputRequestedRegion(DataObject *) +{ + this->GetOutput() + ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); +} + + +template<class TInputImage, class TFeatureImage> +void +BinaryStatisticsKeepNObjectsImageFilter<TInputImage, TFeatureImage> +::GenerateData() +{ + // Create a process accumulator for tracking the progress of this minipipeline + ProgressAccumulator::Pointer progress = ProgressAccumulator::New(); + progress->SetMiniPipelineFilter(this); + + // Allocate the output + this->AllocateOutputs(); + + typename LabelizerType::Pointer labelizer = LabelizerType::New(); + labelizer->SetInput( this->GetInput() ); + labelizer->SetInputForegroundValue( m_ForegroundValue ); + labelizer->SetOutputBackgroundValue( m_BackgroundValue ); + labelizer->SetFullyConnected( m_FullyConnected ); + labelizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(labelizer, .3f); + + typename LabelObjectValuatorType::Pointer valuator = LabelObjectValuatorType::New(); + valuator->SetInput( labelizer->GetOutput() ); + valuator->SetFeatureImage( this->GetFeatureImage() ); + valuator->SetNumberOfThreads( this->GetNumberOfThreads() ); + valuator->SetComputeHistogram( false ); + if( m_Attribute == LabelObjectType::PERIMETER || m_Attribute == LabelObjectType::ROUNDNESS ) + { + valuator->SetComputePerimeter( true ); + } + if( m_Attribute == LabelObjectType::FERET_DIAMETER ) + { + valuator->SetComputeFeretDiameter( true ); + } + progress->RegisterInternalFilter(valuator, .3f); + + typename KeepNObjectsType::Pointer opening = KeepNObjectsType::New(); + opening->SetInput( valuator->GetOutput() ); + opening->SetNumberOfObjects( m_NumberOfObjects ); + opening->SetReverseOrdering( m_ReverseOrdering ); + opening->SetAttribute( m_Attribute ); + opening->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(opening, .2f); + + typename BinarizerType::Pointer binarizer = BinarizerType::New(); + binarizer->SetInput( opening->GetOutput() ); + binarizer->SetForegroundValue( m_ForegroundValue ); + binarizer->SetBackgroundValue( m_BackgroundValue ); + binarizer->SetBackgroundImage( this->GetInput() ); + binarizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(binarizer, .2f); + + binarizer->GraftOutput( this->GetOutput() ); + binarizer->Update(); + this->GraftOutput( binarizer->GetOutput() ); +} + + +template<class TInputImage, class TFeatureImage> +void +BinaryStatisticsKeepNObjectsImageFilter<TInputImage, TFeatureImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "FullyConnected: " << m_FullyConnected << std::endl; + os << indent << "BackgroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_BackgroundValue) << std::endl; + os << indent << "ForegroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_ForegroundValue) << std::endl; + os << indent << "NumberOfObjects: " << m_NumberOfObjects << std::endl; + os << indent << "ReverseOrdering: " << m_ReverseOrdering << std::endl; + os << indent << "Attribute: " << LabelObjectType::GetNameFromAttribute(m_Attribute) << " (" << m_Attribute << ")" << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkBinaryStatisticsOpeningImageFilter.h b/Utilities/ITK/Code/Review/itkBinaryStatisticsOpeningImageFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..088e11373ace84d2e883b6ce98835e900502aa85 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkBinaryStatisticsOpeningImageFilter.h @@ -0,0 +1,217 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkBinaryStatisticsOpeningImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-15 17:10:50 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkBinaryStatisticsOpeningImageFilter_h +#define __itkBinaryStatisticsOpeningImageFilter_h + +#include "itkImageToImageFilter.h" +#include "itkStatisticsLabelObject.h" +#include "itkLabelMap.h" +#include "itkBinaryImageToLabelMapFilter.h" +#include "itkStatisticsLabelMapFilter.h" +#include "itkStatisticsOpeningLabelMapFilter.h" +#include "itkLabelMapToBinaryImageFilter.h" + + +namespace itk { + +/** \class BinaryStatisticsOpeningImageFilter + * \brief Remove objects based on the value of their Statistics attribute. + * + * The BinaryStatisticsOpeningImageFilter removes the objects in a binary image + * with an attribute value smaller or greater than a threshold called Lambda. + * The attributes are those of the StatisticsLabelObject. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * \sa StatisticsLabelObject, LabelStatisticsOpeningImageFilter, BinaryStatisticsOpeningImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TInputImage, class TFeatureImage> +class ITK_EXPORT BinaryStatisticsOpeningImageFilter : + public ImageToImageFilter<TInputImage, TInputImage> +{ +public: + /** Standard class typedefs. */ + typedef BinaryStatisticsOpeningImageFilter Self; + typedef ImageToImageFilter<TInputImage, TInputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef TInputImage OutputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::ConstPointer OutputImageConstPointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + + typedef TFeatureImage FeatureImageType; + typedef typename FeatureImageType::Pointer FeatureImagePointer; + typedef typename FeatureImageType::ConstPointer FeatureImageConstPointer; + typedef typename FeatureImageType::PixelType FeatureImagePixelType; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, TInputImage::ImageDimension); + itkStaticConstMacro(ImageDimension, unsigned int, TInputImage::ImageDimension); + + typedef StatisticsLabelObject<unsigned long, itkGetStaticConstMacro(ImageDimension)> LabelObjectType; + typedef LabelMap< LabelObjectType > LabelMapType; + typedef BinaryImageToLabelMapFilter< InputImageType, LabelMapType > LabelizerType; + typedef StatisticsLabelMapFilter< LabelMapType, FeatureImageType > LabelObjectValuatorType; + typedef typename LabelObjectType::AttributeType AttributeType; + typedef StatisticsOpeningLabelMapFilter< LabelMapType > OpeningType; + typedef LabelMapToBinaryImageFilter< LabelMapType, OutputImageType > BinarizerType; + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(BinaryStatisticsOpeningImageFilter, ImageToImageFilter ); + + /** + * Set/Get whether the connected components are defined strictly by + * face connectivity or by face+edge+vertex connectivity. + * Default is FullyConnectedOff. + * For objects that are 1 pixel wide, use FullyConnectedOn. + */ + itkSetMacro( FullyConnected, bool ); + itkGetConstReferenceMacro( FullyConnected, bool ); + itkBooleanMacro( FullyConnected ); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>)); + /** End concept checking */ +#endif + + /** + * Set/Get the value used as "background" in the output image. + * Defaults to NumericTraits<PixelType>::NonpositiveMin(). + */ + itkSetMacro( BackgroundValue, OutputImagePixelType ); + itkGetConstMacro( BackgroundValue, OutputImagePixelType ); + + /** + * Set/Get the value used as "foreground" in the output image. + * Defaults to NumericTraits<PixelType>::max(). + */ + itkSetMacro( ForegroundValue, OutputImagePixelType ); + itkGetConstMacro( ForegroundValue, OutputImagePixelType); + + /** + * Set/Get the threshold used to keep or remove the objects. + */ + itkGetConstMacro( Lambda, double ); + itkSetMacro( Lambda, double ); + + /** + * Set/Get the ordering of the objects. By default, the objects with + * an attribute value smaller than Lamba are removed. Turning ReverseOrdering + * to true make this filter remove objects with an attribute value greater + * than Lambda instead. + */ + itkGetConstMacro( ReverseOrdering, bool ); + itkSetMacro( ReverseOrdering, bool ); + itkBooleanMacro( ReverseOrdering ); + + /** + * Set/Get the attribute to use to select the object to remove. + * Default is "Size". + */ + itkGetConstMacro( Attribute, AttributeType ); + itkSetMacro( Attribute, AttributeType ); + void SetAttribute( const std::string & s ) + { + this->SetAttribute( LabelObjectType::GetAttributeFromName( s ) ); + } + + /** Set the feature image */ + void SetFeatureImage(const TFeatureImage *input) + { + // Process object is not const-correct so the const casting is required. + this->SetNthInput( 1, const_cast<TFeatureImage *>(input) ); + } + + /** Get the feature image */ + const FeatureImageType * GetFeatureImage() + { + return static_cast<const FeatureImageType*>(this->ProcessObject::GetInput(1)); + } + + /** Set the input image */ + void SetInput1(const InputImageType *input) + { + this->SetInput( input ); + } + + /** Set the feature image */ + void SetInput2(const FeatureImageType *input) + { + this->SetFeatureImage( input ); + } + + +protected: + BinaryStatisticsOpeningImageFilter(); + ~BinaryStatisticsOpeningImageFilter() {} + void PrintSelf( std::ostream& os, Indent indent ) const; + + /** BinaryStatisticsOpeningImageFilter needs the entire input to be available. + * Thus, it needs to provide an implementation of GenerateInputRequestedRegion(). */ + void GenerateInputRequestedRegion(); + + /** BinaryStatisticsOpeningImageFilter will produce the entire output. */ + void EnlargeOutputRequestedRegion( DataObject *itkNotUsed(output) ); + + /** Single-threaded version of GenerateData. This filter delegates + * to GrayscaleGeodesicErodeImageFilter. */ + void GenerateData(); + + +private: + BinaryStatisticsOpeningImageFilter( const Self& ); //purposely not implemented + void operator=( const Self& ); //purposely not implemented + + bool m_FullyConnected; + OutputImagePixelType m_BackgroundValue; + OutputImagePixelType m_ForegroundValue; + double m_Lambda; + bool m_ReverseOrdering; + AttributeType m_Attribute; +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkBinaryStatisticsOpeningImageFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkBinaryStatisticsOpeningImageFilter.txx b/Utilities/ITK/Code/Review/itkBinaryStatisticsOpeningImageFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..eda06c21baf8512ca2c8385fb3977b055e610d90 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkBinaryStatisticsOpeningImageFilter.txx @@ -0,0 +1,139 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkBinaryStatisticsOpeningImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-07 11:28:02 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkBinaryStatisticsOpeningImageFilter_txx +#define __itkBinaryStatisticsOpeningImageFilter_txx + +#include "itkBinaryStatisticsOpeningImageFilter.h" +#include "itkProgressAccumulator.h" + + +namespace itk { + +template<class TInputImage, class TFeatureImage> +BinaryStatisticsOpeningImageFilter<TInputImage, TFeatureImage> +::BinaryStatisticsOpeningImageFilter() +{ + m_BackgroundValue = NumericTraits<OutputImagePixelType>::NonpositiveMin(); + m_ForegroundValue = NumericTraits<OutputImagePixelType>::max(); + m_FullyConnected = false; + m_ReverseOrdering = false; + m_Lambda = 0.0; + m_Attribute = LabelObjectType::MEAN; + this->SetNumberOfRequiredInputs(2); +} + +template<class TInputImage, class TFeatureImage> +void +BinaryStatisticsOpeningImageFilter<TInputImage, TFeatureImage> +::GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // We need all the input. + InputImagePointer input = const_cast<InputImageType *>( this->GetInput() ); + if( input ) + { + input->SetRequestedRegion( input->GetLargestPossibleRegion() ); + } +} + + +template<class TInputImage, class TFeatureImage> +void +BinaryStatisticsOpeningImageFilter<TInputImage, TFeatureImage> +::EnlargeOutputRequestedRegion(DataObject *) +{ + this->GetOutput() + ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); +} + + +template<class TInputImage, class TFeatureImage> +void +BinaryStatisticsOpeningImageFilter<TInputImage, TFeatureImage> +::GenerateData() +{ + // Create a process accumulator for tracking the progress of this minipipeline + ProgressAccumulator::Pointer progress = ProgressAccumulator::New(); + progress->SetMiniPipelineFilter( this ); + + // Allocate the output + this->AllocateOutputs(); + + typename LabelizerType::Pointer labelizer = LabelizerType::New(); + labelizer->SetInput( this->GetInput() ); + labelizer->SetInputForegroundValue( m_ForegroundValue ); + labelizer->SetOutputBackgroundValue( m_BackgroundValue ); + labelizer->SetFullyConnected( m_FullyConnected ); + labelizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(labelizer, .3f); + + typename LabelObjectValuatorType::Pointer valuator = LabelObjectValuatorType::New(); + valuator->SetInput( labelizer->GetOutput() ); + valuator->SetFeatureImage( this->GetFeatureImage() ); + valuator->SetNumberOfThreads( this->GetNumberOfThreads() ); + valuator->SetComputeHistogram( false ); + if( m_Attribute == LabelObjectType::PERIMETER || m_Attribute == LabelObjectType::ROUNDNESS ) + { + valuator->SetComputePerimeter( true ); + } + if( m_Attribute == LabelObjectType::FERET_DIAMETER ) + { + valuator->SetComputeFeretDiameter( true ); + } + progress->RegisterInternalFilter(valuator, .3f); + + typename OpeningType::Pointer opening = OpeningType::New(); + opening->SetInput( valuator->GetOutput() ); + opening->SetLambda( m_Lambda ); + opening->SetReverseOrdering( m_ReverseOrdering ); + opening->SetAttribute( m_Attribute ); + opening->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(opening, .2f); + + typename BinarizerType::Pointer binarizer = BinarizerType::New(); + binarizer->SetInput( opening->GetOutput() ); + binarizer->SetForegroundValue( m_ForegroundValue ); + binarizer->SetBackgroundValue( m_BackgroundValue ); + binarizer->SetBackgroundImage( this->GetInput() ); + binarizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(binarizer, .2f); + + binarizer->GraftOutput( this->GetOutput() ); + binarizer->Update(); + this->GraftOutput( binarizer->GetOutput() ); +} + + +template<class TInputImage, class TFeatureImage> +void +BinaryStatisticsOpeningImageFilter<TInputImage, TFeatureImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "FullyConnected: " << m_FullyConnected << std::endl; + os << indent << "BackgroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_BackgroundValue) << std::endl; + os << indent << "ForegroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_ForegroundValue) << std::endl; + os << indent << "Lambda: " << m_Lambda << std::endl; + os << indent << "ReverseOrdering: " << m_ReverseOrdering << std::endl; + os << indent << "Attribute: " << LabelObjectType::GetNameFromAttribute(m_Attribute) << " (" << m_Attribute << ")" << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkBoxUtilities.h b/Utilities/ITK/Code/Review/itkBoxUtilities.h index 25ab9673e1e8caeea81db55f1a76329c78feda1b..4ad4cfe78a44147dd11e674e37f04e2daf038ad6 100644 --- a/Utilities/ITK/Code/Review/itkBoxUtilities.h +++ b/Utilities/ITK/Code/Review/itkBoxUtilities.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBoxUtilities.h,v $ Language: C++ - Date: $Date: 2008-09-29 18:36:37 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-07-12 10:52:54 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -200,6 +200,7 @@ BoxMeanCalculatorFunction(const TInputImage * accImage, typedef typename TInputImage::IndexType IndexType; typedef typename TInputImage::PixelType PixelType; typedef typename TInputImage::OffsetType OffsetType; + typedef typename TInputImage::OffsetValueType OffsetValueType; typedef TOutputImage OutputImageType; typedef typename TOutputImage::PixelType OutputPixelType; typedef typename TInputImage::PixelType InputPixelType; @@ -216,7 +217,10 @@ BoxMeanCalculatorFunction(const TInputImage * accImage, // this process is actually slightly asymmetric because we need to // subtract rectangles that are next to our kernel, not overlapping it - SizeType kernelSize, internalRadius, RegionLimit; + SizeType kernelSize; + SizeType internalRadius; + SizeType RegionLimit; + IndexType RegionStart = inputRegion.GetIndex(); for( int i=0; i<TInputImage::ImageDimension; i++ ) { @@ -339,7 +343,10 @@ BoxMeanCalculatorFunction(const TInputImage * accImage, if (UnitCorners[k][j] > 0) { // leading edge - crop it - ThisCorner[j] = vnl_math_min(ThisCorner[j], (long)RegionLimit[j]); + if( ThisCorner[j] > static_cast< OffsetValueType>( RegionLimit[j] ) ) + { + ThisCorner[j] = static_cast< OffsetValueType>( RegionLimit[j] ); + } } else { @@ -381,6 +388,7 @@ BoxSigmaCalculatorFunction(const TInputImage * accImage, typedef typename TInputImage::IndexType IndexType; typedef typename TInputImage::PixelType PixelType; typedef typename TInputImage::OffsetType OffsetType; + typedef typename TInputImage::OffsetValueType OffsetValueType; typedef TOutputImage OutputImageType; typedef typename TOutputImage::PixelType OutputPixelType; typedef typename TInputImage::PixelType InputPixelType; @@ -398,7 +406,9 @@ BoxSigmaCalculatorFunction(const TInputImage * accImage, // this process is actually slightly asymmetric because we need to // subtract rectangles that are next to our kernel, not overlapping it - SizeType kernelSize, internalRadius, RegionLimit; + SizeType kernelSize; + SizeType internalRadius; + SizeType RegionLimit; IndexType RegionStart = inputRegion.GetIndex(); for( int i=0; i<TInputImage::ImageDimension; i++ ) { @@ -526,7 +536,10 @@ BoxSigmaCalculatorFunction(const TInputImage * accImage, if (UnitCorners[k][j] > 0) { // leading edge - crop it - ThisCorner[j] = vnl_math_min(ThisCorner[j], (long)RegionLimit[j]); + if( ThisCorner[j] > static_cast< OffsetValueType >( RegionLimit[j]) ) + { + ThisCorner[j] = static_cast< OffsetValueType>( RegionLimit[j] ); + } } else { diff --git a/Utilities/ITK/Code/Review/itkBresenhamLine.h b/Utilities/ITK/Code/Review/itkBresenhamLine.h index cce0c74966396947cf6128dfff91a29ea2ba91c2..3c00ca539138ca2b576041c981353738f07e1965 100644 --- a/Utilities/ITK/Code/Review/itkBresenhamLine.h +++ b/Utilities/ITK/Code/Review/itkBresenhamLine.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBresenhamLine.h,v $ Language: C++ - Date: $Date: 2008-08-06 16:49:13 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-06-03 12:48:05 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -46,7 +46,7 @@ public: BresenhamLine(){} ~BresenhamLine(){} - OffsetArray buildLine(LType Direction, unsigned int length); + OffsetArray BuildLine(LType Direction, unsigned int length); }; diff --git a/Utilities/ITK/Code/Review/itkBresenhamLine.txx b/Utilities/ITK/Code/Review/itkBresenhamLine.txx index 212c478a7e8144dda0a08864510d86fea337f625..47ea0b621f987bc00b1ee3c0e9e614523eab687d 100644 --- a/Utilities/ITK/Code/Review/itkBresenhamLine.txx +++ b/Utilities/ITK/Code/Review/itkBresenhamLine.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkBresenhamLine.txx,v $ Language: C++ - Date: $Date: 2008-08-06 16:49:13 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-06-03 12:48:05 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -24,7 +24,7 @@ namespace itk { template<unsigned int VDimension> typename BresenhamLine<VDimension>::OffsetArray BresenhamLine<VDimension> -::buildLine(LType Direction, unsigned int length) +::BuildLine(LType Direction, unsigned int length) { // copied from the line iterator /** Variables that drive the Bresenham-Algorithm */ diff --git a/Utilities/ITK/Code/Review/itkChangeLabelLabelMapFilter.h b/Utilities/ITK/Code/Review/itkChangeLabelLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..e4ceabd05bbc1d8018bfb31f38f71cce5d64c1a2 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkChangeLabelLabelMapFilter.h @@ -0,0 +1,124 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkChangeLabelLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-04 20:25:11 $ + Version: $Revision: 1.5 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkChangeLabelLabelMapFilter_h +#define __itkChangeLabelLabelMapFilter_h + +#include "itkInPlaceLabelMapFilter.h" +#include <map> + +namespace itk { +/** \class ChangeLabelLabelMapFilter + * \brief Replace the label Ids of selected LabelObjects with new label Ids. + * + * This filter takes as input a label map and a list of pairs of Label Ids, to + * produce as output a new label map where the label Ids have been replaced + * according to the pairs in the list. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * \sa ShapeLabelObject, RelabelComponentImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TImage > +class ITK_EXPORT ChangeLabelLabelMapFilter : + public InPlaceLabelMapFilter<TImage> +{ +public: + /** Standard class typedefs. */ + typedef ChangeLabelLabelMapFilter Self; + typedef InPlaceLabelMapFilter<TImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TImage ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::LabelObjectType LabelObjectType; + + /** ImageDimension constants */ + itkStaticConstMacro(ImageDimension, unsigned int, TImage::ImageDimension); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(ChangeLabelLabelMapFilter, InPlaceLabelMapFilter); + + typedef typename std::map< PixelType, PixelType > ChangeMapType; + typedef typename ChangeMapType::const_iterator ChangeMapIterator; + + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ +/* itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>));*/ + /** End concept checking */ +#endif + + /** + */ + void SetChangeMap( const ChangeMapType & changeMap ); + + const ChangeMapType & GetChangeMap() const; + + void SetChange( const PixelType & oldLabel, const PixelType & newLabel ); + + void ClearChangeMap(); + + +protected: + ChangeLabelLabelMapFilter(); + ~ChangeLabelLabelMapFilter() {}; + + void GenerateData(); + + void PrintSelf(std::ostream& os, Indent indent) const; + + ChangeMapType m_MapOfLabelToBeReplaced; + +private: + ChangeLabelLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + void MoveLabelsToTemporaryArray(); + void ChangeBackgroundIfNeeded(); + void RestoreLabelObjectsAndChangeLabels(); + + typedef typename std::deque< typename LabelObjectType::Pointer > VectorType; + + VectorType m_LabelObjectsToBeRelabeled; + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkChangeLabelLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkChangeLabelLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkChangeLabelLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..100a5a9cfb82ef94da7ef8923758fa9c38124e3d --- /dev/null +++ b/Utilities/ITK/Code/Review/itkChangeLabelLabelMapFilter.txx @@ -0,0 +1,239 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkChangeLabelLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-07-20 19:05:50 $ + Version: $Revision: 1.5 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkChangeLabelLabelMapFilter_txx +#define __itkChangeLabelLabelMapFilter_txx + +#include "itkChangeLabelLabelMapFilter.h" +#include "itkProgressReporter.h" +#include <deque> + + +namespace itk { + +template <class TImage> +ChangeLabelLabelMapFilter<TImage> +::ChangeLabelLabelMapFilter() +{ +} + +template <class TImage> +void +ChangeLabelLabelMapFilter<TImage> +::SetChangeMap( const ChangeMapType & changeMap ) +{ + if( m_MapOfLabelToBeReplaced != changeMap ) + { + m_MapOfLabelToBeReplaced = changeMap; + this->Modified(); + } +} + +template <class TImage> +const typename ChangeLabelLabelMapFilter<TImage>::ChangeMapType & +ChangeLabelLabelMapFilter<TImage> +::GetChangeMap() const +{ + return m_MapOfLabelToBeReplaced; +} + +template <class TImage> +void +ChangeLabelLabelMapFilter<TImage> +::SetChange( const PixelType & oldLabel, const PixelType & newLabel ) +{ + if( m_MapOfLabelToBeReplaced.find( oldLabel ) == m_MapOfLabelToBeReplaced.end() || + m_MapOfLabelToBeReplaced[ oldLabel ] != newLabel ) + { + m_MapOfLabelToBeReplaced[ oldLabel ] = newLabel; + this->Modified(); + } +} + +template <class TImage> +void +ChangeLabelLabelMapFilter<TImage> +::ClearChangeMap() +{ + if( !m_MapOfLabelToBeReplaced.empty() ) + { + m_MapOfLabelToBeReplaced.clear(); + this->Modified(); + } +} + +template <class TImage> +void +ChangeLabelLabelMapFilter<TImage> +::GenerateData() +{ + this->MoveLabelsToTemporaryArray(); + this->ChangeBackgroundIfNeeded(); + this->RestoreLabelObjectsAndChangeLabels(); +} + +template <class TImage> +void +ChangeLabelLabelMapFilter<TImage> +::MoveLabelsToTemporaryArray() +{ + // Allocate the output + this->AllocateOutputs(); + + ImageType * output = this->GetOutput(); + + // Report the progress + ProgressReporter progress( this, 0, m_MapOfLabelToBeReplaced.size() ); + + // First remove the ones to change and store them elsewhere to process later + this->m_LabelObjectsToBeRelabeled.clear(); + + ChangeMapIterator pairToReplace = m_MapOfLabelToBeReplaced.begin(); + + while( pairToReplace != m_MapOfLabelToBeReplaced.end() ) + { + const PixelType labelToBeReplaced = pairToReplace->first; + + if( labelToBeReplaced != output->GetBackgroundValue() ) + { + if( output->HasLabel( labelToBeReplaced ) ) + { + this->m_LabelObjectsToBeRelabeled.push_back( output->GetLabelObject( labelToBeReplaced ) ); + output->RemoveLabel( labelToBeReplaced ); + } + } + + progress.CompletedPixel(); + pairToReplace++; + } + +} + +template <class TImage> +void +ChangeLabelLabelMapFilter<TImage> +::ChangeBackgroundIfNeeded() +{ + ImageType * output = this->GetOutput(); + + // Check if the background is among the list of labels to relabel. + ChangeMapIterator backgroundLabelItr = m_MapOfLabelToBeReplaced.find( output->GetBackgroundValue() ); + const bool backgroundLabelMustBeReplaced = ( backgroundLabelItr != m_MapOfLabelToBeReplaced.end() ); + + // Then change the label of the background if needed + if( backgroundLabelMustBeReplaced ) + { + const PixelType newLabelForBackground = m_MapOfLabelToBeReplaced[ output->GetBackgroundValue() ]; + + if( newLabelForBackground != output->GetBackgroundValue() ) + { + if( output->HasLabel( newLabelForBackground ) ) + { + // we must have a background - remove that object + output->RemoveLabel( newLabelForBackground ); + } + output->SetBackgroundValue( newLabelForBackground ); + } + } +} + + +template <class TImage> +void +ChangeLabelLabelMapFilter<TImage> +::RestoreLabelObjectsAndChangeLabels() +{ + ImageType * output = this->GetOutput(); + + // Put the objects back in the map, with the updated label + typedef typename VectorType::iterator LabelObjectIterator; + LabelObjectIterator labelObjectItr = this->m_LabelObjectsToBeRelabeled.begin(); + + ProgressReporter progress( this, 0, 1 ); + + while( labelObjectItr != this->m_LabelObjectsToBeRelabeled.end() ) + { + LabelObjectType * labelObjectSource = *labelObjectItr; + PixelType newLabel = m_MapOfLabelToBeReplaced[ labelObjectSource->GetLabel() ]; + + // Ignore the label if it is the background + if( newLabel != output->GetBackgroundValue() ) + { + + // If the new label already exists in the output, then merge them. + if( output->HasLabel( newLabel ) ) + { + + // Add the content of the label object to the one already there + LabelObjectType * labelObjectDestination = output->GetLabelObject( newLabel ); + + typedef typename LabelObjectType::LineContainerType LineContainerType; + + const LineContainerType & lineContainer = labelObjectSource->GetLineContainer(); + + typename LineContainerType::const_iterator lineItr = lineContainer.begin(); + + while( lineItr != lineContainer.end() ) + { + labelObjectDestination->AddLine( *lineItr ); + ++lineItr; + } + + // be sure to have the lines well organized + labelObjectDestination->Optimize(); + } + else + { + // just put the label object in the label map with the new label + labelObjectSource->SetLabel( newLabel ); + output->AddLabelObject( labelObjectSource ); + } + } + + // go to the next label object + progress.CompletedPixel(); + labelObjectItr++; + } +} + + +template <class TImage> +void +ChangeLabelLabelMapFilter<TImage> +::PrintSelf(std::ostream& os, Indent indent) const +{ + this->Superclass::PrintSelf(os, indent); + + ChangeMapIterator pairToReplace = m_MapOfLabelToBeReplaced.begin(); + + typedef typename NumericTraits< PixelType >::PrintType LabelPrintType; + + os << indent << "Labels to replace: " << std::endl; + while( pairToReplace != m_MapOfLabelToBeReplaced.end() ) + { + const PixelType oldLabel = pairToReplace->first; + const PixelType newLabel = pairToReplace->second; + + os << indent; + os << static_cast< LabelPrintType >( oldLabel ) << " -> "; + os << static_cast< LabelPrintType >( newLabel ) << std::endl; + + ++pairToReplace; + } +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkChangeRegionLabelMapFilter.h b/Utilities/ITK/Code/Review/itkChangeRegionLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..86c4878e01f3b62edb619a00169c24a1c592d55a --- /dev/null +++ b/Utilities/ITK/Code/Review/itkChangeRegionLabelMapFilter.h @@ -0,0 +1,116 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkChangeRegionLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-07-21 22:17:01 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + Portions of this code are covered under the VTK copyright. + See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkChangeRegionLabelMapFilter_h +#define __itkChangeRegionLabelMapFilter_h + +#include "itkInPlaceLabelMapFilter.h" + +namespace itk +{ + +/** \class ChangeRegionLabelMapFilter + * \brief Change the region of a label map. + * + * Change the region of a label map. If the output can't contain some of the objects' lines + * they are truncated or removed. All objects fully outside the output region are removed. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * \sa LabelMapMaskImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template <class TInputImage> +class ITK_EXPORT ChangeRegionLabelMapFilter : public InPlaceLabelMapFilter<TInputImage> +{ +public: + /** Standard class typedefs. */ + typedef ChangeRegionLabelMapFilter Self; + typedef InPlaceLabelMapFilter<TInputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + + /** Run-time type information (and related methods). */ + itkTypeMacro(ChangeRegionLabelMapFilter, InPlaceImageFilter); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Superclass typedefs. */ + typedef typename Superclass::OutputImageType OutputImageType; + typedef typename Superclass::OutputImagePointer OutputImagePointer; + typedef typename Superclass::OutputImageRegionType OutputImageRegionType; + typedef typename Superclass::OutputImagePixelType OutputImagePixelType; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename InputImageType::LabelObjectType LabelObjectType; + + typedef typename InputImageType::PixelType PixelType; + typedef typename InputImageType::IndexType IndexType; + typedef typename InputImageType::SizeType SizeType; + typedef typename InputImageType::RegionType RegionType; + + typedef TInputImage TOutputImage; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, TOutputImage::ImageDimension); + itkStaticConstMacro(ImageDimension, unsigned int, TOutputImage::ImageDimension); + + /** The output region to use */ + itkSetMacro(Region, OutputImageRegionType); + itkGetConstReferenceMacro(Region, OutputImageRegionType); + +protected: + ChangeRegionLabelMapFilter() {}; + ~ChangeRegionLabelMapFilter() {}; + + virtual void PrintSelf(std::ostream& os, Indent indent) const; + + virtual void ThreadedProcessLabelObject( LabelObjectType * labelObject ); + + void GenerateInputRequestedRegion(); + + void EnlargeOutputRequestedRegion(DataObject *itkNotUsed(output)); + + virtual void GenerateOutputInformation(); + + void GenerateData(); + +private: + ChangeRegionLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + OutputImageRegionType m_Region; + +}; + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkChangeRegionLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkChangeRegionLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkChangeRegionLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..d4f214128f3d9e29dc40792c4d1fffb489c8d622 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkChangeRegionLabelMapFilter.txx @@ -0,0 +1,155 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkChangeRegionLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-07-21 22:17:01 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + Portions of this code are covered under the VTK copyright. + See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkChangeRegionLabelMapFilter_txx +#define __itkChangeRegionLabelMapFilter_txx +#include "itkChangeRegionLabelMapFilter.h" + + +namespace itk +{ + + +template <class TInputImage> +void +ChangeRegionLabelMapFilter<TInputImage> +::GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // We need all the input. + InputImagePointer input = const_cast<InputImageType *>(this->GetInput()); + if ( !input ) + { return; } + input->SetRequestedRegion( input->GetLargestPossibleRegion() ); +} + +template <class TInputImage> +void +ChangeRegionLabelMapFilter<TInputImage> +::GenerateOutputInformation() +{ + Superclass::GenerateOutputInformation(); + this->GetOutput()->SetLargestPossibleRegion( m_Region ); +} + +template <class TInputImage> +void +ChangeRegionLabelMapFilter<TInputImage> +::EnlargeOutputRequestedRegion(DataObject *) +{ + this->GetOutput() + ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); +} + +template <class TInputImage> +void +ChangeRegionLabelMapFilter<TInputImage> +::GenerateData() +{ + if( m_Region.IsInside( this->GetInput()->GetLargestPossibleRegion() ) ) + { + // only copy the image, report progress anyway + ProgressReporter progress( this, 0, 1 ); + this->AllocateOutputs(); + } + else + { + // call the superclass implementation so it will take care to create the threads + Superclass::GenerateData(); + } +} + + +template<class TInputImage> +void +ChangeRegionLabelMapFilter<TInputImage> +::ThreadedProcessLabelObject( LabelObjectType * labelObject ) +{ + typename InputImageType::LabelObjectType::LineContainerType::const_iterator lit; + typename InputImageType::LabelObjectType::LineContainerType lineContainer = labelObject->GetLineContainer(); + labelObject->GetLineContainer().clear(); + + IndexType idxMin = m_Region.GetIndex(); + IndexType idxMax; + for( int i=0; i<ImageDimension; i++ ) + { + idxMax[i] = idxMin[i] + m_Region.GetSize()[i] - 1; + } + + for( lit = lineContainer.begin(); lit != lineContainer.end(); lit++ ) + { + IndexType idx = lit->GetIndex(); + unsigned long length = lit->GetLength(); + + bool outside = false; + for( int i=1; i<ImageDimension; i++ ) + { + if( idx[i] < idxMin[i] || idx[i] > idxMax[i] ) + { + outside = true; + } + } + // check the axis 0 + if( !outside ) + { + long lastIdx0 = idx[0] + length - 1; + if( !( ( idx[0] < idxMin[0] && lastIdx0 < idxMin[0] ) + || ( idx[0] > idxMax[0] && lastIdx0 > idxMax[0] ) ) ) + { + IndexType newIdx = idx; + long newLength = length; + if( idx[0] < idxMin[0] ) + { + newLength -= idxMin[0] - idx[0]; + newIdx[0] = idxMin[0]; + } + if( lastIdx0 > idxMax[0] ) + { + newLength -= lastIdx0 - idxMax[0]; + } + + labelObject->AddLine( newIdx, newLength ); + } + } + } + + // remove the object if it is empty + if( labelObject->GetLineContainer().empty() ) + { + this->m_LabelObjectContainerLock->Lock(); + this->GetOutput()->RemoveLabelObject( labelObject ); + this->m_LabelObjectContainerLock->Unlock(); + } +} + +template<class TInputImage> +void +ChangeRegionLabelMapFilter<TInputImage> +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + os << indent << "Region: " << m_Region << std::endl; +} + + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkConformalFlatteningMeshFilter.txx b/Utilities/ITK/Code/Review/itkConformalFlatteningMeshFilter.txx index 475f04e1639ad08f9edfc57657c12a1c31f49116..161e8a14aaf00717080d52c499c3ce4e9e36a30e 100644 --- a/Utilities/ITK/Code/Review/itkConformalFlatteningMeshFilter.txx +++ b/Utilities/ITK/Code/Review/itkConformalFlatteningMeshFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkConformalFlatteningMeshFilter.txx,v $ Language: C++ - Date: $Date: 2009-04-06 00:19:17 $ - Version: $Revision: 1.28 $ + Date: $Date: 2009-07-11 12:16:37 $ + Version: $Revision: 1.30 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -41,7 +41,7 @@ ConformalFlatteningMeshFilter< TInputMesh, TOutputMesh > // If during the stage when this parameter is used and it is still // -1.0, then it indicates that the user doesn't assign a scale // factor. Then automatically calculate it s.t. after doing the - // stereo-graphic projection, upper and lowwer hemi-sphere will have + // stereo-graphic projection, upper and lower hemi-sphere will have // same number of vertics. } @@ -219,7 +219,7 @@ ConformalFlatteningMeshFilter< TInputMesh, TOutputMesh > normAB2 = AB[0] * AB[0] + AB[1] * AB[1] + AB[2] * AB[2]; - if( normAB2 < 1e-6 ) + if( normAB2 < 1e-10 ) { itkExceptionMacro("||AB||^2 = " << normAB2 << "\nRisk of division by zero"); @@ -344,19 +344,19 @@ ConformalFlatteningMeshFilter< TInputMesh, TOutputMesh > normBC2 = BC[0] * BC[0] + BC[1] * BC[1] + BC[2] * BC[2]; normCA2 = CA[0] * CA[0] + CA[1] * CA[1] + CA[2] * CA[2]; - if( normAB2 < 1e-6 ) + if( normAB2 < 1e-10 ) { itkExceptionMacro("normAB2 " << normAB2); return; } - if( normBC2 < 1e-6 ) + if( normBC2 < 1e-10 ) { itkExceptionMacro("normBC2 " << normBC2); return; } - if( normCA2 < 1e-6 ) + if( normCA2 < 1e-10 ) { itkExceptionMacro("normCA2 " << normCA2); return; @@ -396,19 +396,19 @@ ConformalFlatteningMeshFilter< TInputMesh, TOutputMesh > sinBCA = vcl_sqrt( 1.0 - cosBCA * cosBCA ); sinCAB = vcl_sqrt( 1.0 - cosCAB * cosCAB ); - if( sinABC < 1e-6 ) + if( sinABC < 1e-10 ) { itkExceptionMacro("sinABC= " << sinABC); return; } - if( sinBCA < 1e-6 ) + if( sinBCA < 1e-10 ) { itkExceptionMacro("sinBCA= " << sinBCA); return; } - if( sinCAB < 1e-6 ) + if( sinCAB < 1e-10 ) { itkExceptionMacro("sinCAB= " << sinCAB); return; @@ -438,59 +438,80 @@ ConformalFlatteningMeshFilter< TInputMesh, TOutputMesh > VectorCoordType y(numberOfPoints, 0.0); { // solving Ax = b (D x = bx) - VectorCoordType Dx; - D.pre_mult(x, Dx); + VectorCoordType rx = bx; + VectorCoordType zx(numberOfPoints); - VectorCoordType Dy; - D.pre_mult(y, Dy); + VectorCoordType ry = by; + VectorCoordType zy(numberOfPoints); - VectorCoordType rx = bx - Dx; - VectorCoordType px = rx; + // Jacobi preconditioner + VectorCoordType Dinv( numberOfPoints ); + for (unsigned long ip = 0; ip < numberOfPoints; ++ip) + { + Dinv[ip] = 1.0/( D(ip, ip) + DBL_MIN); + + zx[ip] = rx[ip]*Dinv[ip]; + zy[ip] = ry[ip]*Dinv[ip]; + } - VectorCoordType ry = by - Dy; - VectorCoordType py = ry; + VectorCoordType dx = zx; + VectorCoordType dy = zy; unsigned int numIter = bx.size(); + if (bx.size() != numberOfPoints) + { + // check for safe + std::cerr<<"bx.size() != numberOfPoints\n"; + } numIter += numIter/10; // let the iteration times a little more than the dimension - double tol = 1e-10; + double tol = 1e-6; for ( i = 0; i <= numIter; ++i) { - VectorCoordType Dpx; - D.pre_mult(px, Dpx); - VectorCoordType Dpy; - D.pre_mult(py, Dpy); - - double pDpx = inner_product(px, Dpx); - double pDpy = inner_product(py, Dpy); - - double alphax = inner_product(px, rx)/(pDpx + DBL_MIN); - double alphay = inner_product(py, ry)/(pDpy + DBL_MIN); + VectorCoordType Dxd; + D.pre_mult(dx, Dxd); + VectorCoordType Dyd; + D.pre_mult(dy, Dyd); + + double dDxd = inner_product(dx, Dxd); + double dDyd = inner_product(dy, Dyd); - x += alphax*px; - y += alphay*py; + double zxTrx = inner_product(zx, rx); + double zyTry = inner_product(zy, ry); - rx -= alphax*Dpx; - ry -= alphay*Dpy; + double alphax = zxTrx/(dDxd + DBL_MIN); + double alphay = zyTry/(dDyd + DBL_MIN); - if ((inner_product(rx, rx) < tol) && (inner_product(ry, ry) < tol)) + x += alphax*dx; + y += alphay*dy; + + + rx -= alphax*Dxd; + ry -= alphay*Dyd; + + double rxTrx = inner_product(rx, rx); + double ryTry = inner_product(ry, ry); + if ( rxTrx < tol && ryTry < tol) { + // std::cout<<"out from here when i = "<<i<<std::endl; break; } - VectorCoordType Drx; - D.pre_mult(rx, Drx); - VectorCoordType Dry; - D.pre_mult(ry, Dry); - double betax = -inner_product(px, Drx)/(pDpx + DBL_MIN); - double betay = -inner_product(py, Dry)/(pDpy + DBL_MIN); + for (unsigned long id = 0; id < numberOfPoints; ++id) + { + zx[id] = rx[id]*Dinv[id]; + zy[id] = ry[id]*Dinv[id]; + } + + double betaX = inner_product(zx, rx)/(zxTrx + DBL_MIN); + double betaY = inner_product(zy, ry)/(zyTry + DBL_MIN); - px = rx + betax*px; - py = ry + betay*py; + dx = zx + betaX*dx; + dy = zy + betaY*dy; } } @@ -519,7 +540,7 @@ ConformalFlatteningMeshFilter< TInputMesh, TOutputMesh > { // < 0 means user doesn't explictly assign it. Then // automatically calculate it s.t. after doing the - // stereo-graphic projection, upper and lowwer hemi-sphere will have + // stereo-graphic projection, upper and lower hemi-sphere will have // same number of vertics. std::vector<double> v_r2(numberOfPoints); diff --git a/Utilities/ITK/Code/Review/itkCropLabelMapFilter.h b/Utilities/ITK/Code/Review/itkCropLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..e7607a8342a4998c1916be9c7e58e8eefa7b056a --- /dev/null +++ b/Utilities/ITK/Code/Review/itkCropLabelMapFilter.h @@ -0,0 +1,126 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkCropLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-07-22 23:59:29 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + Portions of this code are covered under the VTK copyright. + See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkCropLabelMapFilter_h +#define __itkCropLabelMapFilter_h + +#include "itkChangeRegionLabelMapFilter.h" + +namespace itk +{ + +/** \class CropLabelMapFilter + * \brief Crop a LabelMap image + * + * Crop a label map. If the output cannot contain some lines of the objects, they are truncated + * or removed. All objects fully outside the output region are removed. + * + * The SetCropSize() method can be used to set the crop size of the lower and the upper + * boundaries in a single call. By default, the filter does not crop anything. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * \sa PadLabelMapFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template <class TInputImage> +class ITK_EXPORT CropLabelMapFilter : public ChangeRegionLabelMapFilter<TInputImage> +{ +public: + /** Standard class typedefs. */ + typedef CropLabelMapFilter Self; + typedef ChangeRegionLabelMapFilter<TInputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(CropLabelMapFilter, ChangeRegionImageFilter); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Superclass typedefs. */ + typedef typename Superclass::OutputImageType OutputImageType; + typedef typename Superclass::OutputImagePointer OutputImagePointer; + typedef typename Superclass::OutputImageRegionType OutputImageRegionType; + typedef typename Superclass::OutputImagePixelType OutputImagePixelType; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename InputImageType::LabelObjectType LabelObjectType; + + typedef typename InputImageType::PixelType PixelType; + typedef typename InputImageType::IndexType IndexType; + typedef typename InputImageType::SizeType SizeType; + typedef typename InputImageType::RegionType RegionType; + + typedef TInputImage TOutputImage; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, TOutputImage::ImageDimension); + itkStaticConstMacro(ImageDimension, unsigned int, TOutputImage::ImageDimension); + + /** Set/Get the cropping sizes for the upper and lower boundaries. */ + itkSetMacro(UpperBoundaryCropSize, SizeType); + itkGetMacro(UpperBoundaryCropSize, SizeType); + itkSetMacro(LowerBoundaryCropSize, SizeType); + itkGetMacro(LowerBoundaryCropSize, SizeType); + + void SetCropSize( const SizeType & size ) + { + this->SetUpperBoundaryCropSize( size ); + this->SetLowerBoundaryCropSize( size ); + } + +protected: + CropLabelMapFilter() + { + m_UpperBoundaryCropSize.Fill(0); + m_LowerBoundaryCropSize.Fill(0); + } + ~CropLabelMapFilter() {}; + + virtual void GenerateOutputInformation(); + + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + CropLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + SizeType m_UpperBoundaryCropSize; + SizeType m_LowerBoundaryCropSize; +}; + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkCropLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkCropLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkCropLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..493b4c3efd172ca5ded47b115c6a90e9810c4a6b --- /dev/null +++ b/Utilities/ITK/Code/Review/itkCropLabelMapFilter.txx @@ -0,0 +1,75 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkCropLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-07-22 23:59:29 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + Portions of this code are covered under the VTK copyright. + See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkCropLabelMapFilter_txx +#define __itkCropLabelMapFilter_txx + +#include "itkCropLabelMapFilter.h" + +namespace itk +{ + +template <class TInputImage> +void +CropLabelMapFilter<TInputImage> +::GenerateOutputInformation() +{ + const TInputImage * inputPtr = this->GetInput(); + if( !inputPtr ) + { + return; + } + + // Compute the new region size. + RegionType croppedRegion; + SizeType size; + IndexType index; + + SizeType inputSize = inputPtr->GetLargestPossibleRegion().GetSize(); + IndexType inputIndex = inputPtr->GetLargestPossibleRegion().GetIndex(); + + SizeType originalCropSize = m_UpperBoundaryCropSize + m_LowerBoundaryCropSize; + + index = inputIndex + m_LowerBoundaryCropSize; + size = inputSize - ( originalCropSize ); + + croppedRegion.SetSize( size ); + croppedRegion.SetIndex( index ); + + // Set extraction region in the superclass. + this->SetRegion( croppedRegion ); + + Superclass::GenerateOutputInformation(); +} + + +template <class TInputImage> +void +CropLabelMapFilter<TInputImage> +::PrintSelf( std::ostream& os, Indent indent ) const +{ + Superclass::PrintSelf( os,indent ); + + os << indent << "UpperBoundaryCropSize: " << m_UpperBoundaryCropSize << std::endl; + os << indent << "LowerBoundaryCropSize: " << m_LowerBoundaryCropSize << std::endl; +} + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkFFTWComplexToComplexImageFilter.h b/Utilities/ITK/Code/Review/itkFFTWComplexToComplexImageFilter.h index 104dd9fa33dc268b7fe03f6839692a7b1bca27f5..d7de577fab57b4a04ae9ac8038fb9e4f62c261d3 100644 --- a/Utilities/ITK/Code/Review/itkFFTWComplexToComplexImageFilter.h +++ b/Utilities/ITK/Code/Review/itkFFTWComplexToComplexImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFFTWComplexToComplexImageFilter.h,v $ Language: C++ - Date: $Date: 2008-07-03 18:41:16 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-08-13 03:19:20 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -103,8 +103,6 @@ protected: virtual bool FullMatrix(); - void PrintSelf(std::ostream& os, Indent indent) const; - private: FFTWComplexToComplexImageFilter(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented @@ -159,8 +157,6 @@ protected: } } - void PrintSelf(std::ostream& os, Indent indent) const; - // // these should be defined in every FFT filter class virtual void GenerateData(); // generates output from input diff --git a/Utilities/ITK/Code/Review/itkFFTWComplexToComplexImageFilter.txx b/Utilities/ITK/Code/Review/itkFFTWComplexToComplexImageFilter.txx index 88a0b9332019b094f717b14bf2ac481ebd048a95..fa6aae55c9d73f451df5c3650b98f78e8daf785c 100644 --- a/Utilities/ITK/Code/Review/itkFFTWComplexToComplexImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkFFTWComplexToComplexImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkFFTWComplexToComplexImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-02-18 20:51:59 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-08-13 03:19:20 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -155,13 +155,6 @@ FullMatrix() return false; } -template <unsigned int NDimension> -void -FFTWComplexToComplexImageFilter<float,NDimension>:: -PrintSelf(std::ostream& os,Indent indent) const -{ -} - #endif // defined(USE_FFTWF) #if defined(USE_FFTWD) @@ -270,13 +263,6 @@ FullMatrix() return false; } -template <unsigned int NDimension> -void -FFTWComplexToComplexImageFilter<double,NDimension>:: -PrintSelf(std::ostream& os,Indent indent) const -{ -} - #endif // defined(USE_FFTWD) }// namespace itk diff --git a/Utilities/ITK/Code/Review/itkGeometricalQuadEdge.h b/Utilities/ITK/Code/Review/itkGeometricalQuadEdge.h index bcbf15fe30456832f23c317f747081eaa3d1de66..8916d78a122b33a7abf3248736f8060194529b70 100644 --- a/Utilities/ITK/Code/Review/itkGeometricalQuadEdge.h +++ b/Utilities/ITK/Code/Review/itkGeometricalQuadEdge.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGeometricalQuadEdge.h,v $ Language: C++ - Date: $Date: 2008-07-01 15:45:31 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-09-08 20:00:55 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -42,7 +42,7 @@ namespace itk * GeometricalQuadEdge<...> and GeometricalQuadEdge<...>::Dual would be the * same types (this is simply due to the very definition of * GeometricalQuadEdge<...>::Dual). This would in turn make the types QEType - * and QEDual of \ref itkQE::Mesh identical and would prevent any algorithm + * and QEDual of \ref QuadEdgeMesh identical and would prevent any algorithm * requiring to distinguish those types (e.g. by relying on a * dynamic_cast<QEType*>) to be effective. This justifies the existence of * last dummy template parameter and it's default value. diff --git a/Utilities/ITK/Code/Review/itkGridForwardWarpImageFilter.txx b/Utilities/ITK/Code/Review/itkGridForwardWarpImageFilter.txx index b76a5a1bd0bf1de9066ed02df8f6ae3f69a34833..119668beeb95b96350e1833fed0435f4d3920132 100644 --- a/Utilities/ITK/Code/Review/itkGridForwardWarpImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkGridForwardWarpImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGridForwardWarpImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-05-26 23:45:04 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-06-16 07:58:47 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -129,11 +129,7 @@ GridForwardWarpImageFilter<TDeformationField,TOutputImage> inside = false; break; } -#ifdef ITK_USE_PORTABLE_ROUND refIndex[j] = Math::Round(contindex[j]); -#else - refIndex[j] = vnl_math_rnd(contindex[j]); -#endif } if( inside ) @@ -160,11 +156,7 @@ GridForwardWarpImageFilter<TDeformationField,TOutputImage> targetIn = false; break; } -#ifdef ITK_USE_PORTABLE_ROUND targetIndex[j] = Math::Round(contindex[j]); -#else - targetIndex[j] = vnl_math_rnd(contindex[j]); -#endif } if( targetIn ) diff --git a/Utilities/ITK/Code/Review/itkHessianToObjectnessMeasureImageFilter.h b/Utilities/ITK/Code/Review/itkHessianToObjectnessMeasureImageFilter.h index 15b202cc9a55a9da805361d100010fdb3e53ff59..22a45117d2ec15223fc394d2ff4bde52752995a0 100644 --- a/Utilities/ITK/Code/Review/itkHessianToObjectnessMeasureImageFilter.h +++ b/Utilities/ITK/Code/Review/itkHessianToObjectnessMeasureImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkHessianToObjectnessMeasureImageFilter.h,v $ Language: C++ - Date: $Date: 2009-04-23 03:43:41 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-07-01 12:43:38 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,7 +22,7 @@ namespace itk { -/** \class HessianObjectnessMeasureImageFilter +/** \class HessianToObjectnessMeasureImageFilter * \brief A filter to enhance M-dimensional objects in N-dimensional images * * The objectness measure is a generalization of Frangi's vesselness measure, diff --git a/Utilities/ITK/Code/Review/itkInPlaceLabelMapFilter.h b/Utilities/ITK/Code/Review/itkInPlaceLabelMapFilter.h new file mode 100755 index 0000000000000000000000000000000000000000..0e6bfd62618616c276dce599eb630fe125835b1b --- /dev/null +++ b/Utilities/ITK/Code/Review/itkInPlaceLabelMapFilter.h @@ -0,0 +1,182 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkInPlaceLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-07-10 14:15:40 $ + Version: $Revision: 1.4 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + Portions of this code are covered under the VTK copyright. + See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkInPlaceLabelMapFilter_h +#define __itkInPlaceLabelMapFilter_h + +#include "itkLabelMapFilter.h" + +namespace itk +{ + +/** \class InPlaceLabelMapFilter + * \brief Base class for filters that takes an image as input and overwrites + * that image as the output + * + * InPlaceLabelMapFilter is the base class for all process objects whose + * output image data is constructed by overwriting the input image + * data. In other words, the output bulk data is the same block of + * memory as the input bulk data. This filter provides the mechanisms + * for in place image processing while maintaining general pipeline + * mechanics. InPlaceLabelMapFilters use less memory than standard + * ImageToImageFilters because the input buffer is reused as the + * output buffer. However, this benefit does not come without a cost. + * Since the filter overwrites its input, the ownership of the bulk + * data is transitioned from the input data object to the output data + * object. When a data object has multiple consumers with one + * of the consumers being an in place filter, the in place filter + * effectively destroys the bulk data for the data object. Upstream + * filters will then have to re-execute to regenerate the data object's + * bulk data for the remaining consumers. + * + * Since an InPlaceLabelMapFilter reuses the input bulk data memory for the + * output bulk data memory, the input image type must match the output + * image type. If the input and output image types are not identical, + * the filter reverts to a traditional ImageToImageFilter behaviour + * where an output image is allocated. In place operation can also be + * controlled (when the input and output image type match) via the + * methods InPlaceOn() and InPlaceOff(). + * + * Subclasses of InPlaceLabelMapFilter must take extra care in how they + * manage memory using (and perhaps overriding) the implementations of + * ReleaseInputs() and AllocateOutputs() provided here. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, + * INRA de Jouy-en-Josas, France. + * + * \sa LabelMapToBinaryImageFilter, LabelMapToLabelImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template <class TInputImage> +class ITK_EXPORT InPlaceLabelMapFilter : public LabelMapFilter<TInputImage, TInputImage> +{ +public: + /** Standard class typedefs. */ + typedef InPlaceLabelMapFilter Self; + typedef LabelMapFilter<TInputImage, TInputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + + /** Run-time type information (and related methods). */ + itkTypeMacro(InPlaceLabelMapFilter, LabelMapFilter); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Superclass typedefs. */ + typedef typename Superclass::OutputImageType OutputImageType; + typedef typename Superclass::OutputImagePointer OutputImagePointer; + typedef typename Superclass::OutputImageRegionType OutputImageRegionType; + typedef typename Superclass::OutputImagePixelType OutputImagePixelType; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename InputImageType::LabelObjectType LabelObjectType; + + typedef typename InputImageType::PixelType PixelType; + typedef typename InputImageType::IndexType IndexType; + typedef typename InputImageType::RegionType RegionType; + + typedef TInputImage TOutputImage; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, TOutputImage::ImageDimension); + + /** In place operation can be turned on and off. This only has an + * effect when the input and output image type match. */ + itkSetMacro(InPlace, bool); + itkGetMacro(InPlace, bool); + itkBooleanMacro(InPlace); + + /** Can the filter run in place? To do so, the filter's first input + * and output must have the same dimension and pixel type. This + * method can be used in conjunction with the InPlace ivar to + * determine whether a particular use of the filter is really + * running in place. Some filters may be able to optimize their + * operation if the InPlace is true and CanRunInPlace is true. */ + bool CanRunInPlace() const + { + return (typeid(TInputImage) == typeid(TOutputImage)); + }; + +protected: + InPlaceLabelMapFilter(); + ~InPlaceLabelMapFilter(); + + virtual void PrintSelf(std::ostream& os, Indent indent) const; + + /** The GenerateData method normally allocates the buffers for all + * of the outputs of a filter. Since InPlaceLabelMapFilter's can use an + * overwritten version of the input for its output, the output + * buffer should not be allocated. When possible, we graft the input + * to the filter to the output. If an InPlaceFilter has multiple + * outputs, then it would need to override this method to graft one + * of its outputs and allocate the remaining. If a filter is + * threaded (i.e. it provides an implementation of + * ThreadedGenerateData()), this method is called automatically. If + * an InPlaceFilter is not threaded (i.e. it provides an + * implementation of GenerateData()), then this method (or + * equivalent) must be called in GenerateData(). */ + virtual void AllocateOutputs(); + + /** InPlaceLabelMapFilter may transfer ownership of the input bulk data + * to the output object. Once the output object owns the bulk data + * (done in AllocateOutputs()), the input object must release its + * hold on the bulk data. ProcessObject::ReleaseInputs() only + * releases the input bulk data when the user has set the + * ReleaseDataFlag. InPlaceLabelMapFilter::ReleaseInputs() also + * releases the input that it has overwritten. + * + * \sa ProcessObject::ReleaseInputs() */ + virtual void ReleaseInputs(); + + + /** + * Return the output label collection image, instead of the input as in the default + * implementation + */ + virtual InputImageType * GetLabelMap() + { + return this->GetOutput(); + } + + typedef typename Superclass::LabelObjectContainerType LabelObjectContainerType; + typedef typename Superclass::LabelObjectContainerConstIterator LabelObjectContainerConstIterator; + +private: + InPlaceLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + bool m_InPlace; + +}; + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkInPlaceLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkInPlaceLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkInPlaceLabelMapFilter.txx new file mode 100755 index 0000000000000000000000000000000000000000..ee9942ce4d870d842c2d22e7c5e4e9a044ab5091 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkInPlaceLabelMapFilter.txx @@ -0,0 +1,159 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkInPlaceLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-07-10 13:53:12 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + Portions of this code are covered under the VTK copyright. + See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkInPlaceLabelMapFilter_txx +#define __itkInPlaceLabelMapFilter_txx + +#include "itkInPlaceLabelMapFilter.h" + + +namespace itk +{ + +/** + * + */ +template <class TInputImage> +InPlaceLabelMapFilter<TInputImage> +::InPlaceLabelMapFilter() : m_InPlace(true) +{ +} + +/** + * + */ +template <class TInputImage> +InPlaceLabelMapFilter<TInputImage> +::~InPlaceLabelMapFilter() +{ +} + + + +template<class TInputImage> +void +InPlaceLabelMapFilter<TInputImage> +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + os << indent << "InPlace: " << (this->m_InPlace ? "On" : "Off") << std::endl; + if ( this->CanRunInPlace()) + { + os << indent << "The input and output to this filter are the same type. The filter can be run in place." << std::endl; + } + else + { + os << indent << "The input and output to this filter are different types. The filter cannot be run in place." << std::endl; + } +} + +template<class TInputImage> +void +InPlaceLabelMapFilter<TInputImage> +::AllocateOutputs() +{ + // if told to run in place and the types support it, + if( this->m_InPlace && this->CanRunInPlace() ) + { + // Graft this first input to the output. Later, we'll need to + // remove the input's hold on the bulk data. + // + OutputImagePointer inputAsOutput = dynamic_cast<TOutputImage *>(const_cast<TInputImage *>(this->GetInput())); + + if( inputAsOutput ) + { + // save the largest possible region to restore it after the graft output. + // the largest possible region is not that important with LabelMap and + // can be managed by the filter, even when running inplace + RegionType region = this->GetOutput()->GetLargestPossibleRegion(); + this->GraftOutput( inputAsOutput ); + this->GetOutput()->SetRegions( region ); + } + + // If there are more than one outputs, allocate the remaining outputs + for (unsigned int i=1; i < this->GetNumberOfOutputs(); i++) + { + OutputImagePointer outputPtr; + + outputPtr = this->GetOutput(i); + outputPtr->SetBufferedRegion(outputPtr->GetRequestedRegion()); + outputPtr->Allocate(); + } + } + else + { + Superclass::AllocateOutputs(); + // copy the content of the input image to the output image + const TInputImage * input = this->GetInput(); + TOutputImage * output = this->GetOutput(); + assert( input != NULL ); + assert( output != NULL ); + + output->SetBackgroundValue( input->GetBackgroundValue() ); + + + const LabelObjectContainerType & labelObjectContainer = input->GetLabelObjectContainer(); + + LabelObjectContainerConstIterator it = labelObjectContainer.begin(); + + while( it != labelObjectContainer.end() ) + { + const LabelObjectType * labeObject = it->second; + + assert( labeObject != NULL ); + assert( labeObject->GetLabel() == it->first ); + + typename LabelObjectType::Pointer newLabelObject = LabelObjectType::New(); + newLabelObject->CopyAllFrom( labeObject ); + + output->AddLabelObject( newLabelObject ); + it++; + } + + } +} + +template<class TInputImage> +void +InPlaceLabelMapFilter<TInputImage> +::ReleaseInputs() +{ + // if told to run in place and the types support it, + if( this->m_InPlace && (typeid(TInputImage) == typeid(TOutputImage)) ) + { + + // Release any input where the ReleaseData flag has been set + ProcessObject::ReleaseInputs(); + + // Release input 0 by default since we overwrote it + TInputImage * ptr = const_cast<TInputImage*>( this->GetInput() ); + if( ptr ) + { + ptr->ReleaseData(); + } + } + else + { + Superclass::ReleaseInputs(); + } +} + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelContourImageFilter.h b/Utilities/ITK/Code/Review/itkLabelContourImageFilter.h index 0ea2f29e8fce2743f698dd1c09fe186da48e55b9..aab3fd671ec021e322ae012e5a55f4cdab18011c 100644 --- a/Utilities/ITK/Code/Review/itkLabelContourImageFilter.h +++ b/Utilities/ITK/Code/Review/itkLabelContourImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelContourImageFilter.h,v $ Language: C++ - Date: $Date: 2009-04-23 03:43:41 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-07-22 16:57:52 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -84,11 +84,13 @@ public: /** * Image typedef support */ - typedef TInputImage InputImageType; - typedef typename TInputImage::IndexType IndexType; - typedef typename TInputImage::SizeType SizeType; - typedef typename TInputImage::OffsetType OffsetType; - typedef typename TInputImage::PixelType InputImagePixelType; + typedef TInputImage InputImageType; + typedef typename TInputImage::IndexType IndexType; + typedef typename TInputImage::SizeType SizeType; + typedef typename TInputImage::OffsetType OffsetType; + typedef typename TInputImage::PixelType InputImagePixelType; + typedef typename TInputImage::SizeValueType SizeValueType; + typedef typename TInputImage::OffsetValueType OffsetValueType; typedef TOutputImage OutputImageType; typedef typename TOutputImage::RegionType RegionType; diff --git a/Utilities/ITK/Code/Review/itkLabelContourImageFilter.txx b/Utilities/ITK/Code/Review/itkLabelContourImageFilter.txx index 81bc27acbdf063bb15a7cad15e2db516351d8a2e..0c3c168186fee1c856c308627ae08c63c6896b3a 100644 --- a/Utilities/ITK/Code/Review/itkLabelContourImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkLabelContourImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelContourImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-02-14 22:00:53 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-08-07 19:14:24 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -67,7 +67,7 @@ LabelContourImageFilter< TInputImage, TOutputImage> typename TOutputImage::Pointer output = this->GetOutput(); typename TInputImage::ConstPointer input = this->GetInput(); - long nbOfThreads = this->GetNumberOfThreads(); + unsigned long nbOfThreads = this->GetNumberOfThreads(); if( itk::MultiThreader::GetGlobalMaximumNumberOfThreads() != 0 ) { nbOfThreads = vnl_math_min( this->GetNumberOfThreads(), itk::MultiThreader::GetGlobalMaximumNumberOfThreads() ); @@ -80,9 +80,9 @@ LabelContourImageFilter< TInputImage, TOutputImage> m_Barrier = Barrier::New(); m_Barrier->Initialize( nbOfThreads ); - long pixelcount = output->GetRequestedRegion().GetNumberOfPixels(); - long xsize = output->GetRequestedRegion().GetSize()[0]; - long linecount = pixelcount/xsize; + SizeValueType pixelcount = output->GetRequestedRegion().GetNumberOfPixels(); + SizeValueType xsize = output->GetRequestedRegion().GetSize()[0]; + SizeValueType linecount = pixelcount/xsize; m_LineMap.clear(); m_LineMap.resize( linecount ); m_NumberOfThreads = nbOfThreads; @@ -110,9 +110,9 @@ LabelContourImageFilter< TInputImage, TOutputImage> outLineIt.SetDirection(0); // set the progress reporter to deal with the number of lines - long pixelcountForThread = outputRegionForThread.GetNumberOfPixels(); - long xsizeForThread = outputRegionForThread.GetSize()[0]; - long linecountForThread = pixelcountForThread/xsizeForThread; + SizeValueType pixelcountForThread = outputRegionForThread.GetNumberOfPixels(); + SizeValueType xsizeForThread = outputRegionForThread.GetSize()[0]; + SizeValueType linecountForThread = pixelcountForThread/xsizeForThread; ProgressReporter progress(this, threadId, linecountForThread * 2); // find the split axis @@ -130,8 +130,8 @@ LabelContourImageFilter< TInputImage, TOutputImage> // compute the number of pixels before that thread SizeType outputRegionSize = output->GetRequestedRegion().GetSize(); outputRegionSize[splitAxis] = outputRegionForThreadIdx[splitAxis] - outputRegionIdx[splitAxis]; - long firstLineIdForThread = RegionType( outputRegionIdx, outputRegionSize ).GetNumberOfPixels() / xsizeForThread; - long lineId = firstLineIdForThread; + SizeValueType firstLineIdForThread = RegionType( outputRegionIdx, outputRegionSize ).GetNumberOfPixels() / xsizeForThread; + SizeValueType lineId = firstLineIdForThread; OffsetVec LineOffsets; SetupLineOffsets(LineOffsets); @@ -149,7 +149,7 @@ LabelContourImageFilter< TInputImage, TOutputImage> InputPixelType PVal = inLineIt.Get(); runLength thisRun; - long length=0; + SizeValueType length=0; IndexType thisIndex; thisIndex = inLineIt.GetIndex(); //std::cout << thisIndex << std::endl; @@ -184,24 +184,24 @@ LabelContourImageFilter< TInputImage, TOutputImage> // now process the map and make appropriate entries in an equivalence // table // assert( linecount == m_ForegroundLineMap.size() ); - long pixelcount = output->GetRequestedRegion().GetNumberOfPixels(); - long xsize = output->GetRequestedRegion().GetSize()[0]; - long linecount = pixelcount/xsize; + SizeValueType pixelcount = output->GetRequestedRegion().GetNumberOfPixels(); + SizeValueType xsize = output->GetRequestedRegion().GetSize()[0]; + OffsetValueType linecount = pixelcount/xsize; - long lastLineIdForThread = linecount; + SizeValueType lastLineIdForThread = linecount; if( threadId != m_NumberOfThreads - 1 ) { lastLineIdForThread = firstLineIdForThread + RegionType( outputRegionIdx, outputRegionForThread.GetSize() ).GetNumberOfPixels() / xsizeForThread; } - for(long ThisIdx = firstLineIdForThread; ThisIdx < lastLineIdForThread; ++ThisIdx) + for(SizeValueType ThisIdx = firstLineIdForThread; ThisIdx < lastLineIdForThread; ++ThisIdx) { if( !m_LineMap[ThisIdx].empty() ) { for (OffsetVec::const_iterator I = LineOffsets.begin(); I != LineOffsets.end(); ++I) { - long NeighIdx = ThisIdx + (*I); + OffsetValueType NeighIdx = ThisIdx + (*I); // check if the neighbor is in the map if ( NeighIdx >= 0 && NeighIdx < linecount && !m_LineMap[NeighIdx].empty() ) { @@ -276,7 +276,7 @@ LabelContourImageFilter< TInputImage, TOutputImage> typename LineNeighborhoodType::IndexListType::const_iterator LI; PretendIndexType idx = LineRegion.GetIndex(); - long offset = fakeImage->ComputeOffset( idx ); + OffsetValueType offset = fakeImage->ComputeOffset( idx ); for (LI=ActiveIndexes.begin(); LI != ActiveIndexes.end(); LI++) { @@ -324,7 +324,7 @@ LabelContourImageFilter< TInputImage, TOutputImage> } } - long offset = 0; + OffsetValueType offset = 0; if (m_FullyConnected || sameLine) { offset = 1; @@ -345,8 +345,8 @@ LabelContourImageFilter< TInputImage, TOutputImage> continue; } //runLength cL = *cIt; - long cStart = cIt->where[0]; // the start x position - long cLast = cStart + cIt->length - 1; + OffsetValueType cStart = cIt->where[0]; // the start x position + OffsetValueType cLast = cStart + cIt->length - 1; bool lineCompleted = false; for (nIt=mIt; nIt != Neighbour.end() && !lineCompleted; ++nIt) { @@ -356,8 +356,8 @@ LabelContourImageFilter< TInputImage, TOutputImage> } //runLength nL = *nIt; - long nStart = nIt->where[0]; - long nLast = nStart + nIt->length - 1; + OffsetValueType nStart = nIt->where[0]; + OffsetValueType nLast = nStart + nIt->length - 1; // there are a few ways that neighbouring lines might overlap // neighbor S------------------E // current S------------------------E @@ -371,13 +371,13 @@ LabelContourImageFilter< TInputImage, TOutputImage> // neighbor S------------------E // current S-------E //------------- - long ss1 = nStart - offset; - // long ss2 = nStart + offset; - // long ee1 = nLast - offset; - long ee2 = nLast + offset; + OffsetValueType ss1 = nStart - offset; + // OffsetValueType ss2 = nStart + offset; + // OffsetValueType ee1 = nLast - offset; + OffsetValueType ee2 = nLast + offset; bool eq = false; - long oStart = 0; - long oLast = 0; + OffsetValueType oStart = 0; + OffsetValueType oLast = 0; // the logic here can probably be improved a lot if ((ss1 >= cStart) && (ee2 <= cLast)) { diff --git a/Utilities/ITK/Code/Review/itkLabelImageToLabelMapFilter.h b/Utilities/ITK/Code/Review/itkLabelImageToLabelMapFilter.h index 31d5eccc5075b6324ba3bfe041444f6e8ff0948a..3829c88dd5acaa298f3049bfc870c3fc32d59373 100644 --- a/Utilities/ITK/Code/Review/itkLabelImageToLabelMapFilter.h +++ b/Utilities/ITK/Code/Review/itkLabelImageToLabelMapFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelImageToLabelMapFilter.h,v $ Language: C++ - Date: $Date: 2009-05-14 21:08:43 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-07-08 15:58:33 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -31,10 +31,14 @@ namespace itk { * * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * * \sa BinaryImageToLabelMapFilter, LabelMapToLabelImageFilter * \ingroup ImageEnhancement MathematicalMorphologyImageFilters */ -template<class TInputImage, class TOutputImage=LabelMap< LabelObject< typename TInputImage::PixelType, ::itk::GetImageDimension<TInputImage>::ImageDimension::ImageDimension > > > +template<class TInputImage, class TOutputImage=LabelMap< LabelObject< typename TInputImage::PixelType, ::itk::GetImageDimension<TInputImage>::ImageDimension > > > class ITK_EXPORT LabelImageToLabelMapFilter : public ImageToImageFilter<TInputImage, TOutputImage> { diff --git a/Utilities/ITK/Code/Review/itkLabelImageToShapeLabelMapFilter.h b/Utilities/ITK/Code/Review/itkLabelImageToShapeLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..90fa3fa1fb1be9115538acb971591bcf4e219800 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelImageToShapeLabelMapFilter.h @@ -0,0 +1,154 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelImageToShapeLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-11 14:24:42 $ + Version: $Revision: 1.4 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelImageToShapeLabelMapFilter_h +#define __itkLabelImageToShapeLabelMapFilter_h + +#include "itkImageToImageFilter.h" +#include "itkShapeLabelObject.h" +#include "itkLabelMap.h" +#include "itkLabelImageToLabelMapFilter.h" +#include "itkShapeLabelMapFilter.h" + + +namespace itk { + +/** \class LabelImageToShapeLabelMapFilter + * \brief Converts a label image to a label map and valuates the shape attributes + * + * A convenient class that converts a label image to a label map and valuates the shape attribute at once. + * + * This implementation was taken from the Insight Journal paper: + * + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * \sa ShapeLabelObject, LabelShapeOpeningImageFilter, LabelStatisticsOpeningImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TInputImage, class TOutputImage=LabelMap< ShapeLabelObject< ITK_TYPENAME TInputImage::PixelType, ::itk::GetImageDimension<TInputImage>::ImageDimension> > > +class ITK_EXPORT LabelImageToShapeLabelMapFilter : + public ImageToImageFilter<TInputImage, TOutputImage> +{ +public: + /** Standard class typedefs. */ + typedef LabelImageToShapeLabelMapFilter Self; + typedef ImageToImageFilter<TInputImage, TOutputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + + typedef TOutputImage OutputImageType; + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::ConstPointer OutputImageConstPointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + typedef typename OutputImageType::LabelObjectType LabelObjectType; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, TInputImage::ImageDimension); + itkStaticConstMacro(ImageDimension, unsigned int, TInputImage::ImageDimension); + + typedef LabelImageToLabelMapFilter< InputImageType, OutputImageType > + LabelizerType; + typedef Image< typename OutputImageType::PixelType, itkGetStaticConstMacro(OutputImageDimension)> + ShapeLabelFilterOutput; + typedef ShapeLabelMapFilter< TOutputImage, ShapeLabelFilterOutput > + LabelObjectValuatorType; + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(LabelImageToShapeLabelMapFilter, ImageToImageFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>)); + /** End concept checking */ +#endif + + /** + * Set/Get the value used as "background" in the output image. + * Defaults to NumericTraits<PixelType>::NonpositiveMin(). + */ + itkSetMacro( BackgroundValue, OutputImagePixelType ); + itkGetConstMacro( BackgroundValue, OutputImagePixelType ); + + /** + * Set/Get whether the maximum Feret diameter should be computed or not. + * Default value is false, because of the high computation time required. + */ + itkSetMacro(ComputeFeretDiameter, bool); + itkGetConstReferenceMacro(ComputeFeretDiameter, bool); + itkBooleanMacro(ComputeFeretDiameter); + + /** + * Set/Get whether the perimeter should be computed or not. + * Default value is false, because of the high computation time required. + */ + itkSetMacro(ComputePerimeter, bool); + itkGetConstReferenceMacro(ComputePerimeter, bool); + itkBooleanMacro(ComputePerimeter); + +protected: + LabelImageToShapeLabelMapFilter(); + ~LabelImageToShapeLabelMapFilter() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + + /** LabelImageToShapeLabelMapFilter needs the entire input be available. + * Thus, it needs to provide an implementation of GenerateInputRequestedRegion(). */ + void GenerateInputRequestedRegion(); + + /** LabelImageToShapeLabelMapFilter will produce the entire output. */ + void EnlargeOutputRequestedRegion(DataObject *itkNotUsed(output)); + + /** Single-threaded version of GenerateData. + * This filter delegates to GrayscaleGeodesicErodeImageFilter. */ + void GenerateData(); + + +private: + LabelImageToShapeLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + OutputImagePixelType m_BackgroundValue; + bool m_ComputeFeretDiameter; + bool m_ComputePerimeter; + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkLabelImageToShapeLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelImageToShapeLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkLabelImageToShapeLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..75b36c03093918d62a4f981f192919c928873ccc --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelImageToShapeLabelMapFilter.txx @@ -0,0 +1,106 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelImageToShapeLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-07 08:29:56 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelImageToShapeLabelMapFilter_txx +#define __itkLabelImageToShapeLabelMapFilter_txx + +#include "itkLabelImageToShapeLabelMapFilter.h" +#include "itkProgressAccumulator.h" + + +namespace itk { + +template<class TInputImage, class TOutputImage> +LabelImageToShapeLabelMapFilter<TInputImage, TOutputImage> +::LabelImageToShapeLabelMapFilter() +{ + m_BackgroundValue = NumericTraits<OutputImagePixelType>::NonpositiveMin(); + m_ComputeFeretDiameter = false; + m_ComputePerimeter = false; +} + +template<class TInputImage, class TOutputImage> +void +LabelImageToShapeLabelMapFilter<TInputImage, TOutputImage> +::GenerateInputRequestedRegion() +{ + // Call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // We need all the inputs + InputImagePointer input = const_cast<InputImageType *>(this->GetInput()); + if( input ) + { + input->SetRequestedRegion( input->GetLargestPossibleRegion() ); + } +} + + +template<class TInputImage, class TOutputImage> +void +LabelImageToShapeLabelMapFilter<TInputImage, TOutputImage> +::EnlargeOutputRequestedRegion(DataObject *) +{ + this->GetOutput() + ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); +} + + +template<class TInputImage, class TOutputImage> +void +LabelImageToShapeLabelMapFilter<TInputImage, TOutputImage> +::GenerateData() +{ + // Create a process accumulator for tracking the progress of this minipipeline + ProgressAccumulator::Pointer progress = ProgressAccumulator::New(); + progress->SetMiniPipelineFilter(this); + + // Allocate the output + this->AllocateOutputs(); + + typename LabelizerType::Pointer labelizer = LabelizerType::New(); + labelizer->SetInput( this->GetInput() ); + labelizer->SetBackgroundValue( m_BackgroundValue ); + labelizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(labelizer, .5f); + + typename LabelObjectValuatorType::Pointer valuator = LabelObjectValuatorType::New(); + valuator->SetInput( labelizer->GetOutput() ); + valuator->SetNumberOfThreads( this->GetNumberOfThreads() ); + valuator->SetComputePerimeter( m_ComputePerimeter ); + valuator->SetComputeFeretDiameter( m_ComputeFeretDiameter ); + progress->RegisterInternalFilter(valuator, .5f); + + valuator->GraftOutput( this->GetOutput() ); + valuator->Update(); + this->GraftOutput( valuator->GetOutput() ); +} + + +template<class TInputImage, class TOutputImage> +void +LabelImageToShapeLabelMapFilter<TInputImage, TOutputImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "BackgroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_BackgroundValue) << std::endl; + os << indent << "ComputeFeretDiameter: " << m_ComputeFeretDiameter << std::endl; + os << indent << "ComputePerimeter: " << m_ComputePerimeter << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelImageToStatisticsLabelMapFilter.h b/Utilities/ITK/Code/Review/itkLabelImageToStatisticsLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..397a2a84fc998defd40da65fcabbedc9dedd7d30 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelImageToStatisticsLabelMapFilter.h @@ -0,0 +1,203 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelImageToStatisticsLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-10 11:54:59 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelImageToStatisticsLabelMapFilter_h +#define __itkLabelImageToStatisticsLabelMapFilter_h + +#include "itkImageToImageFilter.h" +#include "itkStatisticsLabelObject.h" +#include "itkLabelMap.h" +#include "itkLabelImageToLabelMapFilter.h" +#include "itkStatisticsLabelMapFilter.h" + + +namespace itk { + +/** \class LabelImageToStatisticsLabelMapFilter + * \brief a convenient class to convert a label image to a label map and valuate the statistics attributes at once + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \sa StatisticsLabelObject, LabelStatisticsOpeningImageFilter, LabelStatisticsOpeningImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TInputImage, class TFeatureImage, class TOutputImage=LabelMap< StatisticsLabelObject< ITK_TYPENAME TInputImage::PixelType, ::itk::GetImageDimension<TInputImage>::ImageDimension> > > +class ITK_EXPORT LabelImageToStatisticsLabelMapFilter : + public ImageToImageFilter<TInputImage, TOutputImage> +{ +public: + /** Standard class typedefs. */ + typedef LabelImageToStatisticsLabelMapFilter Self; + typedef ImageToImageFilter<TInputImage, TOutputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + + typedef TOutputImage OutputImageType; + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::ConstPointer OutputImageConstPointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + typedef typename OutputImageType::LabelObjectType LabelObjectType; + + typedef TFeatureImage FeatureImageType; + typedef typename FeatureImageType::Pointer FeatureImagePointer; + typedef typename FeatureImageType::ConstPointer FeatureImageConstPointer; + typedef typename FeatureImageType::PixelType FeatureImagePixelType; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(ImageDimension, unsigned int, + TInputImage::ImageDimension); + + typedef LabelImageToLabelMapFilter< InputImageType, OutputImageType > LabelizerType; + typedef StatisticsLabelMapFilter< OutputImageType, FeatureImageType > LabelObjectValuatorType; + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(LabelImageToStatisticsLabelMapFilter, + ImageToImageFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>)); + /** End concept checking */ +#endif + + /** + * Set/Get the value used as "background" in the output image. + * Defaults to NumericTraits<PixelType>::NonpositiveMin(). + */ + itkSetMacro(BackgroundValue, OutputImagePixelType); + itkGetConstMacro(BackgroundValue, OutputImagePixelType); + + /** + * Set/Get whether the maximum Feret diameter should be computed or not. The + * defaut value is false, because of the high computation time required. + */ + itkSetMacro(ComputeFeretDiameter, bool); + itkGetConstReferenceMacro(ComputeFeretDiameter, bool); + itkBooleanMacro(ComputeFeretDiameter); + + /** + * Set/Get whether the perimeter should be computed or not. The defaut value + * is false, because of the high computation time required. + */ + itkSetMacro(ComputePerimeter, bool); + itkGetConstReferenceMacro(ComputePerimeter, bool); + itkBooleanMacro(ComputePerimeter); + + /** Set the feature image */ + void SetFeatureImage(const TFeatureImage *input) + { + // Process object is not const-correct so the const casting is required. + this->SetNthInput( 1, const_cast<TFeatureImage *>(input) ); + } + + /** Get the feature image */ + const FeatureImageType * GetFeatureImage() + { + return static_cast<FeatureImageType*>(this->ProcessObject::GetInput(1)); + } + + /** Set the input image */ + void SetInput1(const InputImageType *input) + { + this->SetInput( input ); + } + + /** Set the feature image */ + void SetInput2(const FeatureImageType *input) + { + this->SetFeatureImage( input ); + } + + /** + * Set/Get whether the histogram should be attached to the label object or not. + * This option defaults to `true`, but because the histogram may take a lot of memory + * compared to the other attributes, this option is useful to reduce the memory usage + * when the histogram is not required. + */ + itkSetMacro(ComputeHistogram, bool); + itkGetConstReferenceMacro(ComputeHistogram, bool); + itkBooleanMacro(ComputeHistogram); + + /** + * Set/Get the number of bins in the histogram. Note that the histogram is used + * to compute the median value, and that this option may have an effect on the + * value of the median. + */ + itkSetMacro(NumberOfBins, unsigned int); + itkGetConstReferenceMacro(NumberOfBins, unsigned int); + + +protected: + LabelImageToStatisticsLabelMapFilter(); + ~LabelImageToStatisticsLabelMapFilter() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + + /** LabelImageToStatisticsLabelMapFilter needs the entire input be + * available. Thus, it needs to provide an implementation of + * GenerateInputRequestedRegion(). */ + void GenerateInputRequestedRegion(); + + /** LabelImageToStatisticsLabelMapFilter will produce the entire output. */ + void EnlargeOutputRequestedRegion(DataObject *itkNotUsed(output)); + + /** Single-threaded version of GenerateData. This filter delegates + * to GrayscaleGeodesicErodeImageFilter. */ + void GenerateData(); + + +private: + LabelImageToStatisticsLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + OutputImagePixelType m_BackgroundValue; + bool m_ComputeFeretDiameter; + bool m_ComputePerimeter; + unsigned int m_NumberOfBins; + bool m_ComputeHistogram; + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkLabelImageToStatisticsLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelImageToStatisticsLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkLabelImageToStatisticsLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..3e401878d6e20c78e3230dd09344751e06e6dd7f --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelImageToStatisticsLabelMapFilter.txx @@ -0,0 +1,114 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelImageToStatisticsLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-07 08:27:57 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelImageToStatisticsLabelMapFilter_txx +#define __itkLabelImageToStatisticsLabelMapFilter_txx + +#include "itkLabelImageToStatisticsLabelMapFilter.h" +#include "itkProgressAccumulator.h" + + +namespace itk { + +template<class TInputImage, class TFeatureImage, class TOutputImage> +LabelImageToStatisticsLabelMapFilter<TInputImage, TFeatureImage, TOutputImage> +::LabelImageToStatisticsLabelMapFilter() +{ + m_BackgroundValue = NumericTraits<OutputImagePixelType>::NonpositiveMin(); + m_ComputeFeretDiameter = false; + m_ComputePerimeter = false; + m_NumberOfBins = 128; + m_ComputeHistogram = true; + this->SetNumberOfRequiredInputs(2); +} + +template<class TInputImage, class TFeatureImage, class TOutputImage> +void +LabelImageToStatisticsLabelMapFilter<TInputImage, TFeatureImage, TOutputImage> +::GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // We need all the input. + InputImagePointer input = const_cast<InputImageType *>(this->GetInput()); + if( input ) + { + input->SetRequestedRegion( input->GetLargestPossibleRegion() ); + } +} + + +template<class TInputImage, class TFeatureImage, class TOutputImage> +void +LabelImageToStatisticsLabelMapFilter<TInputImage, TFeatureImage, TOutputImage> +::EnlargeOutputRequestedRegion(DataObject *) +{ + this->GetOutput() + ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); +} + + +template<class TInputImage, class TFeatureImage, class TOutputImage> +void +LabelImageToStatisticsLabelMapFilter<TInputImage, TFeatureImage, TOutputImage> +::GenerateData() +{ + // Create a process accumulator for tracking the progress of this minipipeline + ProgressAccumulator::Pointer progress = ProgressAccumulator::New(); + progress->SetMiniPipelineFilter(this); + + // Allocate the output + this->AllocateOutputs(); + + typename LabelizerType::Pointer labelizer = LabelizerType::New(); + labelizer->SetInput( this->GetInput() ); + labelizer->SetBackgroundValue( m_BackgroundValue ); + labelizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(labelizer, .5f); + + typename LabelObjectValuatorType::Pointer valuator = LabelObjectValuatorType::New(); + valuator->SetInput( labelizer->GetOutput() ); + valuator->SetFeatureImage( this->GetFeatureImage() ); + valuator->SetNumberOfThreads( this->GetNumberOfThreads() ); + valuator->SetComputePerimeter( m_ComputePerimeter ); + valuator->SetComputeFeretDiameter( m_ComputeFeretDiameter ); + valuator->SetComputeHistogram( m_ComputeHistogram ); + valuator->SetNumberOfBins( m_NumberOfBins ); + progress->RegisterInternalFilter(valuator, .5f); + + valuator->GraftOutput( this->GetOutput() ); + valuator->Update(); + this->GraftOutput( valuator->GetOutput() ); +} + + +template<class TInputImage, class TFeatureImage, class TOutputImage> +void +LabelImageToStatisticsLabelMapFilter<TInputImage, TFeatureImage, TOutputImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "BackgroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_BackgroundValue) << std::endl; + os << indent << "ComputeFeretDiameter: " << m_ComputeFeretDiameter << std::endl; + os << indent << "ComputePerimeter: " << m_ComputePerimeter << std::endl; + os << indent << "ComputeHistogram: " << m_ComputeHistogram << std::endl; + os << indent << "NumberOfBins: " << m_NumberOfBins << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelMap.txx b/Utilities/ITK/Code/Review/itkLabelMap.txx index 0671040d643088a8ad74a145d177772c1639ec42..d7f39c685ec6ff6f8899be40d958b586622be284 100644 --- a/Utilities/ITK/Code/Review/itkLabelMap.txx +++ b/Utilities/ITK/Code/Review/itkLabelMap.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelMap.txx,v $ Language: C++ - Date: $Date: 2009-05-15 17:47:34 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-07-07 18:41:40 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -262,7 +262,6 @@ LabelMap<TLabelObject> labelObject->SetLabel( label ); labelObject->AddIndex( idx ); this->AddLabelObject( labelObject ); -// std::cout<< m_LabelObjectContainer.size() << std::endl; } } @@ -293,7 +292,6 @@ LabelMap<TLabelObject> labelObject->SetLabel( label ); labelObject->AddLine( idx, length ); this->AddLabelObject( labelObject ); -// std::cout<< m_LabelObjectContainer.size() << std::endl; } } diff --git a/Utilities/ITK/Code/Review/itkLabelMapFilter.h b/Utilities/ITK/Code/Review/itkLabelMapFilter.h index 1d0dfa55a9615ad273827e32ed200f5408293ce4..bb36eaf2fbd42a122a920416dab86d66e8a1d266 100644 --- a/Utilities/ITK/Code/Review/itkLabelMapFilter.h +++ b/Utilities/ITK/Code/Review/itkLabelMapFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelMapFilter.h,v $ Language: C++ - Date: $Date: 2009-05-16 22:19:30 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-08-15 16:50:00 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,6 +22,7 @@ #include "itkImageToImageFilter.h" #include "itkProgressReporter.h" +#include "itkFastMutexLock.h" namespace itk { @@ -46,7 +47,9 @@ namespace itk * \ingroup LabeledImageFilters */ template <class TInputImage, class TOutputImage> -class ITK_EXPORT LabelMapFilter : public ImageToImageFilter<TInputImage, TOutputImage> +class ITK_EXPORT LabelMapFilter : +public +ImageToImageFilter<TInputImage, TOutputImage> { public: /** Standard class typedefs. */ @@ -55,7 +58,6 @@ public: typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; - /** Run-time type information (and related methods). */ itkTypeMacro(LabelMapFilter,ImageToImageFilter); @@ -77,10 +79,8 @@ public: typedef typename OutputImageType::PixelType OutputImagePixelType; /** ImageDimension constants */ - itkStaticConstMacro(InputImageDimension, unsigned int, - TInputImage::ImageDimension); - itkStaticConstMacro(OutputImageDimension, unsigned int, - TOutputImage::ImageDimension); + itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, TOutputImage::ImageDimension); /** LabelMapFilter requires the entire input to be * available. Thus, it needs to provide an implementation of @@ -113,11 +113,14 @@ protected: typename FastMutexLock::Pointer m_LabelObjectContainerLock; + typedef typename InputImageType::LabelObjectContainerType LabelObjectContainerType; + typedef typename LabelObjectContainerType::const_iterator LabelObjectContainerConstIterator; + private: LabelMapFilter(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented - typename InputImageType::LabelObjectContainerType::const_iterator m_LabelObjectIterator; + LabelObjectContainerConstIterator m_LabelObjectIterator; ProgressReporter * m_Progress; diff --git a/Utilities/ITK/Code/Review/itkLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkLabelMapFilter.txx index 24f570568f78c1ecc297ee0fa565aaabc8658d00..31deede885cb217a8b08f9bcd1bb28f6bc975bbb 100644 --- a/Utilities/ITK/Code/Review/itkLabelMapFilter.txx +++ b/Utilities/ITK/Code/Review/itkLabelMapFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelMapFilter.txx,v $ Language: C++ - Date: $Date: 2009-05-16 22:19:31 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-07-23 22:22:04 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -26,9 +26,6 @@ namespace itk { -/** - * - */ template <class TInputImage, class TOutputImage> LabelMapFilter<TInputImage, TOutputImage> ::LabelMapFilter() @@ -36,9 +33,6 @@ LabelMapFilter<TInputImage, TOutputImage> m_Progress = NULL; } -/** - * - */ template <class TInputImage, class TOutputImage> LabelMapFilter<TInputImage, TOutputImage> ::~LabelMapFilter() @@ -74,8 +68,7 @@ void LabelMapFilter<TInputImage, TOutputImage> ::EnlargeOutputRequestedRegion(DataObject *) { - this->GetOutput() - ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); + this->GetOutput()->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); } diff --git a/Utilities/ITK/Code/Review/itkLabelMapToBinaryImageFilter.h b/Utilities/ITK/Code/Review/itkLabelMapToBinaryImageFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..8e818d29a4e58cb6db2730b4b28219d65380193f --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelMapToBinaryImageFilter.h @@ -0,0 +1,154 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelMapToBinaryImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-07 11:28:02 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelMapToBinaryImageFilter_h +#define __itkLabelMapToBinaryImageFilter_h + +#include "itkLabelMapFilter.h" +#include "itkBarrier.h" + +namespace itk { + +/** \class LabelMapToBinaryImageFilter + * \brief Convert a LabelMap to a binary image. + * + * LabelMapToBinaryImageFilter to a binary image. All the objects in the image + * are used as foreground. The background values of the original binary image + * can be restored by passing this image to the filter with the + * SetBackgroundImage() method. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, + * INRA de Jouy-en-Josas, France. + * + * \sa LabelMapToLabelImageFilter, LabelMapMaskImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TInputImage, class TOutputImage> +class ITK_EXPORT LabelMapToBinaryImageFilter : + public LabelMapFilter<TInputImage, TOutputImage> +{ +public: + /** Standard class typedefs. */ + typedef LabelMapToBinaryImageFilter Self; + typedef LabelMapFilter<TInputImage, TOutputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef TOutputImage OutputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename InputImageType::LabelObjectType LabelObjectType; + + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::ConstPointer OutputImageConstPointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + typedef typename OutputImageType::IndexType IndexType; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, TOutputImage::ImageDimension); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(LabelMapToBinaryImageFilter, ImageToImageFilter); + + /** + * Set/Get the value used as "background" in the output image. + * Defaults to NumericTraits<PixelType>::NonpositiveMin(). + */ + itkSetMacro(BackgroundValue, OutputImagePixelType); + itkGetConstMacro(BackgroundValue, OutputImagePixelType); + + /** + * Set/Get the value used as "foreground" in the output image. + * Defaults to NumericTraits<PixelType>::max(). + */ + itkSetMacro(ForegroundValue, OutputImagePixelType); + itkGetConstMacro(ForegroundValue, OutputImagePixelType); + + /** Set/Get the background image top be used to restore the background values */ + void SetBackgroundImage( const OutputImageType *input) + { + // Process object is not const-correct so the const casting is required. + this->SetNthInput( 1, const_cast<OutputImageType *>(input) ); + } + + OutputImageType * GetBackgroundImage() + { + return static_cast<OutputImageType*>(const_cast<DataObject *>(this->ProcessObject::GetInput(1))); + } + + /** Set the input image */ + void SetInput1( const InputImageType * input ) + { + this->SetInput( input ); + } + + /** Set the marker image */ + void SetInput2( const OutputImageType * input ) + { + this->SetBackgroundImage( input ); + } + +protected: + LabelMapToBinaryImageFilter(); + ~LabelMapToBinaryImageFilter() {}; + + /** LabelMapToBinaryImageFilter needs the entire input be + * available. Thus, it needs to provide an implementation of + * GenerateInputRequestedRegion(). */ + void GenerateInputRequestedRegion(); + + /** LabelMapToBinaryImageFilter will produce the entire output. */ + void EnlargeOutputRequestedRegion(DataObject *itkNotUsed(output)); + + virtual void BeforeThreadedGenerateData(); + + virtual void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ); + + virtual void ThreadedProcessLabelObject( LabelObjectType * labelObject ); + + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + LabelMapToBinaryImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + OutputImagePixelType m_BackgroundValue; + OutputImagePixelType m_ForegroundValue; + + typename Barrier::Pointer m_Barrier; + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkLabelMapToBinaryImageFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelMapToBinaryImageFilter.txx b/Utilities/ITK/Code/Review/itkLabelMapToBinaryImageFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..be10344780cb865af47b87a69583e8e997cca6d7 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelMapToBinaryImageFilter.txx @@ -0,0 +1,188 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelMapToBinaryImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-07 11:28:02 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelMapToBinaryImageFilter_txx +#define __itkLabelMapToBinaryImageFilter_txx + +#include "itkLabelMapToBinaryImageFilter.h" +#include "itkNumericTraits.h" +#include "itkProgressReporter.h" +#include "itkImageRegionConstIterator.h" +#include "itkImageRegionIterator.h" + +namespace itk { + +template <class TInputImage, class TOutputImage> +LabelMapToBinaryImageFilter<TInputImage, TOutputImage> +::LabelMapToBinaryImageFilter() +{ + this->m_BackgroundValue = NumericTraits<OutputImagePixelType>::NonpositiveMin(); + this->m_ForegroundValue = NumericTraits<OutputImagePixelType>::max(); +} + +template <class TInputImage, class TOutputImage> +void +LabelMapToBinaryImageFilter<TInputImage, TOutputImage> +::GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // We need all the input. + InputImagePointer input = const_cast<InputImageType *>(this->GetInput()); + + if( input ) + { + input->SetRequestedRegion( input->GetLargestPossibleRegion() ); + } +} + + +template <class TInputImage, class TOutputImage> +void +LabelMapToBinaryImageFilter<TInputImage, TOutputImage> +::EnlargeOutputRequestedRegion(DataObject *) +{ + this->GetOutput()->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); +} + + +template<class TInputImage, class TOutputImage> +void +LabelMapToBinaryImageFilter<TInputImage, TOutputImage> +::BeforeThreadedGenerateData() +{ + unsigned long numberOfThreads = this->GetNumberOfThreads(); + if( itk::MultiThreader::GetGlobalMaximumNumberOfThreads() != 0 ) + { + numberOfThreads = vnl_math_min( + this->GetNumberOfThreads(), itk::MultiThreader::GetGlobalMaximumNumberOfThreads() ); + } + + // number of threads can be constrained by the region size, so call the + // SplitRequestedRegion to get the real number of threads which will be used + typename TOutputImage::RegionType splitRegion; // dummy region - just to call the following method + + numberOfThreads = this->SplitRequestedRegion(0, numberOfThreads, splitRegion); + + m_Barrier = Barrier::New(); + + m_Barrier->Initialize( numberOfThreads ); + + this->Superclass::BeforeThreadedGenerateData(); +} + + +template<class TInputImage, class TOutputImage> +void +LabelMapToBinaryImageFilter<TInputImage, TOutputImage> +::ThreadedGenerateData( const OutputImageRegionType& outputRegionForThread, int threadId ) +{ + OutputImageType * output = this->GetOutput(); + + // fill the output with background value - they will be overridden with the + // foreground value later, if there is some objects + if( this->GetNumberOfInputs() == 2 ) + { + // fill the background with the background values from the background image + ImageRegionConstIterator< OutputImageType > bgIt( this->GetBackgroundImage(), outputRegionForThread ); + ImageRegionIterator< OutputImageType > oIt( output, outputRegionForThread ); + + bgIt.GoToBegin(); + oIt.GoToBegin(); + + while( !oIt.IsAtEnd() ) + { + const OutputImagePixelType & bg = bgIt.Get(); + if( bg != this->m_ForegroundValue ) + { + oIt.Set( bg ); + } + else + { + oIt.Set( this->m_BackgroundValue ); + } + ++oIt; + ++bgIt; + } + } + else + { + // fill the background with the background value + ImageRegionIterator< OutputImageType > oIt( output, outputRegionForThread ); + oIt.GoToBegin(); + + while( !oIt.IsAtEnd() ) + { + oIt.Set( this->m_BackgroundValue ); + ++oIt; + } + } + + // wait for the other threads to complete that part + this->m_Barrier->Wait(); + + // and delegate to the superclass implementation to use the thread support for the label objects + this->Superclass::ThreadedGenerateData( outputRegionForThread, threadId ); + +} + + +template<class TInputImage, class TOutputImage> +void +LabelMapToBinaryImageFilter<TInputImage, TOutputImage> +::ThreadedProcessLabelObject( LabelObjectType * labelObject ) +{ + OutputImageType * output = this->GetOutput(); + + typedef typename LabelObjectType::LineContainerType LineContainerType; + + typename LineContainerType::const_iterator lit; + LineContainerType & lineContainer = labelObject->GetLineContainer(); + + for( lit = lineContainer.begin(); lit != lineContainer.end(); lit++ ) + { + IndexType idx = lit->GetIndex(); + + unsigned long length = lit->GetLength(); + + for( unsigned int i=0; i<length; i++) + { + output->SetPixel( idx, this->m_ForegroundValue ); + idx[0]++; + } + } +} + + +template< class TInputImage, class TOutputImage > +void +LabelMapToBinaryImageFilter<TInputImage, TOutputImage> +::PrintSelf(std::ostream& os, Indent indent) const +{ + this->Superclass::PrintSelf(os,indent); + + os << indent << "ForegroundValue: " + << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(this->m_ForegroundValue) << std::endl; + os << indent << "BackgroundValue: " + << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(this->m_BackgroundValue) << std::endl; + os << indent << "Barrier object: " << this->m_Barrier.GetPointer() << std::endl; +} + + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelMapToLabelImageFilter.h b/Utilities/ITK/Code/Review/itkLabelMapToLabelImageFilter.h index 377a2edbea60dd110a5469e17f62eed8c58c36f4..4da1bfdf850964793d1cc3c3afe79b2fb4cce539 100644 --- a/Utilities/ITK/Code/Review/itkLabelMapToLabelImageFilter.h +++ b/Utilities/ITK/Code/Review/itkLabelMapToLabelImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelMapToLabelImageFilter.h,v $ Language: C++ - Date: $Date: 2009-05-16 22:19:31 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-07-30 22:54:24 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,7 +22,7 @@ namespace itk { /** \class LabelMapToLabelImageFilter - * \brief Convert a LabelMap to a labeled image + * \brief Converts a LabelMap to a labeled image. * * LabelMapToBinaryImageFilter to a label image. * @@ -63,17 +63,14 @@ public: typedef typename OutputImageType::IndexType IndexType; /** ImageDimension constants */ - itkStaticConstMacro(InputImageDimension, unsigned int, - TInputImage::ImageDimension); - itkStaticConstMacro(OutputImageDimension, unsigned int, - TOutputImage::ImageDimension); + itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, TOutputImage::ImageDimension); /** Standard New method. */ itkNewMacro(Self); /** Runtime information support. */ - itkTypeMacro(LabelMapToLabelImageFilter, - ImageToImageFilter); + itkTypeMacro(LabelMapToLabelImageFilter, ImageToImageFilter); protected: LabelMapToLabelImageFilter(); diff --git a/Utilities/ITK/Code/Review/itkLabelObject.h b/Utilities/ITK/Code/Review/itkLabelObject.h index 57d79dc91147a33f05f9e027bb7b261dc5760af6..573ac1e729bcc4c80206e101f57e9173fca573f6 100644 --- a/Utilities/ITK/Code/Review/itkLabelObject.h +++ b/Utilities/ITK/Code/Review/itkLabelObject.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelObject.h,v $ Language: C++ - Date: $Date: 2009-05-23 19:04:36 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-08-06 18:07:04 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -27,7 +27,7 @@ namespace itk { /** \class LabelObject - * \brief The base class for the representation of an labeled binary object in an image + * \brief The base class for the representation of an labeled binary object in an image. * * LabelObject is the base class to represent a labeled object in an image. * It should be used associated with the LabelMap. @@ -77,11 +77,9 @@ public: typedef typename LineType::LengthType LengthType; typedef typename std::deque< LineType > LineContainerType; typedef unsigned int AttributeType; + typedef unsigned long SizeValueType; - enum - { - LABEL = 0 - }; + itkStaticConstMacro(LABEL, AttributeType, 0); static AttributeType GetAttributeFromName( const std::string & s ); static std::string GetNameFromAttribute( const AttributeType & a ); @@ -121,15 +119,17 @@ public: void SetLineContainer( const LineContainerType & lineContainer ); - int GetNumberOfLines() const; + SizeValueType GetNumberOfLines() const; - const LineType & GetLine( int i ) const; + const LineType & GetLine( SizeValueType i ) const; - LineType & GetLine( int i ); + LineType & GetLine( SizeValueType i ); - int Size() const; + SizeValueType Size() const; + + bool Empty() const; - IndexType GetIndex( int offset ) const; + IndexType GetIndex( SizeValueType offset ) const; /** Copy the attributes of another node to this one */ virtual void CopyAttributesFrom( const Self * src ); diff --git a/Utilities/ITK/Code/Review/itkLabelObject.txx b/Utilities/ITK/Code/Review/itkLabelObject.txx index 1ae75e654ba9bde3eeb93b0c13eb52a667469b1f..9c41a2dc93cfdf5a22d70ecae8566ea6c86507be 100644 --- a/Utilities/ITK/Code/Review/itkLabelObject.txx +++ b/Utilities/ITK/Code/Review/itkLabelObject.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelObject.txx,v $ Language: C++ - Date: $Date: 2009-05-23 23:52:55 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-08-10 16:38:36 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -41,7 +41,7 @@ LabelObject<TLabel, VImageDimension>::GetAttributeFromName( const std::string & return LABEL; } // can't recognize the name - throw std::runtime_error("Unknown attribute."); + itkGenericExceptionMacro(<< "Unknown attribute: " << s); } template < class TLabel, unsigned int VImageDimension > @@ -53,10 +53,9 @@ LabelObject<TLabel, VImageDimension> { case LABEL: return "Label"; - break; } // can't recognize the namespace - throw std::runtime_error("Unknown attribute."); + itkGenericExceptionMacro(<< "Unknown attribute: " << a); } /** @@ -170,7 +169,7 @@ LabelObject<TLabel, VImageDimension>::SetLineContainer( const LineContainerType } template < class TLabel, unsigned int VImageDimension > -int +typename LabelObject<TLabel, VImageDimension>::SizeValueType LabelObject<TLabel, VImageDimension>::GetNumberOfLines() const { return m_LineContainer.size(); @@ -179,20 +178,20 @@ LabelObject<TLabel, VImageDimension>::GetNumberOfLines() const template < class TLabel, unsigned int VImageDimension > const typename LabelObject<TLabel, VImageDimension>::LineType & -LabelObject<TLabel, VImageDimension>::GetLine( int i ) const +LabelObject<TLabel, VImageDimension>::GetLine( SizeValueType i ) const { return m_LineContainer[i]; } template < class TLabel, unsigned int VImageDimension > typename LabelObject<TLabel, VImageDimension>::LineType & -LabelObject<TLabel, VImageDimension>::GetLine( int i ) +LabelObject<TLabel, VImageDimension>::GetLine( SizeValueType i ) { return m_LineContainer[i]; } template < class TLabel, unsigned int VImageDimension > -int +typename LabelObject<TLabel, VImageDimension>::SizeValueType LabelObject<TLabel, VImageDimension>::Size() const { int size = 0; @@ -204,18 +203,27 @@ LabelObject<TLabel, VImageDimension>::Size() const } return size; } - + +template < class TLabel, unsigned int VImageDimension > +bool +LabelObject<TLabel, VImageDimension>::Empty() const +{ + return this->m_LineContainer.empty(); +} + template < class TLabel, unsigned int VImageDimension > typename LabelObject<TLabel, VImageDimension>::IndexType -LabelObject<TLabel, VImageDimension>::GetIndex( int offset ) const +LabelObject<TLabel, VImageDimension>::GetIndex( SizeValueType offset ) const { - int o = offset; - for( typename LineContainerType::const_iterator it=m_LineContainer.begin(); - it != m_LineContainer.end(); - it++ ) + SizeValueType o = offset; + + typename LineContainerType::const_iterator it = this->m_LineContainer.begin(); + + while( it != m_LineContainer.end() ) { - int size = it->GetLength(); - if( o > size) + SizeValueType size = it->GetLength(); + + if( o >= size) { o -= size; } @@ -225,6 +233,8 @@ LabelObject<TLabel, VImageDimension>::GetIndex( int offset ) const idx[0] += o; return idx; } + + it++; } itkGenericExceptionMacro(<< "Invalid offset: " << offset); } @@ -235,7 +245,8 @@ void LabelObject<TLabel, VImageDimension>::CopyAttributesFrom( const Self * src ) { itkAssertOrThrowMacro ( (src != NULL), "Null Pointer" ); - // nothing to do here - this class has no attribute + m_Label = src->m_Label; + } /** Copy the lines, the label and the attributes from another node. */ @@ -245,7 +256,6 @@ LabelObject<TLabel, VImageDimension>::CopyAllFrom( const Self * src ) { itkAssertOrThrowMacro ( (src != NULL), "Null Pointer" ); m_LineContainer = src->m_LineContainer; - m_Label = src->m_Label; // also copy the attributes this->CopyAttributesFrom( src ); } @@ -272,9 +282,9 @@ LabelObject<TLabel, VImageDimension>::Optimize() IndexType currentIdx = lineContainer.begin()->GetIndex(); long int currentLength = lineContainer.begin()->GetLength(); - for( typename LineContainerType::const_iterator it=lineContainer.begin(); - it != lineContainer.end(); - it++ ) + typename LineContainerType::const_iterator it = lineContainer.begin(); + + while( it != lineContainer.end() ) { const LineType & line = *it; IndexType idx = line.GetIndex(); @@ -300,15 +310,15 @@ LabelObject<TLabel, VImageDimension>::Optimize() else { // add the previous line to the new line container and use the new line index and size - // std::cout << currentIdx << " " << currentLength << std::endl; this->AddLine( currentIdx, currentLength ); currentIdx = idx; currentLength = length; } - // std::cout << line.GetIndex() << " " << line.GetLength() << std::endl; + + it++; } + // complete the last line - // std::cout << currentIdx << " " << currentLength << std::endl; this->AddLine( currentIdx, currentLength ); } } diff --git a/Utilities/ITK/Code/Review/itkLabelObjectAccessors.h b/Utilities/ITK/Code/Review/itkLabelObjectAccessors.h new file mode 100644 index 0000000000000000000000000000000000000000..e7783d9577961ed915a758136ccd5d10b5af29b4 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelObjectAccessors.h @@ -0,0 +1,98 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelObjectAccessors.h,v $ + Language: C++ + Date: $Date: 2009-08-12 12:57:42 $ + Version: $Revision: 1.6 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelObjectAccessors_h +#define __itkLabelObjectAccessors_h + + +namespace itk +{ + + +namespace Functor +{ + +template< class TLabelObject > +class ITK_EXPORT LabelLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef typename LabelObjectType::LabelType AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetLabel(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT NumberOfLinesLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef int AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetNumberOfLines(); + } +}; + +template< class TLabelObject, class TAttributeAccessor > +class LabelObjectComparator +{ +public: + typedef TLabelObject LabelObjectType; + typedef TAttributeAccessor AttributeAccessorType; + bool operator()( const LabelObjectType * a, const LabelObjectType * b ) const + { + return m_Accessor( a ) > m_Accessor( b ); + } + LabelObjectComparator() {} + LabelObjectComparator(LabelObjectComparator const& from) + { + m_Accessor = from.m_Accessor; + } +private: + AttributeAccessorType m_Accessor; +}; + +template< class TLabelObject, class TAttributeAccessor > +class LabelObjectReverseComparator +{ +public: + typedef TLabelObject LabelObjectType; + typedef TAttributeAccessor AttributeAccessorType; + bool operator()( const LabelObjectType * a, const LabelObjectType * b ) const + { + return m_Accessor( a ) < m_Accessor( b ); + } + + LabelObjectReverseComparator() {} + LabelObjectReverseComparator(LabelObjectReverseComparator const& from) + { + m_Accessor = from.m_Accessor; + } +private: + AttributeAccessorType m_Accessor; +}; + +} + + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelObjectLine.h b/Utilities/ITK/Code/Review/itkLabelObjectLine.h index 85c81dd0e36fe97fb772a9ae7d37598a532b4ec6..7bdbdb1eb574fb36aa9a49d055c4c7506bafd1be 100644 --- a/Utilities/ITK/Code/Review/itkLabelObjectLine.h +++ b/Utilities/ITK/Code/Review/itkLabelObjectLine.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelObjectLine.h,v $ Language: C++ - Date: $Date: 2009-05-13 19:05:59 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-07-07 17:47:10 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -50,23 +50,21 @@ public: virtual ~LabelObjectLine() {}; LabelObjectLine( const IndexType & idx, const LengthType & length ); - // - // Set/Get Index - // + /** + * Set/Get Index + */ void SetIndex( const IndexType & idx ); - IndexType & GetIndex(); const IndexType & GetIndex() const; - // - // SetGet Length - // + /** + * SetGet Length + */ void SetLength( const LengthType length ); - LengthType & GetLength(); const LengthType & GetLength() const; - // - // Check for index - // + /** + * Check for index + */ bool HasIndex( const IndexType idx ) const; bool IsNextIndex( const IndexType & idx ) const; diff --git a/Utilities/ITK/Code/Review/itkLabelObjectLine.txx b/Utilities/ITK/Code/Review/itkLabelObjectLine.txx index 230f1bb826f10a6261e8cd4228f6ee9c2bf1a3dd..190e6d25cd60b41a8bd5db741a815c43f9dca94e 100644 --- a/Utilities/ITK/Code/Review/itkLabelObjectLine.txx +++ b/Utilities/ITK/Code/Review/itkLabelObjectLine.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelObjectLine.txx,v $ Language: C++ - Date: $Date: 2009-05-13 14:48:22 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-07-07 17:47:10 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -36,13 +36,6 @@ void LabelObjectLine<VImageDimension>::SetIndex( const IndexType & idx ) m_Index = idx; } -template < unsigned int VImageDimension > -typename LabelObjectLine<VImageDimension>::IndexType & -LabelObjectLine<VImageDimension>::GetIndex() -{ - return m_Index; -} - template < unsigned int VImageDimension > const typename LabelObjectLine<VImageDimension>::IndexType & LabelObjectLine<VImageDimension>::GetIndex() const @@ -56,13 +49,6 @@ void LabelObjectLine<VImageDimension>::SetLength( const LengthType length ) m_Length = length; } -template < unsigned int VImageDimension > -typename LabelObjectLine<VImageDimension>::LengthType & -LabelObjectLine<VImageDimension>::GetLength() -{ - return m_Length; -} - template < unsigned int VImageDimension > const typename LabelObjectLine<VImageDimension>::LengthType & LabelObjectLine<VImageDimension>::GetLength() const diff --git a/Utilities/ITK/Code/Review/itkLabelOverlayFunctor.h b/Utilities/ITK/Code/Review/itkLabelOverlayFunctor.h index ce94614864488fe3db63b026000c08cc1794322d..72dce5b9f73e6f039e8671e27aef08435db8c00e 100644 --- a/Utilities/ITK/Code/Review/itkLabelOverlayFunctor.h +++ b/Utilities/ITK/Code/Review/itkLabelOverlayFunctor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelOverlayFunctor.h,v $ Language: C++ - Date: $Date: 2009-02-24 19:03:15 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-07-07 12:28:58 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -36,7 +36,7 @@ namespace Functor { * * \sa LabelOverlayImageFilter LabelToRGBFunctor * - **/ + */ template< class TInputPixel, class TLabel, class TRGBPixel > class LabelOverlayFunctor { @@ -96,6 +96,24 @@ public: m_RGBFunctor.SetBackgroundValue( v ); } + void ResetColors() + { + m_RGBFunctor.ResetColors(); + } + + unsigned int GetNumberOfColors() const + { + return m_RGBFunctor.GetNumberOfColors(); + } + + /** type of the color component */ + typedef typename TRGBPixel::ComponentType ComponentType; + + void AddColor( ComponentType r, ComponentType g, ComponentType b ) + { + m_RGBFunctor.AddColor( r, g, b ); + } + protected: private: diff --git a/Utilities/ITK/Code/Review/itkLabelOverlayImageFilter.h b/Utilities/ITK/Code/Review/itkLabelOverlayImageFilter.h index 749e813a5043deec2d207cbacc5f6dc3783eea79..80a584f66ab9e4825b71c5c7f687410c5bdad7c9 100644 --- a/Utilities/ITK/Code/Review/itkLabelOverlayImageFilter.h +++ b/Utilities/ITK/Code/Review/itkLabelOverlayImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelOverlayImageFilter.h,v $ Language: C++ - Date: $Date: 2008-02-07 15:58:06 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-07-07 12:27:33 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -110,6 +110,18 @@ public: typename OutputPixelType::ValueType>)); /** End concept checking */ #endif + + /** Empty the color LUT container */ + void ResetColors(); + + /** Get number of colors in the LUT container */ + unsigned int GetNumberOfColors() const; + + /** type of the color component */ + typedef typename OutputPixelType::ComponentType ComponentType; + + /** Add color to the LUT container */ + void AddColor( ComponentType r, ComponentType g, ComponentType b ); protected: LabelOverlayImageFilter(); diff --git a/Utilities/ITK/Code/Review/itkLabelOverlayImageFilter.txx b/Utilities/ITK/Code/Review/itkLabelOverlayImageFilter.txx index d14cfd59f1ce9200ebef6e0a6beba4059eb1878c..cb96323e9575c872100f27d2547f7af37b90b4c5 100644 --- a/Utilities/ITK/Code/Review/itkLabelOverlayImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkLabelOverlayImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelOverlayImageFilter.txx,v $ Language: C++ - Date: $Date: 2007-10-21 09:54:20 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-07-07 12:27:33 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -71,6 +71,41 @@ LabelOverlayImageFilter<TInputImage, TLabelImage, TOutputImage> const_cast<DataObject *>(this->ProcessObject::GetInput(1))); } +/** + * Get number of colors in the LUT container + */ +template <class TInputImage, class TLabelImage, class TOutputImage> +unsigned int +LabelOverlayImageFilter<TInputImage, TLabelImage, TOutputImage> +::GetNumberOfColors() const +{ + return this->GetFunctor().GetNumberOfColors(); +} + +/** + * Empty the color LUT container + */ +template <class TInputImage, class TLabelImage, class TOutputImage> +void +LabelOverlayImageFilter<TInputImage, TLabelImage, TOutputImage> +::ResetColors() +{ + this->GetFunctor().ResetColors(); +} + + +/** + * Add a color to the LUT container + */ +template <class TInputImage, class TLabelImage, class TOutputImage> +void +LabelOverlayImageFilter<TInputImage, TLabelImage, TOutputImage> +::AddColor( ComponentType r, ComponentType g, ComponentType b ) +{ + this->GetFunctor().AddColor( r, g, b ); +} + + /** * Standard PrintSelf method */ diff --git a/Utilities/ITK/Code/Review/itkLabelPerimeterEstimationCalculator.h b/Utilities/ITK/Code/Review/itkLabelPerimeterEstimationCalculator.h new file mode 100644 index 0000000000000000000000000000000000000000..418db256a9bd76dae050b61d2bd79d344ae23af9 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelPerimeterEstimationCalculator.h @@ -0,0 +1,140 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelPerimeterEstimationCalculator.h,v $ + Language: C++ + Date: $Date: 2009-07-30 18:25:06 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelPerimeterEstimationCalculator_h +#define __itkLabelPerimeterEstimationCalculator_h + +#include "itkObject.h" + +namespace itk { + +/** \class LabelPerimeterEstimationCalculator + * \brief Estimates the perimeter of a label object. + * + * The LabelPerimeterEstimationCalculator takes a label object and calculates + * an estimated perimeter based on pixels' and their neighbors. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * \sa + */ +template<class TInputImage> +class ITK_EXPORT LabelPerimeterEstimationCalculator : + public Object +{ +public: + /** Standard class typedefs. */ + typedef LabelPerimeterEstimationCalculator Self; + typedef Object Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + + typedef typename InputImageType::RegionType RegionType; + typedef typename InputImageType::SizeType SizeType; + typedef typename InputImageType::IndexType IndexType; + + typedef typename std::map< InputImagePixelType, double > PerimetersType; + + /** ImageDimension constants */ + itkStaticConstMacro(ImageDimension, unsigned int, TInputImage::ImageDimension); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(LabelPerimeterEstimationCalculator, Object); + + /** + * Set/Get whether the connected components are defined strictly by + * face connectivity or by face+edge+vertex connectivity. Default is + * FullyConnectedOff. For objects that are 1 pixel wide, use + * FullyConnectedOn. + */ + itkSetMacro(FullyConnected, bool); + itkGetConstReferenceMacro(FullyConnected, bool); + itkBooleanMacro(FullyConnected); + + void SetImage( const InputImageType * img ) + { + m_Image = img; + } + + const InputImageType * GetImage() const + { + return m_Image; + } + + void Compute(); + + const PerimetersType & GetPerimeters() const + { + return m_Perimeters; + } + + const double & GetPerimeter( const InputImagePixelType & label ) const + { + if( m_Perimeters.find( label ) != m_Perimeters.end() ) + { + return m_Perimeters.find( label )->second; + } + itkExceptionMacro( << "Unknown label: " << static_cast<typename NumericTraits<InputImagePixelType>::PrintType>(label) ); + } + + bool HasLabel( const InputImagePixelType & label ) const + { + if( m_Perimeters.find( label ) != m_Perimeters.end() ) + { + return true; + } + return false; + } + +protected: + LabelPerimeterEstimationCalculator(); + ~LabelPerimeterEstimationCalculator() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + + +private: + LabelPerimeterEstimationCalculator(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + bool m_FullyConnected; + + const InputImageType * m_Image; + + PerimetersType m_Perimeters; + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkLabelPerimeterEstimationCalculator.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelPerimeterEstimationCalculator.txx b/Utilities/ITK/Code/Review/itkLabelPerimeterEstimationCalculator.txx new file mode 100644 index 0000000000000000000000000000000000000000..5ded1d4043162143a979331bb96270fbc7a95896 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelPerimeterEstimationCalculator.txx @@ -0,0 +1,225 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelPerimeterEstimationCalculator.txx,v $ + Language: C++ + Date: $Date: 2009-07-30 18:25:06 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelPerimeterEstimationCalculator_txx +#define __itkLabelPerimeterEstimationCalculator_txx + +#include "itkLabelPerimeterEstimationCalculator.h" +#include "itkProgressReporter.h" +#include "itkImageRegionIterator.h" +#include "itkImageRegionConstIteratorWithIndex.h" +#include "itkShapedNeighborhoodIterator.h" +#include "itkConstShapedNeighborhoodIterator.h" +#include "itkConstantBoundaryCondition.h" +#include "itkSize.h" +#include "itkConnectedComponentAlgorithm.h" +#include <set> + +namespace itk { + +template <class TInputImage> +LabelPerimeterEstimationCalculator<TInputImage> +::LabelPerimeterEstimationCalculator() +{ + m_FullyConnected = false; +} + + +template<class TInputImage> +void +LabelPerimeterEstimationCalculator<TInputImage> +::Compute() +{ + + m_Perimeters.clear(); + + // ProgressReporter progress( this, 0, this->GetImage()->GetRequestedRegion().GetNumberOfPixels() ); + + // reduce the region to avoid reading outside + RegionType region = this->GetImage()->GetRequestedRegion(); + SizeType size = region.GetSize(); + for( int i=0; i<ImageDimension; i++ ) + { + size[i]--; + } + region.SetSize( size ); + + // the radius which will be used for all the shaped iterators + Size< ImageDimension > radius; + radius.Fill(1); + + // set up the iterator + typedef ConstShapedNeighborhoodIterator<InputImageType> IteratorType; + typename IteratorType::ConstIterator nIt; + IteratorType iIt( radius, this->GetImage(), region ); + // we want to search the neighbors with offset >= 0 + // 2D -> 4 neighbors + // 3D -> 8 neighbors + typename IteratorType::OffsetType offset; + unsigned int centerIndex = iIt.GetCenterNeighborhoodIndex(); + // store the offsets to reuse them to evaluate the contributions of the + // configurations + typename std::vector< IndexType > indexes; + IndexType idx0; + idx0.Fill( 0 ); + for( unsigned int d=centerIndex; d < 2*centerIndex+1; d++ ) + { + offset = iIt.GetOffset( d ); + bool deactivate = false; + for ( int j=0; j<ImageDimension && !deactivate; j++ ) + { + if( offset[j] < 0 ) + { + deactivate = true; + } + } + if( deactivate ) + { + iIt.DeactivateOffset( offset ); + } + else + { + iIt.ActivateOffset( offset ); + indexes.push_back( idx0 + offset ); + } + + } + + // to store the configurations count for all the labels + typedef typename std::map< unsigned long, unsigned long > MapType; + typedef typename std::map< InputImagePixelType, MapType > LabelMapType; + LabelMapType confCount; + + for( iIt.GoToBegin(); !iIt.IsAtEnd(); ++iIt ) + { + // 2 pass - find the labels in the neighborhood + // - count the configurations for all the labels + + typedef typename std::set< InputImagePixelType > LabelSetType; + LabelSetType labelSet; + for ( nIt= iIt.Begin(); + nIt != iIt.End(); + nIt++ ) + { + labelSet.insert( nIt.Get() ); + } + + for( typename LabelSetType::const_iterator it = labelSet.begin(); + it != labelSet.end(); + it++ ) + { + + unsigned long conf = 0; + int i=0; + + for ( nIt= iIt.Begin(); + nIt != iIt.End(); + nIt++, i++ ) + { + if( nIt.Get() == *it ) + { + conf += 1 << i; + } + } + + confCount[ *it ][ conf ]++; + + } + + // progress.CompletedPixel(); + + } + + // compute the participation to the perimeter for all the configurations + double physicalSize = 1; + for( int i=0; i<ImageDimension; i++ ) + { + physicalSize *= this->GetImage()->GetSpacing()[i]; + } + typedef typename std::map< unsigned long, double > ContributionMapType; + ContributionMapType contributions; + int numberOfNeighbors = (int)vcl_pow( 2.0, ImageDimension ); + int numberOfConfigurations = (int)vcl_pow( 2.0, numberOfNeighbors ); + // create an image to store the neighbors + typedef typename itk::Image< bool, ImageDimension > ImageType; + typename ImageType::Pointer neighborsImage = ImageType::New(); + // typename ImageType::SizeType size; + size.Fill( 2 ); + neighborsImage->SetRegions( size ); + neighborsImage->Allocate(); + for( int i=0; i<numberOfConfigurations; i++ ) + { + neighborsImage->FillBuffer( false ); + for( int j=0; j<numberOfNeighbors; j++ ) + { + if( i & 1 << j ) + { + neighborsImage->SetPixel( indexes[ j ], true ); + } + } + // the image is created - we can now compute the contributions of the pixels + // for that configuration + contributions[i] = 0; + for( int j=0; j<numberOfNeighbors; j++ ) + { + IndexType currentIdx = indexes[j]; + if( neighborsImage->GetPixel( currentIdx ) ) + { + for( int k=0; k<ImageDimension; k++ ) + { + IndexType idx = currentIdx; + idx[k] = vcl_abs( idx[k] - 1 ); + if( !neighborsImage->GetPixel( idx ) ) + { + contributions[i] += physicalSize / this->GetImage()->GetSpacing()[k] / 2.0; + } + } + } + } + contributions[i] /= ImageDimension; + } + + + // and use those contributions to found the perimeter + m_Perimeters.clear(); + for( typename LabelMapType::const_iterator it = confCount.begin(); + it != confCount.end(); + it++ ) + { + m_Perimeters[ it->first ] = 0; + for( typename MapType::const_iterator it2 = it->second.begin(); + it2 != it->second.end(); + it2++ ) + { + m_Perimeters[ it->first ] += contributions[ it2->first ] * it2->second; + } + } + +} + + +template<class TInputImage> +void +LabelPerimeterEstimationCalculator<TInputImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "FullyConnected: " << m_FullyConnected << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelShapeKeepNObjectsImageFilter.h b/Utilities/ITK/Code/Review/itkLabelShapeKeepNObjectsImageFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..1602abf53b6ce4809bdf47b82b3a28e9eebd873e --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelShapeKeepNObjectsImageFilter.h @@ -0,0 +1,172 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelShapeKeepNObjectsImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-08 01:21:23 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelShapeKeepNObjectsImageFilter_h +#define __itkLabelShapeKeepNObjectsImageFilter_h + +#include "itkImageToImageFilter.h" +#include "itkShapeLabelObject.h" +#include "itkLabelMap.h" +#include "itkLabelImageToLabelMapFilter.h" +#include "itkShapeLabelMapFilter.h" +#include "itkShapeKeepNObjectsLabelMapFilter.h" +#include "itkLabelMapToLabelImageFilter.h" + + +namespace itk { + +/** \class LabelShapeKeepNObjectsImageFilter + * \brief keep N objects according to their shape attributes + * + * LabelShapeKeepNObjectsImageFilter keep the N objects in a labeled image + * with the highest (or lowest) attribute value. The attributes are the ones + * of the ShapeLabelObject. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \sa ShapeLabelObject, BinaryShapeKeepNObjectsImageFilter, LabelStatisticsKeepNObjectsImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TInputImage> +class ITK_EXPORT LabelShapeKeepNObjectsImageFilter : + public ImageToImageFilter<TInputImage, TInputImage> +{ +public: + /** Standard class typedefs. */ + typedef LabelShapeKeepNObjectsImageFilter Self; + typedef ImageToImageFilter<TInputImage, TInputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef TInputImage OutputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::ConstPointer OutputImageConstPointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(ImageDimension, unsigned int, + TInputImage::ImageDimension); + + typedef ShapeLabelObject<InputImagePixelType, itkGetStaticConstMacro(ImageDimension)> LabelObjectType; + typedef LabelMap< LabelObjectType > LabelMapType; + typedef LabelImageToLabelMapFilter< InputImageType, LabelMapType > LabelizerType; + typedef Image< typename OutputImageType::PixelType, itkGetStaticConstMacro(OutputImageDimension)> ShapeLabelFilterOutput; + typedef ShapeLabelMapFilter< LabelMapType, ShapeLabelFilterOutput > LabelObjectValuatorType; + typedef typename LabelObjectType::AttributeType AttributeType; + typedef ShapeKeepNObjectsLabelMapFilter< LabelMapType > KeepNObjectsType; + typedef LabelMapToLabelImageFilter< LabelMapType, OutputImageType > BinarizerType; + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(LabelShapeKeepNObjectsImageFilter, + ImageToImageFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>)); + /** End concept checking */ +#endif + + /** + * Set/Get the value used as "background" in the output image. + * Defaults to NumericTraits<PixelType>::NonpositiveMin(). + */ + itkSetMacro(BackgroundValue, OutputImagePixelType); + itkGetConstMacro(BackgroundValue, OutputImagePixelType); + + /** + * Set/Get the number of objects to keep + */ + itkGetConstMacro(NumberOfObjects, unsigned long); + itkSetMacro(NumberOfObjects, unsigned long); + + /** + * Set/Get the ordering of the objects. By default, the ones with the + * highest value are kept. Turming ReverseOrdering to true make this filter + * keep the objects with the smallest values + */ + itkGetConstMacro( ReverseOrdering, bool ); + itkSetMacro( ReverseOrdering, bool ); + itkBooleanMacro( ReverseOrdering ); + + /** + * Set/Get the attribute to use to select the object to keep. The default + * is "Size". + */ + itkGetConstMacro( Attribute, AttributeType ); + itkSetMacro( Attribute, AttributeType ); + void SetAttribute( const std::string & s ) + { + this->SetAttribute( LabelObjectType::GetAttributeFromName( s ) ); + } + + +protected: + LabelShapeKeepNObjectsImageFilter(); + ~LabelShapeKeepNObjectsImageFilter() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + + /** LabelShapeKeepNObjectsImageFilter needs the entire input be + * available. Thus, it needs to provide an implementation of + * GenerateInputRequestedRegion(). */ + void GenerateInputRequestedRegion(); + + /** LabelShapeKeepNObjectsImageFilter will produce the entire output. */ + void EnlargeOutputRequestedRegion(DataObject *itkNotUsed(output)); + + /** Single-threaded version of GenerateData. This filter delegates + * to GrayscaleGeodesicErodeImageFilter. */ + void GenerateData(); + +private: + LabelShapeKeepNObjectsImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + OutputImagePixelType m_BackgroundValue; + unsigned long m_NumberOfObjects; + bool m_ReverseOrdering; + AttributeType m_Attribute; +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkLabelShapeKeepNObjectsImageFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelShapeKeepNObjectsImageFilter.txx b/Utilities/ITK/Code/Review/itkLabelShapeKeepNObjectsImageFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..9d31bb121147fbaf085d937fa250a85f40c5b914 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelShapeKeepNObjectsImageFilter.txx @@ -0,0 +1,128 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelShapeKeepNObjectsImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-07 11:46:22 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelShapeKeepNObjectsImageFilter_txx +#define __itkLabelShapeKeepNObjectsImageFilter_txx + +#include "itkLabelShapeKeepNObjectsImageFilter.h" +#include "itkProgressAccumulator.h" + + +namespace itk { + +template<class TInputImage> +LabelShapeKeepNObjectsImageFilter<TInputImage> +::LabelShapeKeepNObjectsImageFilter() +{ + m_BackgroundValue = NumericTraits<OutputImagePixelType>::NonpositiveMin(); + m_NumberOfObjects = 1; + m_ReverseOrdering = false; + m_Attribute = LabelObjectType::SIZE; +} + +template<class TInputImage> +void +LabelShapeKeepNObjectsImageFilter<TInputImage> +::GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // We need all the input. + InputImagePointer input = const_cast<InputImageType *>(this->GetInput()); + if( input ) + { + input->SetRequestedRegion( input->GetLargestPossibleRegion() ); + } +} + + +template<class TInputImage> +void +LabelShapeKeepNObjectsImageFilter<TInputImage> +::EnlargeOutputRequestedRegion(DataObject *) +{ + this->GetOutput() + ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); +} + + +template<class TInputImage> +void +LabelShapeKeepNObjectsImageFilter<TInputImage> +::GenerateData() +{ + // Create a process accumulator for tracking the progress of this minipipeline + ProgressAccumulator::Pointer progress = ProgressAccumulator::New(); + progress->SetMiniPipelineFilter(this); + + // Allocate the output + this->AllocateOutputs(); + + typename LabelizerType::Pointer labelizer = LabelizerType::New(); + labelizer->SetInput( this->GetInput() ); + labelizer->SetBackgroundValue( m_BackgroundValue ); + labelizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(labelizer, .3f); + + typename LabelObjectValuatorType::Pointer valuator = LabelObjectValuatorType::New(); + valuator->SetInput( labelizer->GetOutput() ); + valuator->SetLabelImage( this->GetInput() ); + valuator->SetNumberOfThreads( this->GetNumberOfThreads() ); + if( m_Attribute == LabelObjectType::PERIMETER || m_Attribute == LabelObjectType::ROUNDNESS ) + { + valuator->SetComputePerimeter( true ); + } + if( m_Attribute == LabelObjectType::FERET_DIAMETER ) + { + valuator->SetComputeFeretDiameter( true ); + } + progress->RegisterInternalFilter(valuator, .3f); + + typename KeepNObjectsType::Pointer opening = KeepNObjectsType::New(); + opening->SetInput( valuator->GetOutput() ); + opening->SetNumberOfObjects( m_NumberOfObjects ); + opening->SetReverseOrdering( m_ReverseOrdering ); + opening->SetAttribute( m_Attribute ); + opening->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(opening, .2f); + + typename BinarizerType::Pointer binarizer = BinarizerType::New(); + binarizer->SetInput( opening->GetOutput() ); + binarizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(binarizer, .2f); + + binarizer->GraftOutput( this->GetOutput() ); + binarizer->Update(); + this->GraftOutput( binarizer->GetOutput() ); +} + + +template<class TInputImage> +void +LabelShapeKeepNObjectsImageFilter<TInputImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "BackgroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_BackgroundValue) << std::endl; + os << indent << "NumberOfObjects: " << m_NumberOfObjects << std::endl; + os << indent << "ReverseOrdering: " << m_ReverseOrdering << std::endl; + os << indent << "Attribute: " << LabelObjectType::GetNameFromAttribute(m_Attribute) << " (" << m_Attribute << ")" << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelShapeOpeningImageFilter.h b/Utilities/ITK/Code/Review/itkLabelShapeOpeningImageFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..cdf5e051426485d244b1bfcf3e54a665c4176ebe --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelShapeOpeningImageFilter.h @@ -0,0 +1,175 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelShapeOpeningImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-08 01:21:23 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelShapeOpeningImageFilter_h +#define __itkLabelShapeOpeningImageFilter_h + +#include "itkImageToImageFilter.h" +#include "itkShapeLabelObject.h" +#include "itkLabelMap.h" +#include "itkLabelImageToLabelMapFilter.h" +#include "itkShapeLabelMapFilter.h" +#include "itkShapeOpeningLabelMapFilter.h" +#include "itkLabelMapToLabelImageFilter.h" + + +namespace itk { + +/** \class LabelShapeOpeningImageFilter + * \brief remove the objects according to the value of their shape attribute + * + * LabelShapeOpeningImageFilter removes the objects in a labeled image + * with an attribute value smaller or greater than a threshold called Lambda. + * The attributes are the ones of the ShapeLabelObject. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \sa ShapeLabelObject, BinaryShapeOpeningImageFilter, LabelStatisticsOpeningImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TInputImage> +class ITK_EXPORT LabelShapeOpeningImageFilter : + public ImageToImageFilter<TInputImage, TInputImage> +{ +public: + /** Standard class typedefs. */ + typedef LabelShapeOpeningImageFilter Self; + typedef ImageToImageFilter<TInputImage, TInputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef TInputImage OutputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::ConstPointer OutputImageConstPointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(ImageDimension, unsigned int, + TInputImage::ImageDimension); + + typedef ShapeLabelObject<InputImagePixelType, itkGetStaticConstMacro(ImageDimension)> LabelObjectType; + typedef LabelMap< LabelObjectType > LabelMapType; + typedef LabelImageToLabelMapFilter< InputImageType, LabelMapType > LabelizerType; + typedef Image< typename OutputImageType::PixelType, itkGetStaticConstMacro(OutputImageDimension)> + ShapeLabelFilterOutput; + typedef ShapeLabelMapFilter< LabelMapType, ShapeLabelFilterOutput > LabelObjectValuatorType; + typedef typename LabelObjectType::AttributeType AttributeType; + typedef ShapeOpeningLabelMapFilter< LabelMapType > OpeningType; + typedef LabelMapToLabelImageFilter< LabelMapType, OutputImageType > BinarizerType; + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(LabelShapeOpeningImageFilter, + ImageToImageFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>)); + /** End concept checking */ +#endif + + /** + * Set/Get the value used as "background" in the output image. + * Defaults to NumericTraits<PixelType>::NonpositiveMin(). + */ + itkSetMacro(BackgroundValue, OutputImagePixelType); + itkGetConstMacro(BackgroundValue, OutputImagePixelType); + + /** + * Set/Get the threshold used to keep or remove the objects. + */ + itkGetConstMacro(Lambda, double); + itkSetMacro(Lambda, double); + + /** + * Set/Get the ordering of the objects. By default, the objects with + * an attribute value smaller than Lamba are removed. Turning ReverseOrdering + * to true make this filter remove the object with an attribute value greater + * than Lambda instead. + */ + itkGetConstMacro( ReverseOrdering, bool ); + itkSetMacro( ReverseOrdering, bool ); + itkBooleanMacro( ReverseOrdering ); + + /** + * Set/Get the attribute to use to select the object to remove. The default + * is "Size". + */ + itkGetConstMacro( Attribute, AttributeType ); + itkSetMacro( Attribute, AttributeType ); + void SetAttribute( const std::string & s ) + { + this->SetAttribute( LabelObjectType::GetAttributeFromName( s ) ); + } + + +protected: + LabelShapeOpeningImageFilter(); + ~LabelShapeOpeningImageFilter() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + + /** LabelShapeOpeningImageFilter needs the entire input be + * available. Thus, it needs to provide an implementation of + * GenerateInputRequestedRegion(). */ + void GenerateInputRequestedRegion(); + + /** LabelShapeOpeningImageFilter will produce the entire output. */ + void EnlargeOutputRequestedRegion(DataObject *itkNotUsed(output)); + + /** Single-threaded version of GenerateData. This filter delegates + * to GrayscaleGeodesicErodeImageFilter. */ + void GenerateData(); + + +private: + LabelShapeOpeningImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + OutputImagePixelType m_BackgroundValue; + double m_Lambda; + bool m_ReverseOrdering; + AttributeType m_Attribute; +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkLabelShapeOpeningImageFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelShapeOpeningImageFilter.txx b/Utilities/ITK/Code/Review/itkLabelShapeOpeningImageFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..6f1de36f8c621e63ac323f0908a2207c4a64e27e --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelShapeOpeningImageFilter.txx @@ -0,0 +1,128 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelShapeOpeningImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-07 11:52:11 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelShapeOpeningImageFilter_txx +#define __itkLabelShapeOpeningImageFilter_txx + +#include "itkLabelShapeOpeningImageFilter.h" +#include "itkProgressAccumulator.h" + + +namespace itk { + +template<class TInputImage> +LabelShapeOpeningImageFilter<TInputImage> +::LabelShapeOpeningImageFilter() +{ + m_BackgroundValue = NumericTraits<OutputImagePixelType>::NonpositiveMin(); + m_Lambda = NumericTraits< double >::Zero; + m_ReverseOrdering = false; + m_Attribute = LabelObjectType::SIZE; +} + +template<class TInputImage> +void +LabelShapeOpeningImageFilter<TInputImage> +::GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // We need all the input. + InputImagePointer input = const_cast<InputImageType *>(this->GetInput()); + if( input ) + { + input->SetRequestedRegion( input->GetLargestPossibleRegion() ); + } +} + + +template<class TInputImage> +void +LabelShapeOpeningImageFilter<TInputImage> +::EnlargeOutputRequestedRegion(DataObject *) +{ + this->GetOutput() + ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); +} + + +template<class TInputImage> +void +LabelShapeOpeningImageFilter<TInputImage> +::GenerateData() +{ + // Create a process accumulator for tracking the progress of this minipipeline + ProgressAccumulator::Pointer progress = ProgressAccumulator::New(); + progress->SetMiniPipelineFilter(this); + + // Allocate the output + this->AllocateOutputs(); + + typename LabelizerType::Pointer labelizer = LabelizerType::New(); + labelizer->SetInput( this->GetInput() ); + labelizer->SetBackgroundValue( m_BackgroundValue ); + labelizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(labelizer, .3f); + + typename LabelObjectValuatorType::Pointer valuator = LabelObjectValuatorType::New(); + valuator->SetInput( labelizer->GetOutput() ); + valuator->SetLabelImage( this->GetInput() ); + valuator->SetNumberOfThreads( this->GetNumberOfThreads() ); + if( m_Attribute == LabelObjectType::PERIMETER || m_Attribute == LabelObjectType::ROUNDNESS ) + { + valuator->SetComputePerimeter( true ); + } + if( m_Attribute == LabelObjectType::FERET_DIAMETER ) + { + valuator->SetComputeFeretDiameter( true ); + } + progress->RegisterInternalFilter(valuator, .3f); + + typename OpeningType::Pointer opening = OpeningType::New(); + opening->SetInput( valuator->GetOutput() ); + opening->SetLambda( m_Lambda ); + opening->SetReverseOrdering( m_ReverseOrdering ); + opening->SetAttribute( m_Attribute ); + opening->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(opening, .2f); + + typename BinarizerType::Pointer binarizer = BinarizerType::New(); + binarizer->SetInput( opening->GetOutput() ); + binarizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(binarizer, .2f); + + binarizer->GraftOutput( this->GetOutput() ); + binarizer->Update(); + this->GraftOutput( binarizer->GetOutput() ); +} + + +template<class TInputImage> +void +LabelShapeOpeningImageFilter<TInputImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "BackgroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_BackgroundValue) << std::endl; + os << indent << "Lambda: " << m_Lambda << std::endl; + os << indent << "ReverseOrdering: " << m_ReverseOrdering << std::endl; + os << indent << "Attribute: " << LabelObjectType::GetNameFromAttribute(m_Attribute) << " (" << m_Attribute << ")" << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelStatisticsKeepNObjectsImageFilter.h b/Utilities/ITK/Code/Review/itkLabelStatisticsKeepNObjectsImageFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..4afbff818e7ef3adf1f7b252b4469daa3de2d6f7 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelStatisticsKeepNObjectsImageFilter.h @@ -0,0 +1,201 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelStatisticsKeepNObjectsImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-11 14:24:43 $ + Version: $Revision: 1.4 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelStatisticsKeepNObjectsImageFilter_h +#define __itkLabelStatisticsKeepNObjectsImageFilter_h + +#include "itkImageToImageFilter.h" +#include "itkStatisticsLabelObject.h" +#include "itkLabelMap.h" +#include "itkLabelImageToLabelMapFilter.h" +#include "itkStatisticsLabelMapFilter.h" +#include "itkStatisticsKeepNObjectsLabelMapFilter.h" +#include "itkLabelMapToLabelImageFilter.h" + + +namespace itk { + +/** \class LabelStatisticsKeepNObjectsImageFilter + * \brief keep N objects according to their statistics attributes + * + * LabelStatisticsKeepNObjectsImageFilter keep the N objects in a labeled image + * with the highest (or lowest) attribute value. The attributes are the ones + * of the StatisticsLabelObject. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \sa StatisticsLabelObject, BinaryStatisticsKeepNObjectsImageFilter, LabelShapeKeepNObjectsImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TInputImage, class TFeatureImage> +class ITK_EXPORT LabelStatisticsKeepNObjectsImageFilter : + public ImageToImageFilter<TInputImage, TInputImage> +{ +public: + /** Standard class typedefs. */ + typedef LabelStatisticsKeepNObjectsImageFilter Self; + typedef ImageToImageFilter<TInputImage, TInputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef TInputImage OutputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::ConstPointer OutputImageConstPointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + + typedef TFeatureImage FeatureImageType; + typedef typename FeatureImageType::Pointer FeatureImagePointer; + typedef typename FeatureImageType::ConstPointer FeatureImageConstPointer; + typedef typename FeatureImageType::PixelType FeatureImagePixelType; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(ImageDimension, unsigned int, + TInputImage::ImageDimension); + + typedef StatisticsLabelObject<InputImagePixelType, itkGetStaticConstMacro(ImageDimension)> LabelObjectType; + typedef LabelMap< LabelObjectType > LabelMapType; + typedef LabelImageToLabelMapFilter< InputImageType, LabelMapType > LabelizerType; + typedef StatisticsLabelMapFilter< LabelMapType, TFeatureImage > LabelObjectValuatorType; + typedef typename LabelObjectType::AttributeType AttributeType; + typedef StatisticsKeepNObjectsLabelMapFilter< LabelMapType > KeepNObjectsType; + typedef LabelMapToLabelImageFilter< LabelMapType, OutputImageType > BinarizerType; + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(LabelStatisticsKeepNObjectsImageFilter, + ImageToImageFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>)); + /** End concept checking */ +#endif + + /** + * Set/Get the value used as "background" in the output image. + * Defaults to NumericTraits<PixelType>::NonpositiveMin(). + */ + itkSetMacro(BackgroundValue, OutputImagePixelType); + itkGetConstMacro(BackgroundValue, OutputImagePixelType); + + /** + * Set/Get the number of objects to keep + */ + itkGetConstMacro(NumberOfObjects, unsigned long); + itkSetMacro(NumberOfObjects, unsigned long); + + /** + * Set/Get the ordering of the objects. By default, the ones with the + * highest value are kept. Turming ReverseOrdering to true make this filter + * keep the objects with the smallest values + */ + itkGetConstMacro( ReverseOrdering, bool ); + itkSetMacro( ReverseOrdering, bool ); + itkBooleanMacro( ReverseOrdering ); + + /** + * Set/Get the attribute to use to select the object to keep. The default + * is "Mean". + */ + itkGetConstMacro( Attribute, AttributeType ); + itkSetMacro( Attribute, AttributeType ); + void SetAttribute( const std::string & s ) + { + this->SetAttribute( LabelObjectType::GetAttributeFromName( s ) ); + } + + /** Set the feature image */ + void SetFeatureImage(const TFeatureImage *input) + { + // Process object is not const-correct so the const casting is required. + this->SetNthInput( 1, const_cast<TFeatureImage *>(input) ); + } + + /** Get the feature image */ + const FeatureImageType * GetFeatureImage() + { + return static_cast<const FeatureImageType*>(this->ProcessObject::GetInput(1)); + } + + /** Set the input image */ + void SetInput1(const InputImageType *input) + { + this->SetInput( input ); + } + + /** Set the feature image */ + void SetInput2(const FeatureImageType *input) + { + this->SetFeatureImage( input ); + } + + +protected: + LabelStatisticsKeepNObjectsImageFilter(); + ~LabelStatisticsKeepNObjectsImageFilter() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + + /** LabelStatisticsKeepNObjectsImageFilter needs the entire input be + * available. Thus, it needs to provide an implementation of + * GenerateInputRequestedRegion(). */ + void GenerateInputRequestedRegion(); + + /** LabelStatisticsKeepNObjectsImageFilter will produce the entire output. */ + void EnlargeOutputRequestedRegion(DataObject *itkNotUsed(output)); + + /** Single-threaded version of GenerateData. This filter delegates + * to GrayscaleGeodesicErodeImageFilter. */ + void GenerateData(); + +private: + LabelStatisticsKeepNObjectsImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + OutputImagePixelType m_BackgroundValue; + unsigned long m_NumberOfObjects; + bool m_ReverseOrdering; + AttributeType m_Attribute; +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkLabelStatisticsKeepNObjectsImageFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelStatisticsKeepNObjectsImageFilter.txx b/Utilities/ITK/Code/Review/itkLabelStatisticsKeepNObjectsImageFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..9d83e9d8184c1e495a656261e11bd26ef7f6ae04 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelStatisticsKeepNObjectsImageFilter.txx @@ -0,0 +1,131 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelStatisticsKeepNObjectsImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-07 12:18:38 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelStatisticsKeepNObjectsImageFilter_txx +#define __itkLabelStatisticsKeepNObjectsImageFilter_txx + +#include "itkLabelStatisticsKeepNObjectsImageFilter.h" +#include "itkProgressAccumulator.h" + + +namespace itk { + +template<class TInputImage, class TFeatureImage> +LabelStatisticsKeepNObjectsImageFilter<TInputImage, TFeatureImage> +::LabelStatisticsKeepNObjectsImageFilter() +{ + m_BackgroundValue = NumericTraits<OutputImagePixelType>::NonpositiveMin(); + m_NumberOfObjects = 1; + m_ReverseOrdering = false; + m_Attribute = LabelObjectType::MEAN; + this->SetNumberOfRequiredInputs(2); +} + +template<class TInputImage, class TFeatureImage> +void +LabelStatisticsKeepNObjectsImageFilter<TInputImage, TFeatureImage> +::GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // We need all the input. + InputImagePointer input = const_cast<InputImageType *>(this->GetInput()); + if( input ) + { + input->SetRequestedRegion( input->GetLargestPossibleRegion() ); + } +} + + +template<class TInputImage, class TFeatureImage> +void +LabelStatisticsKeepNObjectsImageFilter<TInputImage, TFeatureImage> +::EnlargeOutputRequestedRegion(DataObject *) +{ + this->GetOutput() + ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); +} + + +template<class TInputImage, class TFeatureImage> +void +LabelStatisticsKeepNObjectsImageFilter<TInputImage, TFeatureImage> +::GenerateData() +{ + // Create a process accumulator for tracking the progress of this minipipeline + ProgressAccumulator::Pointer progress = ProgressAccumulator::New(); + progress->SetMiniPipelineFilter(this); + + // Allocate the output + this->AllocateOutputs(); + + typename LabelizerType::Pointer labelizer = LabelizerType::New(); + labelizer->SetInput( this->GetInput() ); + labelizer->SetBackgroundValue( m_BackgroundValue ); + labelizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(labelizer, .3f); + + typename LabelObjectValuatorType::Pointer valuator = LabelObjectValuatorType::New(); + valuator->SetInput( labelizer->GetOutput() ); + valuator->SetFeatureImage( this->GetFeatureImage() ); + valuator->SetLabelImage( this->GetInput() ); + valuator->SetNumberOfThreads( this->GetNumberOfThreads() ); + valuator->SetComputeHistogram( false ); + if( m_Attribute == LabelObjectType::PERIMETER || m_Attribute == LabelObjectType::ROUNDNESS ) + { + valuator->SetComputePerimeter( true ); + } + if( m_Attribute == LabelObjectType::FERET_DIAMETER ) + { + valuator->SetComputeFeretDiameter( true ); + } + progress->RegisterInternalFilter(valuator, .3f); + + typename KeepNObjectsType::Pointer opening = KeepNObjectsType::New(); + opening->SetInput( valuator->GetOutput() ); + opening->SetNumberOfObjects( m_NumberOfObjects ); + opening->SetReverseOrdering( m_ReverseOrdering ); + opening->SetAttribute( m_Attribute ); + opening->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(opening, .2f); + + typename BinarizerType::Pointer binarizer = BinarizerType::New(); + binarizer->SetInput( opening->GetOutput() ); + binarizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(binarizer, .2f); + + binarizer->GraftOutput( this->GetOutput() ); + binarizer->Update(); + this->GraftOutput( binarizer->GetOutput() ); +} + + +template<class TInputImage, class TFeatureImage> +void +LabelStatisticsKeepNObjectsImageFilter<TInputImage, TFeatureImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "BackgroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_BackgroundValue) << std::endl; + os << indent << "NumberOfObjects: " << m_NumberOfObjects << std::endl; + os << indent << "ReverseOrdering: " << m_ReverseOrdering << std::endl; + os << indent << "Attribute: " << LabelObjectType::GetNameFromAttribute(m_Attribute) << " (" << m_Attribute << ")" << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelStatisticsOpeningImageFilter.h b/Utilities/ITK/Code/Review/itkLabelStatisticsOpeningImageFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..ece25ee33a643fa62b00c4e7a94f99c50f817f98 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelStatisticsOpeningImageFilter.h @@ -0,0 +1,202 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelStatisticsOpeningImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-11 14:24:44 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelStatisticsOpeningImageFilter_h +#define __itkLabelStatisticsOpeningImageFilter_h + +#include "itkImageToImageFilter.h" +#include "itkStatisticsLabelObject.h" +#include "itkLabelMap.h" +#include "itkLabelImageToLabelMapFilter.h" +#include "itkStatisticsLabelMapFilter.h" +#include "itkStatisticsOpeningLabelMapFilter.h" +#include "itkLabelMapToLabelImageFilter.h" + + +namespace itk { + +/** \class LabelStatisticsOpeningImageFilter + * \brief remove the objects according to the value of their statistics attribute + * + * LabelStatisticsOpeningImageFilter removes the objects in a labeled image + * with an attribute value smaller or greater than a threshold called Lambda. + * The attributes are the ones of the StatisticsLabelObject. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \sa StatisticsLabelObject, BinaryStatisticsOpeningImageFilter, LabelShapeOpeningImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TInputImage, class TFeatureImage> +class ITK_EXPORT LabelStatisticsOpeningImageFilter : + public ImageToImageFilter<TInputImage, TInputImage> +{ +public: + /** Standard class typedefs. */ + typedef LabelStatisticsOpeningImageFilter Self; + typedef ImageToImageFilter<TInputImage, TInputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef TInputImage OutputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::ConstPointer OutputImageConstPointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + + typedef TFeatureImage FeatureImageType; + typedef typename FeatureImageType::Pointer FeatureImagePointer; + typedef typename FeatureImageType::ConstPointer FeatureImageConstPointer; + typedef typename FeatureImageType::PixelType FeatureImagePixelType; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(ImageDimension, unsigned int, + TInputImage::ImageDimension); + + typedef StatisticsLabelObject<InputImagePixelType, itkGetStaticConstMacro(ImageDimension)> LabelObjectType; + typedef LabelMap< LabelObjectType > LabelMapType; + typedef LabelImageToLabelMapFilter< InputImageType, LabelMapType > LabelizerType; + typedef StatisticsLabelMapFilter< LabelMapType, TFeatureImage > LabelObjectValuatorType; + typedef typename LabelObjectType::AttributeType AttributeType; + typedef StatisticsOpeningLabelMapFilter< LabelMapType > OpeningType; + typedef LabelMapToLabelImageFilter< LabelMapType, OutputImageType > BinarizerType; + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(LabelStatisticsOpeningImageFilter, + ImageToImageFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>)); + /** End concept checking */ +#endif + + /** + * Set/Get the value used as "background" in the output image. + * Defaults to NumericTraits<PixelType>::NonpositiveMin(). + */ + itkSetMacro(BackgroundValue, OutputImagePixelType); + itkGetConstMacro(BackgroundValue, OutputImagePixelType); + + /** + * Set/Get the threshold used to keep or remove the objects. + */ + itkGetConstMacro(Lambda, double); + itkSetMacro(Lambda, double); + + /** + * Set/Get the ordering of the objects. By default, the objects with + * an attribute value smaller than Lamba are removed. Turning ReverseOrdering + * to true make this filter remove the object with an attribute value greater + * than Lambda instead. + */ + itkGetConstMacro( ReverseOrdering, bool ); + itkSetMacro( ReverseOrdering, bool ); + itkBooleanMacro( ReverseOrdering ); + + /** + * Set/Get the attribute to use to select the object to remove. The default + * is "Mean". + */ + itkGetConstMacro( Attribute, AttributeType ); + itkSetMacro( Attribute, AttributeType ); + void SetAttribute( const std::string & s ) + { + this->SetAttribute( LabelObjectType::GetAttributeFromName( s ) ); + } + + /** Set the feature image */ + void SetFeatureImage(const TFeatureImage *input) + { + // Process object is not const-correct so the const casting is required. + this->SetNthInput( 1, const_cast<TFeatureImage *>(input) ); + } + + /** Get the feature image */ + const FeatureImageType * GetFeatureImage() + { + return static_cast<const FeatureImageType*>(this->ProcessObject::GetInput(1)); + } + + /** Set the input image */ + void SetInput1(const InputImageType *input) + { + this->SetInput( input ); + } + + /** Set the feature image */ + void SetInput2(const FeatureImageType *input) + { + this->SetFeatureImage( input ); + } + +protected: + LabelStatisticsOpeningImageFilter(); + ~LabelStatisticsOpeningImageFilter() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + + /** LabelStatisticsOpeningImageFilter needs the entire input be + * available. Thus, it needs to provide an implementation of + * GenerateInputRequestedRegion(). */ + void GenerateInputRequestedRegion(); + + /** LabelStatisticsOpeningImageFilter will produce the entire output. */ + void EnlargeOutputRequestedRegion(DataObject *itkNotUsed(output)); + + /** Single-threaded version of GenerateData. This filter delegates + * to GrayscaleGeodesicErodeImageFilter. */ + void GenerateData(); + + +private: + LabelStatisticsOpeningImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + OutputImagePixelType m_BackgroundValue; + double m_Lambda; + bool m_ReverseOrdering; + AttributeType m_Attribute; +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkLabelStatisticsOpeningImageFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelStatisticsOpeningImageFilter.txx b/Utilities/ITK/Code/Review/itkLabelStatisticsOpeningImageFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..238037d5e090e40359d7f1753401f19676f4dfb6 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkLabelStatisticsOpeningImageFilter.txx @@ -0,0 +1,131 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkLabelStatisticsOpeningImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-07 12:26:30 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkLabelStatisticsOpeningImageFilter_txx +#define __itkLabelStatisticsOpeningImageFilter_txx + +#include "itkLabelStatisticsOpeningImageFilter.h" +#include "itkProgressAccumulator.h" + + +namespace itk { + +template<class TInputImage, class TFeatureImage> +LabelStatisticsOpeningImageFilter<TInputImage, TFeatureImage> +::LabelStatisticsOpeningImageFilter() +{ + m_BackgroundValue = NumericTraits<OutputImagePixelType>::NonpositiveMin(); + m_Lambda = NumericTraits< double >::Zero; + m_ReverseOrdering = false; + m_Attribute = LabelObjectType::MEAN; + this->SetNumberOfRequiredInputs(2); +} + +template<class TInputImage, class TFeatureImage> +void +LabelStatisticsOpeningImageFilter<TInputImage, TFeatureImage> +::GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // We need all the input. + InputImagePointer input = const_cast<InputImageType *>(this->GetInput()); + if( input ) + { + input->SetRequestedRegion( input->GetLargestPossibleRegion() ); + } +} + + +template<class TInputImage, class TFeatureImage> +void +LabelStatisticsOpeningImageFilter<TInputImage, TFeatureImage> +::EnlargeOutputRequestedRegion(DataObject *) +{ + this->GetOutput() + ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); +} + + +template<class TInputImage, class TFeatureImage> +void +LabelStatisticsOpeningImageFilter<TInputImage, TFeatureImage> +::GenerateData() +{ + // Create a process accumulator for tracking the progress of this minipipeline + ProgressAccumulator::Pointer progress = ProgressAccumulator::New(); + progress->SetMiniPipelineFilter(this); + + // Allocate the output + this->AllocateOutputs(); + + typename LabelizerType::Pointer labelizer = LabelizerType::New(); + labelizer->SetInput( this->GetInput() ); + labelizer->SetBackgroundValue( m_BackgroundValue ); + labelizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(labelizer, .3f); + + typename LabelObjectValuatorType::Pointer valuator = LabelObjectValuatorType::New(); + valuator->SetInput( labelizer->GetOutput() ); + valuator->SetFeatureImage( this->GetFeatureImage() ); + valuator->SetLabelImage( this->GetInput() ); + valuator->SetNumberOfThreads( this->GetNumberOfThreads() ); + valuator->SetComputeHistogram( false ); + if( m_Attribute == LabelObjectType::PERIMETER || m_Attribute == LabelObjectType::ROUNDNESS ) + { + valuator->SetComputePerimeter( true ); + } + if( m_Attribute == LabelObjectType::FERET_DIAMETER ) + { + valuator->SetComputeFeretDiameter( true ); + } + progress->RegisterInternalFilter(valuator, .3f); + + typename OpeningType::Pointer opening = OpeningType::New(); + opening->SetInput( valuator->GetOutput() ); + opening->SetLambda( m_Lambda ); + opening->SetReverseOrdering( m_ReverseOrdering ); + opening->SetAttribute( m_Attribute ); + opening->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(opening, .2f); + + typename BinarizerType::Pointer binarizer = BinarizerType::New(); + binarizer->SetInput( opening->GetOutput() ); + binarizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(binarizer, .2f); + + binarizer->GraftOutput( this->GetOutput() ); + binarizer->Update(); + this->GraftOutput( binarizer->GetOutput() ); +} + + +template<class TInputImage, class TFeatureImage> +void +LabelStatisticsOpeningImageFilter<TInputImage, TFeatureImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "BackgroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_BackgroundValue) << std::endl; + os << indent << "Lambda: " << m_Lambda << std::endl; + os << indent << "ReverseOrdering: " << m_ReverseOrdering << std::endl; + os << indent << "Attribute: " << LabelObjectType::GetNameFromAttribute(m_Attribute) << " (" << m_Attribute << ")" << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkLabelToRGBFunctor.h b/Utilities/ITK/Code/Review/itkLabelToRGBFunctor.h index 67aa8fd4d5546a33bce28781234d690b52f71308..e8386ab6d870488ed2bbe1443ab70ee01f383b3a 100644 --- a/Utilities/ITK/Code/Review/itkLabelToRGBFunctor.h +++ b/Utilities/ITK/Code/Review/itkLabelToRGBFunctor.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelToRGBFunctor.h,v $ Language: C++ - Date: $Date: 2009-02-24 19:03:15 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-07-07 12:27:34 $ + Version: $Revision: 1.11 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -125,6 +125,18 @@ public: m_Colors.push_back( rgbPixel ); } + // Empty the color LUT + void ResetColors() + { + m_Colors.clear(); + } + + // Get number of colors in the LUT + unsigned int GetNumberOfColors() const + { + return m_Colors.size(); + } + bool operator != (const Self &l) const { const bool areDifferent = m_BackgroundColor != l.m_BackgroundColor || diff --git a/Utilities/ITK/Code/Review/itkLabelToRGBImageFilter.h b/Utilities/ITK/Code/Review/itkLabelToRGBImageFilter.h index 4bc1f19c91b581a4c5f9ce9d01c50e7eec6ee225..8a41464ac172b6a376561a0e3df0394ee444f46b 100644 --- a/Utilities/ITK/Code/Review/itkLabelToRGBImageFilter.h +++ b/Utilities/ITK/Code/Review/itkLabelToRGBImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelToRGBImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-28 18:14:36 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-07-07 12:27:34 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -80,6 +80,18 @@ public: itkSetMacro( BackgroundColor, OutputPixelType ); itkGetConstReferenceMacro( BackgroundColor, OutputPixelType ); + /** Empty the color LUT container */ + void ResetColors(); + + /** Get number of colors in the LUT container */ + unsigned int GetNumberOfColors() const; + + /** Type of the color component */ + typedef typename OutputPixelType::ComponentType ComponentType; + + /** Add color to the LUT container */ + void AddColor( ComponentType r, ComponentType g, ComponentType b ); + protected: LabelToRGBImageFilter(); virtual ~LabelToRGBImageFilter() {}; diff --git a/Utilities/ITK/Code/Review/itkLabelToRGBImageFilter.txx b/Utilities/ITK/Code/Review/itkLabelToRGBImageFilter.txx index 9b55f89c6bf18c8d1cff1ea8110de2ce0e492216..3eb42e0828d44bf814a578dce585697580e93baa 100644 --- a/Utilities/ITK/Code/Review/itkLabelToRGBImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkLabelToRGBImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkLabelToRGBImageFilter.txx,v $ Language: C++ - Date: $Date: 2007-10-22 12:54:03 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-07-07 12:27:34 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -34,6 +34,30 @@ LabelToRGBImageFilter<TLabelImage, TOutputImage> m_BackgroundColor.Fill( NumericTraits<OutputPixelValueType>::Zero ); } +template <class TLabelImage, class TOutputImage> +unsigned int +LabelToRGBImageFilter<TLabelImage, TOutputImage> +::GetNumberOfColors() const +{ + return this->GetFunctor().GetNumberOfColors(); +} + +template <class TLabelImage, class TOutputImage> +void +LabelToRGBImageFilter<TLabelImage, TOutputImage> +::ResetColors() +{ + this->GetFunctor().ResetColors(); +} + +template <class TLabelImage, class TOutputImage> +void +LabelToRGBImageFilter<TLabelImage, TOutputImage> +::AddColor( ComponentType r, ComponentType g, ComponentType b ) +{ + this->GetFunctor().AddColor( r, g, b ); +} + template <class TLabelImage, class TOutputImage> void LabelToRGBImageFilter<TLabelImage, TOutputImage> diff --git a/Utilities/ITK/Code/Review/itkMaskedRankImageFilter.h b/Utilities/ITK/Code/Review/itkMaskedRankImageFilter.h index bcdb746e6b9ee9bfebf4ff999402c88481ba0de7..e319d72f6300201cd17b2ceabe0f48b606b8d029 100644 --- a/Utilities/ITK/Code/Review/itkMaskedRankImageFilter.h +++ b/Utilities/ITK/Code/Review/itkMaskedRankImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMaskedRankImageFilter.h,v $ Language: C++ - Date: $Date: 2009-04-23 03:43:42 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-06-03 12:48:05 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -111,7 +111,7 @@ protected: void PrintSelf(std::ostream& os, Indent indent) const; - bool useVectorBasedHistogram() + bool UseVectorBasedHistogram() { // bool, short and char are acceptable for vector based algorithm: they do not require // too much memory. Other types are not usable with that algorithm diff --git a/Utilities/ITK/Code/Review/itkMaskedRankImageFilter.txx b/Utilities/ITK/Code/Review/itkMaskedRankImageFilter.txx index e99eadb4dc085a89cf698a8a60ed017ebd3819f4..a4b5b57627174e8b04dd684414410931fe5c47cb 100644 --- a/Utilities/ITK/Code/Review/itkMaskedRankImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkMaskedRankImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMaskedRankImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-08-07 15:00:35 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-06-03 12:48:05 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -48,7 +48,7 @@ MaskedRankImageFilter<TInputImage, TMaskImage, TOutputImage, TKernel> ::NewHistogram() { HistogramType * hist; - if (useVectorBasedHistogram()) + if (UseVectorBasedHistogram()) { hist = new VHistogram(); } diff --git a/Utilities/ITK/Code/Review/itkMergeLabelMapFilter.h b/Utilities/ITK/Code/Review/itkMergeLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..6d4673397161ae6f600c2d3f708ec93d9b2a1719 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkMergeLabelMapFilter.h @@ -0,0 +1,126 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMergeLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-07-28 14:23:40 $ + Version: $Revision: 1.5 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkMergeLabelMapFilter_h +#define __itkMergeLabelMapFilter_h + +#include "itkInPlaceLabelMapFilter.h" + +namespace itk { +/** \class MergeLabelMapFilter + * \brief Merges two Label Maps using different methods to create the product. + * + * This filter takes two input Label Map and takes an additional integer to determine the method that will + * be used to merge the two Label Maps. The integers are read as follows: + * KEEP = 0, + * AGGREGATE = 1, + * PACK = 2, + * STRICT = 3 + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * \sa ShapeLabelObject, RelabelComponentImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TImage > +class ITK_EXPORT MergeLabelMapFilter : + public InPlaceLabelMapFilter<TImage> +{ +public: + /** Standard class typedefs. */ + typedef MergeLabelMapFilter Self; + typedef InPlaceLabelMapFilter<TImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TImage ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::LabelObjectType LabelObjectType; + typedef typename LabelObjectType::Pointer LabelObjectPointer; + + /** ImageDimension constants */ + itkStaticConstMacro( ImageDimension, unsigned int, TImage::ImageDimension ); + + /** Standard New method. */ + itkNewMacro( Self ); + + /** Runtime information support. */ + itkTypeMacro( MergeLabelMapFilter, InPlaceLabelMapFilter ); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ +/* itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>));*/ + /** End concept checking */ +#endif + +#ifdef STRICT +#undef STRICT +#endif + typedef enum { + KEEP = 0, + AGGREGATE = 1, + PACK = 2, + STRICT = 3 + } MethodChoice; + + itkSetMacro( Method, MethodChoice ); + itkGetConstReferenceMacro( Method, MethodChoice ); + +protected: + MergeLabelMapFilter(); + ~MergeLabelMapFilter() {}; + + void GenerateData(); + + void PrintSelf(std::ostream& os, Indent indent) const; + + typedef typename ImageType::LabelObjectContainerType LabelObjectContainerType; + typedef typename LabelObjectType::LineContainerType LineContainerType; + typedef typename LineContainerType::const_iterator LineContainerIterator; + + MethodChoice m_Method; + +private: + MergeLabelMapFilter( const Self& ); //purposely not implemented + void operator=( const Self& ); //purposely not implemented + + void MergeWithKeep(); + void MergeWithAggregate(); + void MergeWithPack(); + void MergeWithStrict(); + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkMergeLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkMergeLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkMergeLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..73c8915f6cdc3e96b62aa8ae155f59041142018d --- /dev/null +++ b/Utilities/ITK/Code/Review/itkMergeLabelMapFilter.txx @@ -0,0 +1,279 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkMergeLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-07-24 12:03:35 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkMergeLabelMapFilter_txx +#define __itkMergeLabelMapFilter_txx + +#include "itkMergeLabelMapFilter.h" +#include "itkProgressReporter.h" +#include <deque> + + +namespace itk { + +template <class TImage> +MergeLabelMapFilter<TImage> +::MergeLabelMapFilter() +{ + this->m_Method = KEEP; +} + +template <class TImage> +void +MergeLabelMapFilter<TImage> +::GenerateData() +{ + // Allocate the output + this->AllocateOutputs(); + + switch( this->m_Method ) + { + case KEEP: + { + this->MergeWithKeep(); + break; + } + case AGGREGATE: + { + this->MergeWithAggregate(); + break; + } + case PACK: + { + this->MergeWithPack(); + break; + } + case STRICT: + { + this->MergeWithStrict(); + break; + } + default: + { + itkExceptionMacro(<< "No such method: " << this->m_Method ); + } + } +} + +template <class TImage> +void +MergeLabelMapFilter<TImage> +::MergeWithKeep() +{ + + ImageType * output = this->GetOutput(); + + typedef std::deque< LabelObjectPointer > VectorType; + VectorType labelObjects; + + ProgressReporter progress( this, 0, 1 ); + + for( unsigned int i=1; i < this->GetNumberOfInputs(); i++ ) + { + + const LabelObjectContainerType & otherLabelObjects = this->GetInput(i)->GetLabelObjectContainer(); + typename LabelObjectContainerType::const_iterator it2 = otherLabelObjects.begin(); + + while( it2 != otherLabelObjects.end() ) + { + const LabelObjectType * lo = it2->second; + LabelObjectPointer newLo = LabelObjectType::New(); + newLo->CopyAllFrom( lo ); + + if( ! output->HasLabel( newLo->GetLabel() ) ) + { + // we can keep the label + output->AddLabelObject( newLo ); + } + else + { + // store the label object to read it later with another label + labelObjects.push_back( newLo ); + } + + // go to the next label + progress.CompletedPixel(); + it2++; + } + + // add the other label objects, with a different label + typename VectorType::iterator it = labelObjects.begin(); + while( it != labelObjects.end() ) + { + output->PushLabelObject( *it ); + it++; + } + } +} + + +template <class TImage> +void +MergeLabelMapFilter<TImage> +::MergeWithStrict() +{ + + ImageType * output = this->GetOutput(); + + ProgressReporter progress( this, 0, 1 ); + + for( unsigned int i=1; i<this->GetNumberOfInputs(); i++ ) + { + const LabelObjectContainerType & otherLabelObjects = this->GetInput(i)->GetLabelObjectContainer(); + typename LabelObjectContainerType::const_iterator it2 = otherLabelObjects.begin(); + + while( it2 != otherLabelObjects.end() ) + { + const LabelObjectType * lo = it2->second; + LabelObjectPointer newLo = LabelObjectType::New(); + newLo->CopyAllFrom( lo ); + + if( ! output->HasLabel( newLo->GetLabel() ) ) + { + // we can keep the label + output->AddLabelObject( newLo ); + } + else + { + itkExceptionMacro(<< "Label " + << static_cast< typename itk::NumericTraits< PixelType >::PrintType >( newLo->GetLabel() ) + << " from input " << i + << " is already in use."); + } + + // go to the next label + progress.CompletedPixel(); + it2++; + } + } +} + + +template <class TImage> +void +MergeLabelMapFilter<TImage> +::MergeWithAggregate() +{ + + ImageType * output = this->GetOutput(); + + ProgressReporter progress( this, 0, 1 ); + + for( unsigned int i=1; i<this->GetNumberOfInputs(); i++ ) + { + const LabelObjectContainerType & otherLabelObjects = this->GetInput(i)->GetLabelObjectContainer(); + + typename LabelObjectContainerType::const_iterator it2 = otherLabelObjects.begin(); + + while( it2 != otherLabelObjects.end() ) + { + const LabelObjectType * lo = it2->second; + + if( ! output->HasLabel( lo->GetLabel() ) ) + { + // we can keep the label + LabelObjectPointer newLo = LabelObjectType::New(); + newLo->CopyAllFrom( lo ); + output->AddLabelObject( newLo ); + } + else + { + if( lo->GetLabel() != output->GetBackgroundValue() ) + { + // add the lines of that object to the one already in the output + LabelObjectType * mainLo = output->GetLabelObject( lo->GetLabel() ); + const LineContainerType & lineContainer = lo->GetLineContainer(); + + LineContainerIterator lit = lineContainer.begin(); + while( lit != lineContainer.end() ) + { + mainLo->AddLine( *lit ); + lit++; + } + + // be sure to have the lines well organized + mainLo->Optimize(); + } + } + + // go to the next label + progress.CompletedPixel(); + it2++; + } + } +} + + +template <class TImage> +void +MergeLabelMapFilter<TImage> +::MergeWithPack() +{ + + ProgressReporter progress( this, 0, 1 ); + + ImageType * output = this->GetOutput(); + + // get the label objects of the first input + LabelObjectContainerType labelObjects = output->GetLabelObjectContainer(); + + // and put back the objects in the map + output->ClearLabels(); + + typename LabelObjectContainerType::iterator it = labelObjects.begin(); + + while( it != labelObjects.end() ) + { + output->PushLabelObject( it->second ); + + // go to the next label + progress.CompletedPixel(); + it++; + } + + // now, the next images + for( unsigned int i=1; i<this->GetNumberOfInputs(); i++ ) + { + const LabelObjectContainerType & otherLabelObjects = this->GetInput(i)->GetLabelObjectContainer(); + typename LabelObjectContainerType::const_iterator it2 = otherLabelObjects.begin(); + + while( it2 != otherLabelObjects.end() ) + { + const LabelObjectType * lo = it2->second; + LabelObjectPointer newLo = LabelObjectType::New(); + newLo->CopyAllFrom( lo ); + output->PushLabelObject( newLo ); + + // go to the next label + progress.CompletedPixel(); + it2++; + } + } +} + + +template <class TImage> +void +MergeLabelMapFilter<TImage> +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "Method: " << this->m_Method << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkMovingHistogramImageFilter.h b/Utilities/ITK/Code/Review/itkMovingHistogramImageFilter.h index fc21eb7c91ea291a8c5573934e78414d15f16925..0a991d5f381ddc1e62e4ff5ac93618a3c99233da 100644 --- a/Utilities/ITK/Code/Review/itkMovingHistogramImageFilter.h +++ b/Utilities/ITK/Code/Review/itkMovingHistogramImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMovingHistogramImageFilter.h,v $ Language: C++ - Date: $Date: 2008-08-06 11:33:08 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-06-03 12:48:05 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -152,7 +152,7 @@ protected: // declare the type used to store the histogram typedef THistogram HistogramType; - void pushHistogram(HistogramType * histogram, + void PushHistogram(HistogramType * histogram, const OffsetListType* addedList, const OffsetListType* removedList, const RegionType &inputRegion, @@ -160,7 +160,7 @@ protected: const InputImageType* inputImage, const IndexType currentIdx); - void printHist(const HistogramType &H); + void PrintHistogram(const HistogramType &H); #endif diff --git a/Utilities/ITK/Code/Review/itkMovingHistogramImageFilter.txx b/Utilities/ITK/Code/Review/itkMovingHistogramImageFilter.txx index b59bf3c457e88cce83ad3a47f373c708fc40273c..3c464f8b216a262cf4f63abcaf52b94d9ea8d1ca 100644 --- a/Utilities/ITK/Code/Review/itkMovingHistogramImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkMovingHistogramImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMovingHistogramImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-09-30 18:07:03 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-06-03 12:48:05 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -270,7 +270,7 @@ MovingHistogramImageFilter<TInputImage, TOutputImage, TKernel, THistogram> IndexType currentIdx = InLineIt.GetIndex(); outputImage->SetPixel(currentIdx, static_cast< OutputPixelType >( histRef->GetValue( inputImage->GetPixel( currentIdx ) ) )); stRegion.SetIndex( currentIdx - centerOffset ); - pushHistogram(histRef, addedList, removedList, inputRegion, + PushHistogram(histRef, addedList, removedList, inputRegion, stRegion, inputImage, currentIdx); } @@ -300,7 +300,7 @@ MovingHistogramImageFilter<TInputImage, TOutputImage, TKernel, THistogram> HistogramType *tmpHist = HistVec[LineDirection]; stRegion.SetIndex(PrevLineStart - centerOffset); // Now move the histogram - pushHistogram(tmpHist, addedListLine, removedListLine, inputRegion, + PushHistogram(tmpHist, addedListLine, removedListLine, inputRegion, stRegion, inputImage, PrevLineStartHist); //PrevLineStartVec[LineDirection] = LineStart; @@ -329,7 +329,7 @@ MovingHistogramImageFilter<TInputImage, TOutputImage, TKernel, THistogram> template<class TInputImage, class TOutputImage, class TKernel, class THistogram> void MovingHistogramImageFilter<TInputImage, TOutputImage, TKernel, THistogram> -::pushHistogram(HistogramType * histogram, +::PushHistogram(HistogramType * histogram, const OffsetListType* addedList, const OffsetListType* removedList, const RegionType &inputRegion, @@ -371,8 +371,9 @@ MovingHistogramImageFilter<TInputImage, TOutputImage, TKernel, THistogram> template<class TInputImage, class TOutputImage, class TKernel, class THistogram> void + MovingHistogramImageFilter<TInputImage, TOutputImage, TKernel, THistogram> -::printHist(const HistogramType &H) +::PrintHistogram(const HistogramType &H) { /* std::cout << "Hist = " ; typename HistogramType::const_iterator mapIt; diff --git a/Utilities/ITK/Code/Review/itkMovingHistogramMorphologicalGradientImageFilter.h b/Utilities/ITK/Code/Review/itkMovingHistogramMorphologicalGradientImageFilter.h index dcd8168d0a5fa04fba4fdd2dc453bb4d382b1680..48f4085d833c0792f1d8d6929925903527be1c1c 100644 --- a/Utilities/ITK/Code/Review/itkMovingHistogramMorphologicalGradientImageFilter.h +++ b/Utilities/ITK/Code/Review/itkMovingHistogramMorphologicalGradientImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMovingHistogramMorphologicalGradientImageFilter.h,v $ Language: C++ - Date: $Date: 2009-01-28 18:14:36 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-06-03 12:48:05 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -29,7 +29,7 @@ class MorphologicalGradientHistogram public: MorphologicalGradientHistogram() { - if( useVectorBasedAlgorithm() ) + if( UseVectorBasedAlgorithm() ) { initVector(); } } ~MorphologicalGradientHistogram(){} @@ -51,7 +51,7 @@ public: inline void AddPixel( const TInputPixel &p ) { - if( useVectorBasedAlgorithm() ) + if( UseVectorBasedAlgorithm() ) { AddPixelVector( p ); } else { AddPixelMap( p ); } @@ -59,7 +59,7 @@ public: inline void RemovePixel( const TInputPixel &p ) { - if( useVectorBasedAlgorithm() ) + if( UseVectorBasedAlgorithm() ) { RemovePixelVector( p ); } else { RemovePixelMap( p ); } @@ -67,14 +67,14 @@ public: inline TInputPixel GetValue( const TInputPixel & ) { - if( useVectorBasedAlgorithm() ) + if( UseVectorBasedAlgorithm() ) { return GetValueVector(); } else { return GetValueMap(); } } - static inline bool useVectorBasedAlgorithm() + static inline bool UseVectorBasedAlgorithm() { // bool, short and char are acceptable for vector based algorithm: they do not require // too much memory. Other types are not usable with that algorithm @@ -243,7 +243,7 @@ public: /** Return true if the vector based algorithm is used, and * false if the map based algorithm is used */ static bool GetUseVectorBasedAlgorithm() - { return Function::MorphologicalGradientHistogram< ITK_TYPENAME TInputImage::PixelType >::useVectorBasedAlgorithm(); } + { return Function::MorphologicalGradientHistogram< ITK_TYPENAME TInputImage::PixelType >::UseVectorBasedAlgorithm(); } protected: MovingHistogramMorphologicalGradientImageFilter() {}; diff --git a/Utilities/ITK/Code/Review/itkMovingHistogramMorphologyImageFilter.h b/Utilities/ITK/Code/Review/itkMovingHistogramMorphologyImageFilter.h index 3fb7d26e812b6914ba6cfe9fd66d4ef2b1c8d878..8f4cb571fce00457e28fee03140477c8f66fa152 100644 --- a/Utilities/ITK/Code/Review/itkMovingHistogramMorphologyImageFilter.h +++ b/Utilities/ITK/Code/Review/itkMovingHistogramMorphologyImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMovingHistogramMorphologyImageFilter.h,v $ Language: C++ - Date: $Date: 2009-04-23 03:43:42 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-06-03 12:48:05 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -30,7 +30,7 @@ class MorphologyHistogram public: MorphologyHistogram() { - if( useVectorBasedAlgorithm() ) + if( UseVectorBasedAlgorithm() ) { initVector(); } } ~MorphologyHistogram(){} @@ -52,7 +52,7 @@ public: inline void AddBoundary() { - if( useVectorBasedAlgorithm() ) + if( UseVectorBasedAlgorithm() ) { AddBoundaryVector(); } else { AddBoundaryMap(); } @@ -60,7 +60,7 @@ public: inline void RemoveBoundary() { - if( useVectorBasedAlgorithm() ) + if( UseVectorBasedAlgorithm() ) { RemoveBoundaryVector(); } else { RemoveBoundaryMap(); } @@ -68,7 +68,7 @@ public: inline void AddPixel( const TInputPixel &p ) { - if( useVectorBasedAlgorithm() ) + if( UseVectorBasedAlgorithm() ) { AddPixelVector( p ); } else { AddPixelMap( p ); } @@ -76,7 +76,7 @@ public: inline void RemovePixel( const TInputPixel &p ) { - if( useVectorBasedAlgorithm() ) + if( UseVectorBasedAlgorithm() ) { RemovePixelVector( p ); } else { RemovePixelMap( p ); } @@ -84,14 +84,14 @@ public: inline TInputPixel GetValue( const TInputPixel & ) { - if( useVectorBasedAlgorithm() ) + if( UseVectorBasedAlgorithm() ) { return GetValueVector(); } else { return GetValueMap(); } } - inline static bool useVectorBasedAlgorithm() + inline static bool UseVectorBasedAlgorithm() { // bool, short and char are acceptable for vector based algorithm: they do not require // too much memory. Other types are not usable with that algorithm @@ -277,7 +277,7 @@ public: /** Return true if the vector based algorithm is used, and * false if the map based algorithm is used */ static bool GetUseVectorBasedAlgorithm() - { return THistogram::useVectorBasedAlgorithm(); } + { return THistogram::UseVectorBasedAlgorithm(); } protected: MovingHistogramMorphologyImageFilter(); diff --git a/Utilities/ITK/Code/Review/itkMultiScaleHessianBasedMeasureImageFilter.txx b/Utilities/ITK/Code/Review/itkMultiScaleHessianBasedMeasureImageFilter.txx index 049b366fd8efc417915e6d07740b84c7dd56db5d..1bc34258fd2fada5068ffae6dbf49d72a30ec00b 100644 --- a/Utilities/ITK/Code/Review/itkMultiScaleHessianBasedMeasureImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkMultiScaleHessianBasedMeasureImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultiScaleHessianBasedMeasureImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-04-20 12:54:12 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-08-26 19:09:35 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -181,9 +181,12 @@ MultiScaleHessianBasedMeasureImageFilter while (sigma <= m_SigmaMaximum) { - // TODO: change the to debug output - std::cout << "Computing measure for scale with sigma = " - << sigma << std::endl; + if ( m_NumberOfSigmaSteps == 0 ) + { + break; + } + + itkDebugMacro ( << "Computing measure for scale with sigma = " << sigma ); m_HessianFilter->SetSigma( sigma ); @@ -196,6 +199,11 @@ MultiScaleHessianBasedMeasureImageFilter sigma = this->ComputeSigmaValue( scaleLevel ); scaleLevel++; + + if ( m_NumberOfSigmaSteps == 1 ) + { + break; + } } // Write out the best response to the output image @@ -233,18 +241,20 @@ MultiScaleHessianBasedMeasureImageFilter ImageRegionIterator<UpdateBufferType> oit( m_UpdateBuffer, outputRegion ); typename ScalesImageType::Pointer scalesImage = static_cast<ScalesImageType*>(this->ProcessObject::GetOutput(1)); - ImageRegionIterator<ScalesImageType> osit (scalesImage, outputRegion ); + ImageRegionIterator<ScalesImageType> osit; typename HessianImageType::Pointer hessianImage = static_cast<HessianImageType*>(this->ProcessObject::GetOutput(2)); - ImageRegionIterator<HessianImageType> ohit( hessianImage, outputRegion ); + ImageRegionIterator<HessianImageType> ohit; oit.GoToBegin(); if (m_GenerateScalesOutput) { + osit = ImageRegionIterator<ScalesImageType> ( scalesImage, outputRegion ); osit.GoToBegin(); } if (m_GenerateHessianOutput) { + ohit = ImageRegionIterator<HessianImageType> ( hessianImage, outputRegion ); ohit.GoToBegin(); } diff --git a/Utilities/ITK/Code/Review/itkMultiphaseDenseFiniteDifferenceImageFilter.h b/Utilities/ITK/Code/Review/itkMultiphaseDenseFiniteDifferenceImageFilter.h index 3f08d724a9c0a661b24b0d75381523a788da8206..ed7664e3d19aa0d96b85b1e17367999bcab99a40 100644 --- a/Utilities/ITK/Code/Review/itkMultiphaseDenseFiniteDifferenceImageFilter.h +++ b/Utilities/ITK/Code/Review/itkMultiphaseDenseFiniteDifferenceImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultiphaseDenseFiniteDifferenceImageFilter.h,v $ Language: C++ - Date: $Date: 2009-05-15 17:44:18 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-07-29 15:13:55 $ + Version: $Revision: 1.4 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -98,35 +98,47 @@ namespace itk { * * \ingroup ImageFilters * \sa FiniteDifferenceImageFilter */ -template < class TInputImage, - class TOutputImage, - class TFunction, +template < class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell = unsigned int > -class ITK_EXPORT MultiphaseDenseFiniteDifferenceImageFilter - : public MultiphaseFiniteDifferenceImageFilter<TInputImage, - TOutputImage, - TFunction, - TIdCell > +class ITK_EXPORT MultiphaseDenseFiniteDifferenceImageFilter : + public MultiphaseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, + TOutputImage, TFunction, TIdCell > { public: /** Standard class typedefs */ typedef MultiphaseDenseFiniteDifferenceImageFilter Self; - typedef MultiphaseFiniteDifferenceImageFilter< - TInputImage, TOutputImage, TFunction > Superclass; + typedef MultiphaseFiniteDifferenceImageFilter< TInputImage, + TFeatureImage, TOutputImage, TFunction > Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods) */ itkTypeMacro( MultiphaseDenseFiniteDifferenceImageFilter, ImageToImageFilter ); + /** Dimensionality of input and output data is assumed to be the same. + * It is inherited from the superclass. */ + itkStaticConstMacro(ImageDimension, unsigned int, Superclass::ImageDimension); + /** Convenient typedefs */ typedef typename Superclass::InputImageType InputImageType; - typedef typename Superclass::InputSizeType InputSizeType; typedef typename Superclass::InputImagePointer InputImagePointer; typedef typename Superclass::InputRegionType InputRegionType; - typedef typename Superclass::InputSpacingType InputSpacingType; - typedef typename Superclass::InputPointType InputPointType; + typedef typename Superclass::InputSizeType InputSizeType; + typedef typename Superclass::InputSizeValueType InputSizeValueType; + typedef typename Superclass::InputIndexType InputIndexType; + typedef typename Superclass::InputIndexValueType InputIndexValueType; typedef typename Superclass::InputPixelType InputPixelType; + typedef typename Superclass::InputPointType InputPointType; + typedef typename Superclass::InputSpacingType InputSpacingType; + typedef typename InputImageType::ValueType ValueType; + + typedef typename Superclass::FeatureImageType FeatureImageType; + typedef typename Superclass::FeatureSizeType FeatureSizeType; + typedef typename Superclass::FeatureImagePointer FeatureImagePointer; + typedef typename Superclass::FeatureRegionType FeatureRegionType; + typedef typename Superclass::FeatureSpacingType FeatureSpacingType; + typedef typename Superclass::FeaturePointType FeaturePointType; + typedef typename Superclass::FeaturePixelType FeaturePixelType; typedef typename Superclass::OutputImageType OutputImageType; typedef typename Superclass::OutputImagePointer OutputImagePointer; @@ -139,34 +151,29 @@ public: typedef typename Superclass::IdCellType IdCellType; - typedef OutputImageType UpdateBufferType; - typedef OutputImagePointer UpdateBufferPointer; - - /** The type of region used for multithreading */ - typedef typename UpdateBufferType::RegionType ThreadRegionType; - - typedef BinaryThresholdImageFilter< OutputImageType, OutputImageType > ThresholdFilterType; - typedef typename ThresholdFilterType::Pointer ThresholdFilterPointer; + typedef BinaryThresholdImageFilter< InputImageType, InputImageType > + ThresholdFilterType; + typedef typename ThresholdFilterType::Pointer + ThresholdFilterPointer; - typedef SignedMaurerDistanceMapImageFilter< OutputImageType, OutputImageType > MaurerType; - typedef typename MaurerType::Pointer MaurerPointer; + typedef SignedMaurerDistanceMapImageFilter< InputImageType, InputImageType > + MaurerType; + typedef typename MaurerType::Pointer MaurerPointer; - typedef ImageRegionIterator<UpdateBufferType> UpdateIteratorType; - - typedef typename Superclass::FiniteDifferenceFunctionType FiniteDifferenceFunctionType; - typedef typename Superclass::FiniteDifferenceFunctionPointer FiniteDifferenceFunctionPointer; - typedef typename FiniteDifferenceFunctionType::NeighborhoodType NeighborhoodIteratorType; - - /** Dimensionality of input and output data is assumed to be the same. - * It is inherited from the superclass. */ - itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); + typedef typename Superclass::FiniteDifferenceFunctionType + FiniteDifferenceFunctionType; + typedef typename Superclass::FiniteDifferenceFunctionPointer + FiniteDifferenceFunctionPointer; + typedef typename FiniteDifferenceFunctionType::NeighborhoodType + NeighborhoodIteratorType; /** The value type of a time step. Inherited from the superclass. */ typedef typename Superclass::TimeStepType TimeStepType; - typedef NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< OutputImageType > FaceCalculatorType; - typedef typename FaceCalculatorType::FaceListType FaceListType; + typedef NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< InputImageType > + FaceCalculatorType; + typedef typename FaceCalculatorType::FaceListType FaceListType; void SetFunctionCount( const IdCellType& n ); @@ -177,14 +184,14 @@ public: itkConceptMacro(OutputAdditiveOperatorsCheck, (Concept::AdditiveOperators<OutputPixelType>)); itkConceptMacro(InputConvertibleToOutputCheck, - (Concept::Convertible<InputPixelType, OutputPixelType>)); + (Concept::Convertible<FeaturePixelType, OutputPixelType>)); /** End concept checking */ #endif protected: MultiphaseDenseFiniteDifferenceImageFilter() { - this->m_ReinitializeCounter = 1; // FIXME: Should this be a bool ? + this->m_ReinitializeCounter = 1; this->m_UpdateCounter = 0; // FIXME: Should this be a bool ? } @@ -218,7 +225,7 @@ private: virtual TimeStepType CalculateChange(); /** The buffer that holds the updates for an iteration of the algorithm. */ - std::vector< UpdateBufferPointer > m_UpdateBuffers; + std::vector< InputImagePointer > m_UpdateBuffers; }; diff --git a/Utilities/ITK/Code/Review/itkMultiphaseDenseFiniteDifferenceImageFilter.txx b/Utilities/ITK/Code/Review/itkMultiphaseDenseFiniteDifferenceImageFilter.txx index cb84671a64b12baa06e12d0850c52abd44347971..5241dcb8aa1fa968c3d35923f52f5e9eef7e1c40 100644 --- a/Utilities/ITK/Code/Review/itkMultiphaseDenseFiniteDifferenceImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkMultiphaseDenseFiniteDifferenceImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultiphaseDenseFiniteDifferenceImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-05-21 22:03:29 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-07-29 15:14:02 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -23,12 +23,10 @@ namespace itk { -template < class TInputImage, - class TOutputImage, - class TFunction, - typename TIdCell > +template < class TInputImage, class TFeatureImage, class TOutputImage, + class TFunction, typename TIdCell > void -MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, +MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::CopyInputToOutput() { @@ -36,20 +34,14 @@ MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, for( IdCellType i = 0; i < this->m_FunctionCount; i++ ) { - InputImagePointer input = this->m_LevelSet[i]; - InputPointType origin = input->GetOrigin(); - InputSpacingType spacing = input->GetSpacing(); - InputSizeType size = input->GetLargestPossibleRegion().GetSize(); + const InputImagePointer input = this->m_LevelSet[i]; + const InputPointType origin = input->GetOrigin(); + const InputSizeType size = input->GetBufferedRegion().GetSize(); + // Find the index of the target image where this Level Set + // should be pasted. OutputIndexType start; - - // FIXME: Review pixel centering policy here !!! - // Probably the PhysicalPointToIndex method should be used here... - // - for ( unsigned int j = 0; j < ImageDimension; j++ ) - { - start[j] = static_cast<OutputIndexValueType>( origin[j]/spacing[j] ); - } + output->TransformPhysicalPointToIndex( origin, start ); OutputRegionType region; region.SetSize( size ); @@ -60,7 +52,7 @@ MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, itkExceptionMacro ( << "Either input and/or output is NULL." ); } - ImageRegionIterator< InputImageType > in( input, input->GetLargestPossibleRegion() ); + ImageRegionConstIterator< InputImageType > in( input, input->GetBufferedRegion() ); ImageRegionIterator< OutputImageType > out( output, region ); // Fill the output pointer @@ -85,12 +77,10 @@ MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, } } -template < class TInputImage, - class TOutputImage, - class TFunction, - typename TIdCell > +template < class TInputImage, class TFeatureImage, class TOutputImage, + class TFunction, typename TIdCell > void -MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, +MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::AllocateUpdateBuffer() { @@ -105,14 +95,11 @@ MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, } } -template < class TInputImage, - class TOutputImage, - class TFunction, - typename TIdCell > -typename -MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, +template < class TInputImage, class TFeatureImage, class TOutputImage, + class TFunction, typename TIdCell > +typename MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell >::TimeStepType -MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, +MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::CalculateChange() { @@ -120,7 +107,7 @@ MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, for( IdCellType i = 0; i < this->m_FunctionCount; i++ ) { - OutputImagePointer levelset = this->m_LevelSet[i]; + InputImagePointer levelset = this->m_LevelSet[i]; // Get the FiniteDifferenceFunction to use in calculations. const FiniteDifferenceFunctionPointer df = this->m_DifferenceFunctions[i]; @@ -148,7 +135,7 @@ MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, { // Process the non-boundary region. NeighborhoodIteratorType nD ( radius, levelset, *fIt ); - UpdateIteratorType nU ( m_UpdateBuffers[i], *fIt ); + ImageRegionIterator< InputImageType > nU ( m_UpdateBuffers[i], *fIt ); nD.GoToBegin(); nU.GoToBegin(); @@ -178,12 +165,10 @@ MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, return timeStep; } -template< class TInputImage, - class TOutputImage, - class TFunction, - typename TIdCell > +template< class TInputImage, class TFeatureImage, class TOutputImage, + class TFunction, typename TIdCell > void -MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, +MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::SetFunctionCount( const IdCellType& n ) { @@ -193,16 +178,14 @@ MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, for( IdCellType i = 0; i < this->m_FunctionCount; i++ ) { - this->m_UpdateBuffers[i] = UpdateBufferType::New(); + this->m_UpdateBuffers[i] = InputImageType::New(); } } -template< class TInputImage, - class TOutputImage, - class TFunction, - typename TIdCell > +template< class TInputImage, class TFeatureImage, class TOutputImage, + class TFunction, typename TIdCell > void -MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, +MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::ApplyUpdate ( TimeStepType dt ) { @@ -229,15 +212,15 @@ MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, // it is this->m_LevelSet[i]->GetLargestPossibleRegion() InputRegionType region = this->m_LevelSet[i]->GetRequestedRegion(); - ImageRegionIterator<UpdateBufferType> u ( m_UpdateBuffers[i], region ); - ImageRegionIterator<OutputImageType> o ( this->m_LevelSet[i], region ); + ImageRegionIterator< InputImageType > u ( m_UpdateBuffers[i], region ); + ImageRegionIterator< InputImageType > o ( this->m_LevelSet[i], region ); u.GoToBegin(); o.GoToBegin(); while( !u.IsAtEnd() ) { - u.Set( o.Value() + static_cast<OutputPixelType> ( dt ) * u.Get() ); + u.Set( o.Value() + static_cast< InputPixelType > ( dt ) * u.Get() ); ++u; ++o; } @@ -245,7 +228,7 @@ MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, if ( this->GetElapsedIterations() % this->m_ReinitializeCounter == 0 ) { ThresholdFilterPointer thresh = ThresholdFilterType::New(); - thresh->SetLowerThreshold( NumericTraits< OutputPixelType >::NonpositiveMin() ); + thresh->SetLowerThreshold( NumericTraits< InputPixelType >::NonpositiveMin() ); thresh->SetUpperThreshold( 0 ); thresh->SetInsideValue( 1 ); thresh->SetOutsideValue( 0 ); @@ -259,12 +242,12 @@ MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, maurer->SetInsideIsPositive( 0 ); maurer->Update(); - ImageRegionIterator< OutputImageType > it ( maurer->GetOutput(), region ); + ImageRegionIterator< InputImageType > it ( maurer->GetOutput(), region ); o.GoToBegin(); it.GoToBegin(); - OutputPixelType val; + InputPixelType val; while( !o.IsAtEnd() ) { @@ -280,12 +263,10 @@ MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, this->SetRMSChange( vcl_sqrt(rms_change_accumulator / den ) ); } -template< class TInputImage, - class TOutputImage, - class TFunction, - typename TIdCell > +template< class TInputImage, class TFeatureImage, class TOutputImage, + class TFunction, typename TIdCell > void -MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, +MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::PostProcessOutput() { diff --git a/Utilities/ITK/Code/Review/itkMultiphaseFiniteDifferenceImageFilter.h b/Utilities/ITK/Code/Review/itkMultiphaseFiniteDifferenceImageFilter.h index ec0db2c8dce8792cd64b2d364107a1c9fe331e15..a2da9ba020b42bb8932dea7d662b7805e68c1e47 100644 --- a/Utilities/ITK/Code/Review/itkMultiphaseFiniteDifferenceImageFilter.h +++ b/Utilities/ITK/Code/Review/itkMultiphaseFiniteDifferenceImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultiphaseFiniteDifferenceImageFilter.h,v $ Language: C++ - Date: $Date: 2009-05-16 12:35:48 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-07-29 15:14:03 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -159,46 +159,59 @@ namespace itk { * \ingroup LevelSetSegmentation * \sa DenseFiniteDifferenceImageFilter2 */ template < class TInputImage, + class TFeatureImage, class TOutputImage, class TFiniteDifferenceFunction = FiniteDifferenceFunction<TOutputImage>, typename TIdCell = unsigned int > class ITK_EXPORT MultiphaseFiniteDifferenceImageFilter - : public InPlaceImageFilter< TInputImage, TOutputImage > + : public InPlaceImageFilter< TFeatureImage, TOutputImage > { public: /** Standard class typedefs. */ typedef MultiphaseFiniteDifferenceImageFilter Self; - typedef InPlaceImageFilter<TInputImage, TOutputImage> Superclass; + typedef InPlaceImageFilter<TFeatureImage, TOutputImage> Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods) */ itkTypeMacro( MultiphaseFiniteDifferenceImageFilter, InPlaceImageFilter ); + /** Dimensionality of input and output data is assumed to be the same. */ + itkStaticConstMacro(ImageDimension, unsigned int, TOutputImage::ImageDimension); + /** Input and output image types. */ - typedef TInputImage InputImageType; - typedef typename InputImageType::Pointer InputImagePointer; - typedef typename InputImageType::RegionType InputRegionType; - typedef typename InputImageType::SizeType InputSizeType; - typedef typename InputImageType::SpacingType InputSpacingType; - typedef typename InputImageType::PointType InputPointType; - typedef typename InputImageType::PixelType InputPixelType; - - typedef TOutputImage OutputImageType; - typedef typename OutputImageType::Pointer OutputImagePointer; - typedef typename OutputImageType::PixelType OutputPixelType; - typedef typename OutputImageType::RegionType OutputRegionType; - typedef typename OutputImageType::SizeType OutputSizeType; - typedef typename OutputImageType::SizeValueType OutputSizeValueType; - typedef typename OutputImageType::IndexType OutputIndexType; - typedef typename OutputImageType::IndexValueType OutputIndexValueType; + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::PointType InputPointType; + typedef typename InputPointType::CoordRepType InputCoordRepType; + typedef typename InputImageType::IndexType InputIndexType; + typedef typename InputIndexType::IndexValueType InputIndexValueType; + typedef typename InputImageType::SizeType InputSizeType; + typedef typename InputSizeType::SizeValueType InputSizeValueType; + typedef typename InputImageType::RegionType InputRegionType; + typedef typename InputImageType::PixelType InputPixelType; + typedef typename InputImageType::SpacingType InputSpacingType; + + typedef TFeatureImage FeatureImageType; + typedef typename FeatureImageType::Pointer FeatureImagePointer; + typedef typename FeatureImageType::RegionType FeatureRegionType; + typedef typename FeatureImageType::SizeType FeatureSizeType; + typedef typename FeatureImageType::SpacingType FeatureSpacingType; + typedef typename FeatureImageType::PointType FeaturePointType; + typedef typename FeatureImageType::PixelType FeaturePixelType; + + typedef TOutputImage OutputImageType; + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::PixelType OutputPixelType; + typedef typename OutputImageType::RegionType OutputRegionType; + typedef typename OutputImageType::SizeType OutputSizeType; + typedef typename OutputImageType::SizeValueType OutputSizeValueType; + typedef typename OutputImageType::IndexType OutputIndexType; + typedef typename OutputImageType::IndexValueType OutputIndexValueType; typedef TIdCell IdCellType; typedef std::vector< IdCellType > VectorIdCellType; - /** Dimensionality of input and output data is assumed to be the same. */ - itkStaticConstMacro(ImageDimension, unsigned int, OutputImageType::ImageDimension); - /** The value type of the time step. This is distinct from PixelType * because PixelType may often be a vector value, while the TimeStep is * a scalar value. */ @@ -283,7 +296,7 @@ public: /** Get the number of elapsed iterations of the filter. */ itkGetConstReferenceMacro( ElapsedIterations, unsigned int ); - void SetLevelSet( const IdCellType & i, const InputImageType * levelSet ) + void SetLevelSet( const IdCellType & i, const InputImageType *levelSet ) { m_LevelSet[i] = InputImageType::New(); m_LevelSet[i]->SetRequestedRegion( levelSet->GetRequestedRegion() ); @@ -370,13 +383,13 @@ protected: this->m_KdTree = 0; this->m_ElapsedIterations = 0; this->m_MaximumRMSError = vnl_math::eps; - this->m_RMSChange = 100.0; + this->m_RMSChange = NumericTraits<double>::max(); this->m_UseImageSpacing = true; this->m_ManualReinitialization = false; this->m_InitializedState = false; this->m_NumberOfIterations = NumericTraits<unsigned int>::max(); this->m_FunctionCount = 0; - this->InPlaceOn(); + this->InPlaceOff(); } ~MultiphaseFiniteDifferenceImageFilter(){} diff --git a/Utilities/ITK/Code/Review/itkMultiphaseFiniteDifferenceImageFilter.txx b/Utilities/ITK/Code/Review/itkMultiphaseFiniteDifferenceImageFilter.txx index 980944f62a175ef9668cf44eab58353e1213b8d6..71d63a09c551a84691db7ba49c942d7fb438191c 100644 --- a/Utilities/ITK/Code/Review/itkMultiphaseFiniteDifferenceImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkMultiphaseFiniteDifferenceImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultiphaseFiniteDifferenceImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-05-20 22:03:45 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-09-08 20:09:41 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -27,11 +27,13 @@ namespace itk { template < class TInputImage, + class TFeatureImage, class TOutputImage, class TFiniteDifferenceFunction, typename TIdCell > void MultiphaseFiniteDifferenceImageFilter< TInputImage, + TFeatureImage, TOutputImage, TFiniteDifferenceFunction, TIdCell > @@ -68,7 +70,7 @@ MultiphaseFiniteDifferenceImageFilter< TInputImage, this->m_DifferenceFunctions[id]->SetScaleCoefficients(coeffs); } - // Allocate the output image -- inherited + // Allocate the output image -- inherited method this->AllocateOutputs(); // Copy the input image to the output image. Algorithms will operate @@ -82,23 +84,23 @@ MultiphaseFiniteDifferenceImageFilter< TInputImage, // the subclass, since this class cannot define an update buffer type. this->AllocateUpdateBuffer(); - this->SetInitializedState(true); - - this->m_ElapsedIterations = 0; + this->SetInitializedState( true ); } // Iterative algorithm TimeStepType dt; + // An optional method for precalculating global values, or setting + // up for the next iteration + this->InitializeIteration(); + this->m_RMSChange = NumericTraits<double>::max(); + while ( ! this->Halt() ) { - /* An optional method for precalculating global values, or setting - up for the next iteration*/ - this->InitializeIteration(); - dt = this->CalculateChange(); this->ApplyUpdate( dt ); + this->m_ElapsedIterations++; // Invoke the iteration event. @@ -110,6 +112,8 @@ MultiphaseFiniteDifferenceImageFilter< TInputImage, this->ResetPipeline(); throw ProcessAborted(__FILE__,__LINE__); } + + this->InitializeIteration(); } // Reset the state once execution is completed @@ -126,11 +130,13 @@ MultiphaseFiniteDifferenceImageFilter< TInputImage, * */ template < class TInputImage, + class TFeatureImage, class TOutputImage, class TFiniteDifferenceFunction, typename TIdCell > void MultiphaseFiniteDifferenceImageFilter< TInputImage, + TFeatureImage, TOutputImage, TFiniteDifferenceFunction, TIdCell > @@ -141,8 +147,8 @@ MultiphaseFiniteDifferenceImageFilter< TInputImage, Superclass::GenerateInputRequestedRegion(); // get pointers to the input - InputImagePointer inputPtr = - const_cast< InputImageType* >( this->GetInput(0) ); + FeatureImagePointer inputPtr = + const_cast< FeatureImageType* >( this->GetInput(0) ); if ( inputPtr.IsNull() ) { @@ -166,7 +172,7 @@ MultiphaseFiniteDifferenceImageFilter< TInputImage, // get a copy of the input requested region (should equal the output // requested region) - InputRegionType inputRequestedRegion; + FeatureRegionType inputRequestedRegion; inputRequestedRegion = inputPtr->GetRequestedRegion(); // pad the input requested region by the operator radius @@ -197,12 +203,14 @@ MultiphaseFiniteDifferenceImageFilter< TInputImage, } template < class TInputImage, + class TFeatureImage, class TOutputImage, class TFiniteDifferenceFunction, typename TIdCell > -typename MultiphaseFiniteDifferenceImageFilter< TInputImage, +typename MultiphaseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFiniteDifferenceFunction, TIdCell >::TimeStepType MultiphaseFiniteDifferenceImageFilter< TInputImage, + TFeatureImage, TOutputImage, TFiniteDifferenceFunction, TIdCell > @@ -248,11 +256,13 @@ MultiphaseFiniteDifferenceImageFilter< TInputImage, } template < class TInputImage, + class TFeatureImage, class TOutputImage, class TFiniteDifferenceFunction, typename TIdCell > bool MultiphaseFiniteDifferenceImageFilter< TInputImage, + TFeatureImage, TOutputImage, TFiniteDifferenceFunction, TIdCell > @@ -268,16 +278,18 @@ MultiphaseFiniteDifferenceImageFilter< TInputImage, this->UpdateProgress( progress ); return ( (this->GetElapsedIterations() >= this->m_NumberOfIterations) || - ( this->GetMaximumRMSError() >= m_RMSChange ) ); + ( this->GetMaximumRMSError() >= this->m_RMSChange ) ); } template < class TInputImage, + class TFeatureImage, class TOutputImage, class TFiniteDifferenceFunction, typename TIdCell > void MultiphaseFiniteDifferenceImageFilter< TInputImage, + TFeatureImage, TOutputImage, TFiniteDifferenceFunction, TIdCell > diff --git a/Utilities/ITK/Code/Review/itkMultiphaseSparseFiniteDifferenceImageFilter.h b/Utilities/ITK/Code/Review/itkMultiphaseSparseFiniteDifferenceImageFilter.h index 87044694b9773b66ef4eff72d650a550dd52bb5c..6702ae8e04feccb5adc38e731c5397e4f824a323 100644 --- a/Utilities/ITK/Code/Review/itkMultiphaseSparseFiniteDifferenceImageFilter.h +++ b/Utilities/ITK/Code/Review/itkMultiphaseSparseFiniteDifferenceImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultiphaseSparseFiniteDifferenceImageFilter.h,v $ Language: C++ - Date: $Date: 2009-05-15 20:43:38 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-09-08 20:09:41 $ + Version: $Revision: 1.14 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -176,16 +176,17 @@ namespace itk { * http://hdl.handle.net/1926/1533 * */ -template < class TInputImage, class TOutputImage, class TFunction, +template < class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell = unsigned int > class ITK_EXPORT MultiphaseSparseFiniteDifferenceImageFilter : - public MultiphaseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > + public MultiphaseFiniteDifferenceImageFilter< TInputImage, + TFeatureImage, TOutputImage, TFunction, TIdCell > { public: /** Standard class typedefs */ typedef MultiphaseSparseFiniteDifferenceImageFilter Self; - typedef MultiphaseFiniteDifferenceImageFilter< - TInputImage, TOutputImage, TFunction, TIdCell > Superclass; + typedef MultiphaseFiniteDifferenceImageFilter< TInputImage, + TFeatureImage, TOutputImage, TFunction, TIdCell > Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; @@ -195,32 +196,41 @@ public: /** Run-time type information (and related methods). */ itkTypeMacro( MultiphaseSparseFiniteDifferenceImageFilter, MultiphaseFiniteDifferenceImageFilter ); + itkStaticConstMacro( ImageDimension, unsigned int, Superclass::ImageDimension ); + /**Typedefs from the superclass */ typedef typename Superclass::TimeStepType TimeStepType; /** Information derived from the image types. */ typedef typename Superclass::InputImageType InputImageType; - typedef typename Superclass::InputSizeType InputSizeType; typedef typename Superclass::InputImagePointer InputImagePointer; typedef typename Superclass::InputRegionType InputRegionType; - typedef typename Superclass::InputSpacingType InputSpacingType; + typedef typename Superclass::InputSizeType InputSizeType; + typedef typename Superclass::InputSizeValueType InputSizeValueType; + typedef typename Superclass::InputIndexType InputIndexType; + typedef typename Superclass::InputIndexValueType InputIndexValueType; + typedef typename Superclass::InputPixelType InputPixelType; typedef typename Superclass::InputPointType InputPointType; + typedef typename Superclass::InputSpacingType InputSpacingType; + + typedef typename Superclass::FeatureImageType FeatureImageType; + typedef typename Superclass::FeatureSizeType FeatureSizeType; + typedef typename Superclass::FeatureImagePointer FeatureImagePointer; + typedef typename Superclass::FeatureRegionType FeatureRegionType; + typedef typename Superclass::FeatureSpacingType FeatureSpacingType; + typedef typename Superclass::FeaturePointType FeaturePointType; typedef typename Superclass::OutputImageType OutputImageType; typedef typename Superclass::OutputImagePointer OutputImagePointer; typedef typename Superclass::OutputRegionType OutputRegionType; typedef typename Superclass::OutputSizeType OutputSizeType; - typedef typename Superclass::OutputSizeValueType SizeValueType; - typedef typename OutputImageType::ValueType ValueType; typedef typename Superclass::OutputIndexType OutputIndexType; typedef typename Superclass::OutputIndexValueType OutputIndexValueType; typedef typename Superclass::OutputPixelType OutputPixelType; + typedef typename InputImageType::ValueType ValueType; typedef typename Superclass::IdCellType IdCellType; - - itkStaticConstMacro( ImageDimension, unsigned int, TOutputImage::ImageDimension ); - typedef typename Superclass::FiniteDifferenceFunctionType FiniteDifferenceFunctionType; typedef typename Superclass::FiniteDifferenceFunctionPointer @@ -252,11 +262,13 @@ public: StatusImageType; typedef typename StatusImageType::Pointer StatusImagePointer; - typedef ZeroCrossingImageFilter<OutputImageType, OutputImageType> + typedef ZeroCrossingImageFilter< InputImageType, InputImageType> ZeroCrossingFilterType; typedef typename ZeroCrossingFilterType::Pointer ZeroCrossingFilterPointer; + typedef NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< StatusImageType > BFCType; + /** Memory pre-allocator used to manage layer nodes in a multi-threaded * environment. */ typedef ObjectStore< LayerNodeType > LayerNodeStorageType; @@ -266,6 +278,10 @@ public: typedef std::vector< ValueType > UpdateBufferType; typedef typename UpdateBufferType::const_iterator UpdateBufferConstIterator; + typedef SparseFieldCityBlockNeighborList< + NeighborhoodIterator<OutputImageType> > NeighborListType; + typedef typename NeighborListType::OffsetType OffsetType; + /** Set/Get the number of layers to use in the sparse field. Argument is the * number of layers on ONE side of the active layer, so the total layers in * the sparse field is 2 * NumberOfLayers +1 */ @@ -339,10 +355,6 @@ protected: m_Index = index; } - /** Connectivity information for examining neighbor pixels. */ - SparseFieldCityBlockNeighborList< NeighborhoodIterator<OutputImageType> > - m_NeighborList; - /** An array which contains all of the layers needed in the sparse * field. Layers are organized as follows: m_Layer[0] = active layer, * m_Layer[i:odd] = inside layer (i+1)/2, m_Layer[i:even] = outside layer i/2 @@ -352,18 +364,22 @@ protected: /** An image of status values used internally by the algorithm. */ StatusImagePointer m_StatusImage; - OutputImagePointer m_ShiftedImage; - /** Storage for layer node objects. */ LayerNodeStoragePointer m_LayerNodeStore; - /** The update buffer used to store change values computed in + /** The update buffer used to store a vector of change values computed in * CalculateChange. */ UpdateBufferType m_UpdateBuffer; IdCellType m_Index; }; + /** Connectivity information for examining neighbor pixels. */ + NeighborListType m_NeighborList; + + /** Stores the distance between pixels in the neighborhood iterator. */ + std::vector< ValueType > m_PixelDistance; + /**This function allows a subclass to override the way in which updates to * output values are applied during each iteration. The default simply * follows the standard finite difference scheme of scaling the change by the @@ -398,7 +414,7 @@ protected: void CopyInputToOutput(); /** Reserves memory in the update buffer. Called before each iteration. */ - void AllocateUpdateBuffer(); + void AllocateUpdateBuffer(){} /** Applies the update buffer values to the active layer and reconstructs the * sparse field layers for the next iteration. */ @@ -423,6 +439,10 @@ to); /** Initializes the values of the active layer set. */ void InitializeActiveLayerValues(); + /** Initializes the pixel constants that will be set outside the + * sparse layer. */ + void InitializeBackgroundConstants(); + /** Adjusts the values in a single layer "to" using values in a neighboring * layer "from". The list of indicies in "to" are traversed and assigned * new values appropriately. Any indicies in "to" without neighbors in @@ -442,7 +462,7 @@ to); void PropagateFunctionLayerValues( unsigned int functionIndex ); /** Updates the active layer values using m_UpdateBuffer. Also creates an - * "up" and "down" list for promotion/demotion of indicies leaving the + * "up" and "down" list for promotion/demotion of indices leaving the * active set. */ void UpdateActiveLayerValues( TimeStepType dt, LayerType *StatusUpList, LayerType *StatusDownList ); @@ -457,7 +477,7 @@ to); void InitializeIteration(); virtual void UpdatePixel(unsigned int itkNotUsed(functionIndex), unsigned int itkNotUsed(idx), - NeighborhoodIterator<OutputImageType> & itkNotUsed(iterator), ValueType & itkNotUsed(newValue), + NeighborhoodIterator< InputImageType> & itkNotUsed(iterator), ValueType & itkNotUsed(newValue), bool & itkNotUsed(status) ){}; itkGetConstMacro( ValueZero, ValueType ); @@ -503,6 +523,9 @@ to); /** The value in the input which represents the isosurface of interest. */ ValueType m_IsoSurfaceValue; + /** The value of the pixel outside the sparse layers */ + ValueType m_BackgroundValue; + /** This flag tells the solver whether or not to interpolate for the actual surface location when calculating change at each active layer node. By default this is turned on. Subclasses which do not sample propagation @@ -515,6 +538,9 @@ private: unsigned int m_CurrentFunctionIndex; + double m_RMSSum; + unsigned int m_RMSCounter; + /** This flag is true when methods need to check boundary conditions and false when methods do not need to check for boundary conditions. */ bool m_BoundsCheckingActive; diff --git a/Utilities/ITK/Code/Review/itkMultiphaseSparseFiniteDifferenceImageFilter.txx b/Utilities/ITK/Code/Review/itkMultiphaseSparseFiniteDifferenceImageFilter.txx index 5e21f40f9730ab5e4a0bfb312928e76214778f38..674a1cf6b45db00c1b0f7b0b502c2da99915217c 100644 --- a/Utilities/ITK/Code/Review/itkMultiphaseSparseFiniteDifferenceImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkMultiphaseSparseFiniteDifferenceImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMultiphaseSparseFiniteDifferenceImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-05-15 20:41:19 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-09-10 01:17:34 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,32 +22,99 @@ namespace itk { -template < class TInputImage, class TOutputImage, class TFunction, typename TIdCell > -typename MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, +template<class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > +double MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > +::m_ConstantGradientValue = 1.0; + +template<class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > +const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, +TOutputImage, TFunction, TIdCell >::ValueType +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > +::m_ValueOne = NumericTraits<ITK_TYPENAME +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > +::ValueType >::One; + +template<class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > +const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, +TOutputImage, TFunction, TIdCell >::ValueType +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > +::m_ValueZero = NumericTraits<ITK_TYPENAME +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell >:: +ValueType>::Zero; + +template<class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > +const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, +TOutputImage, TFunction, TIdCell >::StatusType +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > +::m_StatusNull = NumericTraits< ITK_TYPENAME +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell >:: +StatusType >::NonpositiveMin(); + +template<class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > +const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, +TOutputImage, TFunction, TIdCell >::StatusType +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > +::m_StatusChanging = -1; + +template<class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > +const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, +TOutputImage, TFunction, TIdCell >::StatusType +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > +::m_StatusActiveChangingUp = -2; + +template<class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > +const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, +TOutputImage, TFunction, TIdCell >::StatusType +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > +::m_StatusActiveChangingDown = -3; + +template<class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > +const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, +TOutputImage, TFunction, TIdCell >::StatusType +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > +::m_StatusBoundaryPixel = -4; + +template<class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > +::MultiphaseSparseFiniteDifferenceImageFilter() +{ + this->m_CurrentFunctionIndex = 0; + this->m_IsoSurfaceValue = m_ValueZero; + this->m_BackgroundValue = NumericTraits<ValueType>::max(); + this->m_NumberOfLayers = ImageDimension; + this->m_InterpolateSurfaceLocation = true; + this->m_BoundsCheckingActive = false; +} + +template < class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > +typename MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell >::TimeStepType -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::CalculateChange() { + // Initialize to the maximum possible value TimeStepType minTimeStep = NumericTraits< TimeStepType >::max(); + TimeStepType timeStep; + InputSpacingType spacing = this->m_LevelSet[0]->GetSpacing(); - for ( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + // Calculate change across all the level-set functions + for ( IdCellType fId = 0; fId < this->m_FunctionCount; ++fId ) { - this->m_CurrentFunctionIndex = i; + this->m_CurrentFunctionIndex = fId; - const FiniteDifferenceFunctionPointer df = this->m_DifferenceFunctions[i]; + const FiniteDifferenceFunctionPointer df = this->m_DifferenceFunctions[fId]; - SparseDataStruct *sparsePtr = this->m_SparseData[i]; + SparseDataStruct *sparsePtr = this->m_SparseData[fId]; FiniteDifferenceFunctionFloatOffsetType offset; - ValueType norm_grad_phi_squared, dx_forward, dx_backward, forwardValue, - backwardValue, centerValue; + ValueType gradientMagnitudeSqr, + forward, backward, current; const ValueType MIN_NORM = 1.0e-6; + void *globalData = df->GetGlobalDataPointer(); - NeighborhoodIterator<OutputImageType> outputIt ( df->GetRadius(), - this->m_LevelSet[this->m_CurrentFunctionIndex], - this->m_LevelSet[this->m_CurrentFunctionIndex]->GetRequestedRegion() ); - TimeStepType timeStep; + NeighborhoodIterator< InputImageType > outputIt ( df->GetRadius(), + this->m_LevelSet[fId], this->m_LevelSet[fId]->GetRequestedRegion() ); if( m_BoundsCheckingActive == false ) { @@ -57,9 +124,9 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunctio sparsePtr->m_UpdateBuffer.clear(); sparsePtr->m_UpdateBuffer.reserve ( sparsePtr->m_Layers[0]->Size() ); - // Calculates the update values for the active layer indicies in this - // iteration. Iterates through the active layer index list, applying - // the level set function to the output image (level set image) at each + // Calculates the update values for the active layer indices in this + // iteration. Iterates through the active layer index list by evaluating + // the update to the output image (level set image) at each // index. Update values are stored in the update buffer. LayerConstIterator layerIt = sparsePtr->m_Layers[0]->Begin(); @@ -69,61 +136,59 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunctio { outputIt.SetLocation ( layerIt->m_Value ); - // Calculate the offset to the surface from the center of this + current = outputIt.GetCenterPixel(); + + // Calculate the offset to the surface from the current of this // neighborhood. This is used by some level set functions in sampling a // speed, advection, or curvature term. - if ( this->GetInterpolateSurfaceLocation() - && ( centerValue = outputIt.GetCenterPixel() ) != 0.0 ) + if ( this->GetInterpolateSurfaceLocation() && current != 0.0 ) { // Surface is at the zero crossing, so distance to surface is: - // phi(x) / norm(grad(phi)), where phi(x) is the center of the + // phi(x) / norm(grad(phi)), where phi(x) is the current of the // neighborhood. The location is therefore - // (i,j,k) - ( phi(x) * grad(phi(x)) ) / norm(grad(phi))^2 - norm_grad_phi_squared = 0.0; + // (i,j,k) - ( phi(x)/ norm(grad(phi))) * (grad(phi(x)) / norm(grad(phi)) ) + gradientMagnitudeSqr = 0.0; for ( j = 0; j < ImageDimension; ++j ) { - forwardValue = outputIt.GetNext ( j ); - backwardValue = outputIt.GetPrevious ( j ); + forward = outputIt.GetNext ( j ); + backward = outputIt.GetPrevious ( j ); - if ( forwardValue * backwardValue >= 0 ) + if ( forward * backward >= 0 ) { // Neighbors are same sign OR at least one neighbor is zero. - dx_forward = forwardValue - centerValue; - dx_backward = centerValue - backwardValue; - // Pick the larger magnitude derivative. - if ( ::vnl_math_abs ( dx_forward ) >::vnl_math_abs( dx_backward ) ) + if ( vnl_math_abs ( forward - current ) > vnl_math_abs( current - backward ) ) { - offset[j] = dx_forward; + offset[j] = ( forward - current ) / spacing[j]; } else { - offset[j] = dx_backward; + offset[j] = ( current - backward ) / spacing[j]; } } else //Neighbors are opposite sign, pick the direction of 0 surface. { - if ( forwardValue * centerValue < 0 ) + if ( forward * current < 0 ) { - offset[j] = forwardValue - centerValue; + offset[j] = ( forward - current ) / spacing[j]; } else { - offset[j] = centerValue - backwardValue; + offset[j] = ( current - backward ) / spacing[j]; } } - norm_grad_phi_squared += offset[j] * offset[j]; + gradientMagnitudeSqr += offset[j] * offset[j]; } // Adding sqrt imagedimension "extends the reach" of the // interpolation - // to surfaces that pass close to the center of cells. This is a + // to surfaces that pass close to the current of cells. This is a // heuristic fudge factor that improves interpolation and reduces // "wiggling" at convergence. - ValueType coeff = centerValue * vcl_sqrt( ImageDimension - + 0.5 )/ ( norm_grad_phi_squared + MIN_NORM ); + ValueType coeff = current * vcl_sqrt( ImageDimension + + 0.5 ) / ( gradientMagnitudeSqr + MIN_NORM ); for ( j = 0; j < ImageDimension; ++j ) { @@ -151,25 +216,27 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunctio minTimeStep = timeStep; } } - minTimeStep = 0.2; //FIXME finally assined to a constant + + minTimeStep = 0.2; //FIXME finally assigned to a constant + return minTimeStep; } -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +template<class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > void -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::ApplyUpdate ( TimeStepType dt ) { unsigned int j, k; - for ( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + for ( IdCellType fId = 0; fId < this->m_FunctionCount; ++fId ) { - this->m_CurrentFunctionIndex = i; + this->m_CurrentFunctionIndex = fId; - SparseDataStruct *sparsePtr = this->m_SparseData[this->m_CurrentFunctionIndex]; + SparseDataStruct *sparsePtr = this->m_SparseData[fId]; unsigned int t; StatusType up_to, up_search; @@ -177,23 +244,23 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, LayerPointerType UpList[2]; LayerPointerType DownList[2]; + for ( j = 0; j < 2; ++j ) { UpList[j] = LayerType::New(); DownList[j] = LayerType::New(); } - // Process the active layer. This step will update the values in the - //active - // layer as well as the values at indices that *will* become part of the - // active layer when they are promoted/demoted. Also records promotions, - // demotions in the m_StatusLayer for current active layer indices - // (i.e. those indices which will move inside or outside the active - // layers). + // Process the active layer. This step will update the values in the + // active layer as well as the values at indices that *will* become part + // of the active layer when they are promoted/demoted. Also records + // promotions, demotions in the UpList[0] and DownList[0] for current + // active layer indices (i.e. those indices which will move inside or outside + // the active layers). this->UpdateActiveLayerValues( dt, UpList[0], DownList[0] ); - // Process the status up/down lists. This is an iterative process which - // proceeds outwards from the active layer. Each iteration generates the + // Process the up/down lists. This is an iterative process which + // proceeds outwards from the active layer. Each iteration generates the // list for the next iteration. // First process the status lists generated on the active layer. @@ -246,12 +313,14 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, // which has already been updated). this->PropagateAllLayerValues(); } + this->m_CurrentFunctionIndex = 0; } -template < class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +template < class TInputImage, class TFeatureImage, class TOutputImage, + class TFunction, typename TIdCell > void -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::ProcessOutsideList ( LayerType *OutsideList, StatusType ChangeToStatus ) @@ -270,9 +339,9 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, } } -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +template<class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > void -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::ProcessStatusList ( LayerType *InputList, LayerType *OutputList, @@ -284,9 +353,9 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, bool bounds_status; LayerNodeType *node; StatusType neighbor_status; - NeighborhoodIterator<StatusImageType> - statusIt ( sparsePtr->m_NeighborList.GetRadius(), sparsePtr->m_StatusImage, - this->m_LevelSet[this->m_CurrentFunctionIndex]->GetRequestedRegion() ); + NeighborhoodIterator<StatusImageType> statusIt ( + m_NeighborList.GetRadius(), sparsePtr->m_StatusImage, + this->m_LevelSet[this->m_CurrentFunctionIndex]->GetRequestedRegion() ); if ( !m_BoundsCheckingActive ) { @@ -296,21 +365,21 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, // Push each index in the input list into its appropriate status layer // (ChangeToStatus) and update the status image value at that index. // Also examine the neighbors of the index to determine which need to go - // onto - // the output list (search for SearchForStatus). + // onto the output list (search for SearchForStatus). while ( ! InputList->Empty() ) { statusIt.SetLocation ( InputList->Front()->m_Value ); statusIt.SetCenterPixel ( ChangeToStatus ); node = InputList->Front(); // Must unlink from the input list - InputList->PopFront(); // _before_ transferring to another list. + InputList->PopFront(); // before transferring to another list. sparsePtr->m_Layers[ChangeToStatus]->PushFront ( node ); - for ( i = 0; i < sparsePtr->m_NeighborList.GetSize(); ++i ) + // Iterate through the neighbors of this status-changed node + for ( i = 0; i < m_NeighborList.GetSize(); ++i ) { neighbor_status = statusIt.GetPixel ( - sparsePtr->m_NeighborList.GetArrayIndex ( i ) ); + m_NeighborList.GetArrayIndex ( i ) ); // Have we bumped up against the boundary? If so, turn on bounds // checking. @@ -319,16 +388,17 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, m_BoundsCheckingActive = true; } + // Find neighbors that move into the list prior to the ChangeToStatus if ( neighbor_status == SearchForStatus ) { // mark this pixel so we don't add it twice. - statusIt.SetPixel ( sparsePtr->m_NeighborList.GetArrayIndex ( i ), + statusIt.SetPixel ( m_NeighborList.GetArrayIndex ( i ), m_StatusChanging, bounds_status ); if ( bounds_status == true ) { node = sparsePtr->m_LayerNodeStore->Borrow(); node->m_Value = statusIt.GetIndex() + - sparsePtr->m_NeighborList.GetNeighborhoodOffset ( i ); + m_NeighborList.GetNeighborhoodOffset ( i ); OutputList->PushFront ( node ); } // else this index was out of bounds. } @@ -336,9 +406,10 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, } } -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > + +template<class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > void -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::UpdateActiveLayerValues ( TimeStepType dt, LayerType *UpList, LayerType @@ -353,37 +424,39 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, // assigned new values if they are determined to be part of the active list // for the next iteration (i.e. their values will be raised or lowered into // the active range). + + // These need to take into account the spacing ?? const ValueType LOWER_ACTIVE_THRESHOLD = -( m_ConstantGradientValue/2.0 ); const ValueType UPPER_ACTIVE_THRESHOLD = m_ConstantGradientValue / 2.0; - ValueType new_value, temp_value, rms_change_accumulator; + ValueType new_value, temp_value; LayerNodeType *node, *release_node; StatusType neighbor_status; - unsigned int i, idx, counter; + unsigned int i, idx; bool bounds_status, flag; LayerIterator layerIt; UpdateBufferConstIterator updateIt; - NeighborhoodIterator< OutputImageType > - outputIt ( sparsePtr->m_NeighborList.GetRadius(), - this->m_LevelSet[this->m_CurrentFunctionIndex], - this->m_LevelSet[this->m_CurrentFunctionIndex]->GetRequestedRegion() ); + NeighborhoodIterator< InputImageType > + outputIt ( m_NeighborList.GetRadius(), + this->m_LevelSet[this->m_CurrentFunctionIndex], + this->m_LevelSet[this->m_CurrentFunctionIndex]->GetRequestedRegion() ); NeighborhoodIterator< StatusImageType > - statusIt ( sparsePtr->m_NeighborList.GetRadius(), - sparsePtr->m_StatusImage, - this->m_LevelSet[this->m_CurrentFunctionIndex]->GetRequestedRegion() ); + statusIt ( m_NeighborList.GetRadius(), + sparsePtr->m_StatusImage, + this->m_LevelSet[this->m_CurrentFunctionIndex]->GetRequestedRegion() ); + // If bounds checking is turned on if ( !m_BoundsCheckingActive ) { outputIt.NeedToUseBoundaryConditionOff(); statusIt.NeedToUseBoundaryConditionOff(); } - counter = 0; - rms_change_accumulator = m_ValueZero; - + // Iterate over the update buffer and active layer + // Both are the same size layerIt = sparsePtr->m_Layers[0]->Begin(); updateIt = sparsePtr->m_UpdateBuffer.begin(); @@ -408,14 +481,15 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, if ( new_value >= UPPER_ACTIVE_THRESHOLD ) { - // This index will move UP into a positive (outside) layer. + // This index will move UP into a positive (outside) layer. Contour is shrinking + // into the negative layers. - // First check for active layer neighbors moving in the opposite - // direction. + // First check for neighbors that belong to the active layer and moving + // in the opposite direction. flag = false; - for ( i = 0; i < sparsePtr->m_NeighborList.GetSize(); ++i ) + for ( i = 0; i < m_NeighborList.GetSize(); ++i ) { - if ( statusIt.GetPixel( sparsePtr->m_NeighborList.GetArrayIndex( i ) ) + if ( statusIt.GetPixel( m_NeighborList.GetArrayIndex( i ) ) == m_StatusActiveChangingDown ) { flag = true; @@ -430,50 +504,49 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, continue; } - rms_change_accumulator += vnl_math_sqr ( new_value-outputIt.GetCenterPixel() ); - // Search the neighborhood for inside indicies. - temp_value = new_value - m_ConstantGradientValue; - for ( i = 0; i < sparsePtr->m_NeighborList.GetSize(); ++i ) + for ( i = 0; i < m_NeighborList.GetSize(); ++i ) { - idx = sparsePtr->m_NeighborList.GetArrayIndex ( i ); + temp_value = new_value - m_ConstantGradientValue * m_PixelDistance[i]; + idx = m_NeighborList.GetArrayIndex ( i ); neighbor_status = statusIt.GetPixel ( idx ); + // 1 is first negative layer that will come into the active layer if ( neighbor_status == 1 ) { // Keep the smallest possible value for the new active node. This // places the new active layer node closest to the zero level-set. if ( outputIt.GetPixel ( idx ) < LOWER_ACTIVE_THRESHOLD || - ::vnl_math_abs ( temp_value ) < ::vnl_math_abs ( + vnl_math_abs ( temp_value ) < vnl_math_abs ( outputIt.GetPixel ( idx ) ) ) { UpdatePixel ( this->m_CurrentFunctionIndex, idx, outputIt, temp_value, bounds_status ); } } } - // Push it into the uplist + // Push current active layer pixel into the uplist node = sparsePtr->m_LayerNodeStore->Borrow(); node->m_Value = layerIt->m_Value; UpList->PushFront ( node ); statusIt.SetCenterPixel ( m_StatusActiveChangingUp ); - // Now remove this index from the active list. + // Now remove this pixel from the active list. release_node = layerIt.GetPointer(); - ++layerIt; sparsePtr->m_Layers[0]->Unlink ( release_node ); sparsePtr->m_LayerNodeStore->Return ( release_node ); } else if ( new_value < LOWER_ACTIVE_THRESHOLD ) { - // This index will move DOWN into a negative (inside) layer. + // This index will move DOWN into a negative (inside) layer. 2 in the + // positive sparse field will come in // First check for active layer neighbors moving in the opposite // direction. flag = false; - for ( i = 0; i < sparsePtr->m_NeighborList.GetSize(); ++i ) + for ( i = 0; i < m_NeighborList.GetSize(); ++i ) { - if ( statusIt.GetPixel( sparsePtr->m_NeighborList.GetArrayIndex( i ) ) + if ( statusIt.GetPixel( m_NeighborList.GetArrayIndex( i ) ) == m_StatusActiveChangingUp ) { flag = true; @@ -488,26 +561,25 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, continue; } - rms_change_accumulator += vnl_math_sqr ( new_value - outputIt.GetCenterPixel() ); - // Search the neighborhood for outside indicies. - temp_value = new_value + m_ConstantGradientValue; - for ( i = 0; i < sparsePtr->m_NeighborList.GetSize(); ++i ) + for ( i = 0; i < m_NeighborList.GetSize(); ++i ) { - idx = sparsePtr->m_NeighborList.GetArrayIndex ( i ); + temp_value = new_value + m_ConstantGradientValue * m_PixelDistance[i]; + idx = m_NeighborList.GetArrayIndex ( i ); neighbor_status = statusIt.GetPixel ( idx ); if ( neighbor_status == 2 ) { // Keep the smallest magnitude value for this active set node. This // places the node closest to the active layer. if ( outputIt.GetPixel ( idx ) >= UPPER_ACTIVE_THRESHOLD || - ::vnl_math_abs ( temp_value ) < ::vnl_math_abs ( + vnl_math_abs ( temp_value ) < vnl_math_abs ( outputIt.GetPixel ( idx ) ) ) { UpdatePixel ( this->m_CurrentFunctionIndex, idx, outputIt, temp_value, bounds_status ); } } } + // Push current active layer pixel into the downlist node = sparsePtr->m_LayerNodeStore->Borrow(); node->m_Value = layerIt->m_Value; DownList->PushFront ( node ); @@ -515,65 +587,52 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, // Now remove this index from the active list. release_node = layerIt.GetPointer(); - ++layerIt; sparsePtr->m_Layers[0]->Unlink ( release_node ); sparsePtr->m_LayerNodeStore->Return ( release_node ); } else { - rms_change_accumulator += vnl_math_sqr ( new_value - outputIt.GetCenterPixel() ); - - UpdatePixel ( this->m_CurrentFunctionIndex, outputIt.Size() >> 1, outputIt, new_value, bounds_status ); - - ++layerIt; + UpdatePixel( this->m_CurrentFunctionIndex, outputIt.Size()/2, outputIt, new_value, bounds_status ); } - ++updateIt; - ++counter; - } - // Determine the average change during this iteration. - if ( counter == 0 ) - { - this->SetRMSChange ( static_cast<double> ( m_ValueZero ) ); - } - else - { - this->SetRMSChange ( - vcl_sqrt ( static_cast< double >( rms_change_accumulator / - static_cast<double> ( counter ) ) ) ); + // Move to the next active layer pixel + ++layerIt; + ++updateIt; } } -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +template<class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > void -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::InitializeActiveLayerValues() { - const ValueType CHANGE_FACTOR = m_ConstantGradientValue / 2.0; - // const ValueType CHANGE_FACTOR = 0.7; + // Initialize all active layer pixels to values computed as distance + // to the 0 contour. Similar to the fast marching initial seeds. + const ValueType MIN_NORM = 1.0e-6; + InputSpacingType spacing = this->m_LevelSet[0]->GetSpacing(); + double temp; for ( IdCellType i = 0; i < this->m_FunctionCount; i++ ) { SparseDataStruct *sparsePtr = this->m_SparseData[i]; - unsigned int center; + InputImagePointer levelset = this->m_LevelSet[i]; typename LayerType::ConstIterator activeIt; - ConstNeighborhoodIterator<OutputImageType> - outputIt ( sparsePtr->m_NeighborList.GetRadius(), - this->m_LevelSet[i], - this->m_LevelSet[i]->GetRequestedRegion() ); + ConstNeighborhoodIterator< InputImageType > outputIt ( + m_NeighborList.GetRadius(), + levelset, levelset->GetRequestedRegion() ); sparsePtr->m_UpdateBuffer.clear(); sparsePtr->m_UpdateBuffer.reserve ( sparsePtr->m_Layers[0]->Size() ); + unsigned int center; // index to active layer pixel center = outputIt.Size()/2; - typename OutputImageType::Pointer output = this->m_LevelSet[i]; - - ValueType dx_forward, dx_backward, length, distance; + ValueType dx, gradientMagnitude, gradientMagnitudeSqr, + distance, forward, current, backward; // For all indicies in the active layer... activeIt = sparsePtr->m_Layers[0]->Begin(); @@ -583,70 +642,98 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, // assign an active layer value in the output image. outputIt.SetLocation ( activeIt->m_Value ); - length = m_ValueZero; + gradientMagnitudeSqr = m_ValueZero; for ( unsigned int j = 0; j < ImageDimension; ++j ) { - dx_forward = outputIt.GetPixel ( center + - sparsePtr->m_NeighborList.GetStride( j ) ) - - outputIt.GetCenterPixel(); - dx_backward = outputIt.GetCenterPixel() - - outputIt.GetPixel ( center - - sparsePtr->m_NeighborList.GetStride ( j ) ); - - if ( vnl_math_abs ( dx_forward ) > vnl_math_abs ( dx_backward ) ) + // Compute forward and backward pixel values + forward = outputIt.GetPixel ( center + m_NeighborList.GetStride( j ) ); + current = outputIt.GetCenterPixel(); + backward = outputIt.GetPixel ( center - m_NeighborList.GetStride ( j ) ); + + if ( forward * backward >= 0 ) { - length += dx_forward * dx_forward; + // Neighbors are same sign OR at least one neighbor is zero. + // Pick the larger magnitude derivative. + if ( ::vnl_math_abs ( forward - center ) >::vnl_math_abs( center - backward ) ) + { + dx = ( forward - current ) / spacing[j]; + } + else + { + dx = ( current - backward ) / spacing[j]; + } } else { - length += dx_backward * dx_backward; + // Choose the derivative closest to the 0 contour + if ( vnl_math_sgn( current*forward ) == -1 ) + { + dx = ( forward - current ) / spacing[j]; + } + else + { + dx = ( current - backward ) / spacing[j]; + } } + gradientMagnitudeSqr += dx * dx; } - length = vcl_sqrt ( length ) + MIN_NORM; - distance = outputIt.GetCenterPixel() / length; + gradientMagnitude = vcl_sqrt ( gradientMagnitudeSqr ) + MIN_NORM; + + // Compute the correct distance as phi(x)/gradientMagnitude + distance = outputIt.GetCenterPixel() / gradientMagnitude; + // Insert in the update buffer sparsePtr->m_UpdateBuffer.push_back( - vnl_math_min ( vnl_math_max ( -CHANGE_FACTOR, distance ), - CHANGE_FACTOR ) ); + vnl_math_min ( vnl_math_max ( -MIN_NORM, distance ), + MIN_NORM ) ); ++activeIt; } + // Update the level-set image using the update buffer activeIt = sparsePtr->m_Layers[0]->Begin(); while( activeIt != sparsePtr->m_Layers[0]->End() ) { - output->SetPixel ( activeIt->m_Value, sparsePtr->m_UpdateBuffer.front() ); + // Update the accumulator value using the update buffer + temp = static_cast< double > ( sparsePtr->m_UpdateBuffer.front() + - levelset->GetPixel ( activeIt->m_Value ) ); + m_RMSSum += temp * temp; + m_RMSCounter++; + + levelset->SetPixel ( activeIt->m_Value, sparsePtr->m_UpdateBuffer.front() ); ++activeIt; } } } -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +template<class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > void -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::PropagateAllLayerValues() { for ( IdCellType i = 0; i < this->m_FunctionCount; i++ ) { + // Calls the UpdatePixel(...) function inside PropagateFunctionLayerValues ( i ); } } -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +template<class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > void -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > -::PropagateFunctionLayerValues ( unsigned int functionIndex ) +::PropagateFunctionLayerValues ( unsigned int fId ) { - SparseDataStruct *sparsePtr = this->m_SparseData[functionIndex]; + SparseDataStruct *sparsePtr = this->m_SparseData[fId]; // Update values in the first inside and first outside layers using the // active layer as a seed. Inside layers are odd numbers, outside layers are // even numbers. + this->PropagateLayerValues ( sparsePtr, 0, 1, 3, 1 ); // first inside this->PropagateLayerValues ( sparsePtr, 0, 2, 4, 2 ); // first outside @@ -657,14 +744,17 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, } } -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +template<class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > void -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::PropagateLayerValues ( SparseDataStruct *sparsePtr, StatusType from, StatusType to, StatusType promote, int InOrOut ) { + // InOrOut indicates whether we are propagating in the negative/positive region + // of the level-set function + unsigned int i; ValueType value_temp, delta; ValueType value = NumericTraits<ValueType>::Zero; // warnings @@ -674,23 +764,16 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, StatusType past_end = static_cast<StatusType>( sparsePtr->m_Layers.size() )-1; - // Are we propagating values inward (more negative) or outward (more + // Are we propagating values inward (-1, more negative) or outward (1, more // positive)? - if ( InOrOut == 1 ) - { - delta = - m_ConstantGradientValue; - } - else - { - delta = m_ConstantGradientValue; - } + delta = ( InOrOut == 1 ) ? -1: 1; - NeighborhoodIterator<OutputImageType> - outputIt ( sparsePtr->m_NeighborList.GetRadius(), + NeighborhoodIterator< InputImageType > + outputIt ( m_NeighborList.GetRadius(), this->m_LevelSet[sparsePtr->m_Index], this->m_LevelSet[sparsePtr->m_Index]->GetRequestedRegion() ); - NeighborhoodIterator<StatusImageType> - statusIt ( sparsePtr->m_NeighborList.GetRadius(), sparsePtr->m_StatusImage, + NeighborhoodIterator< StatusImageType > + statusIt ( m_NeighborList.GetRadius(), sparsePtr->m_StatusImage, this->m_LevelSet[sparsePtr->m_Index]->GetRequestedRegion() ); if ( !m_BoundsCheckingActive ) @@ -699,10 +782,13 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, statusIt.NeedToUseBoundaryConditionOff(); } + // Iterate over the to-layer to fill the values in the output image toIt = sparsePtr->m_Layers[to]->Begin(); while ( toIt != sparsePtr->m_Layers[to]->End() ) { - statusIt.SetLocation ( toIt->m_Value ); + // Set the iterator location in the status image + OutputIndexType indexCurrent = toIt->m_Value; + statusIt.SetLocation ( indexCurrent ); // Is this index marked for deletion? If the status image has // been marked with another layer's value, we need to delete this node @@ -716,17 +802,34 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, continue; } + // Set the iterator location in the level-set image outputIt.SetLocation ( toIt->m_Value ); + // We explore all neighbors to identify the closest from-layer node found_neighbor_flag = false; - for ( i = 0; i < sparsePtr->m_NeighborList.GetSize(); ++i ) + unsigned int indexNeighbor; + for ( i = 0; i < m_NeighborList.GetSize(); ++i ) { // If this neighbor is in the "from" list, compare its absolute value - // to to any previous values found in the "from" list. Keep the value - // that will cause the next layer to be closest to the zero level set. - if ( statusIt.GetPixel ( sparsePtr->m_NeighborList.GetArrayIndex ( i ) ) == from ) + // to any previous values found in the "from" list. Keep the value + // that will cause the to-layer to be closest to the zero level set. + indexNeighbor = m_NeighborList.GetArrayIndex ( i ); // Get index + if ( statusIt.GetPixel ( indexNeighbor ) == from ) // if belongs to from-layer { - value_temp = outputIt.GetPixel ( sparsePtr->m_NeighborList.GetArrayIndex ( i ) ); + // This value should be a distance in terms of spacing with neighbors + // plus its current value + + InputPointType p1, p2; + ValueType dist = 0; // compute the distance between neighbors + this->m_LevelSet[sparsePtr->m_Index]->TransformIndexToPhysicalPoint( + statusIt.GetIndex( indexNeighbor ), p1 ); + this->m_LevelSet[sparsePtr->m_Index]->TransformIndexToPhysicalPoint( + indexCurrent, p2); + for( unsigned int j = 0; j < ImageDimension; j++ ) + dist += (p1[j] - p2[j]) * (p1[j] - p2[j]); + dist = delta * vcl_sqrt( dist ); + + value_temp = dist + outputIt.GetPixel ( indexNeighbor ); // grab its value if ( !found_neighbor_flag ) { @@ -734,7 +837,9 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, } else { - if ( InOrOut == 1 ) + // Irrespective of negative/positive region, select the lowest absolute minimum + //value = delta * vnl_math_min( vnl_math_abs( value_temp ), vnl_math_abs( value ) ); + if ( InOrOut == 1 ) // inward { // Find the largest (least negative) neighbor if ( value_temp > value ) @@ -750,6 +855,7 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, value = value_temp; } } + } found_neighbor_flag = true; } @@ -760,9 +866,13 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, // Set the new value using the smallest distance // found in our "from" neighbors. bool bounds_status; - ValueType updateValue = value + delta; + unsigned int center = outputIt.Size()/2; + + UpdatePixel(sparsePtr->m_Index, center, outputIt, value, bounds_status); - UpdatePixel ( sparsePtr->m_Index, outputIt.Size() >>1, outputIt, updateValue, bounds_status ); + // Update the rms change + m_RMSSum += ( value - outputIt.GetCenterPixel() ) * ( value - outputIt.GetCenterPixel() ); + m_RMSCounter++; ++toIt; } @@ -778,7 +888,11 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, if ( promote > past_end ) { sparsePtr->m_LayerNodeStore->Return ( node ); + // Reset the pixel status to null -- does not belong to sparse layer statusIt.SetCenterPixel ( m_StatusNull ); + // Set the pixel to its default background value + this->m_LevelSet[sparsePtr->m_Index]->SetPixel( indexCurrent , + delta * this->m_BackgroundValue ); } else { @@ -789,183 +903,157 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, } } - -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > -double MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, TOutputImage, TFunction, TIdCell > -::m_ConstantGradientValue = 1.0; - -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > -const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, -TOutputImage, TFunction, TIdCell >::ValueType -MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, TOutputImage, TFunction, TIdCell > -::m_ValueOne = NumericTraits<ITK_TYPENAME -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > -::ValueType >::One; - -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > -const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, -TOutputImage, TFunction, TIdCell >::ValueType -MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, TOutputImage, TFunction, TIdCell > -::m_ValueZero = NumericTraits<ITK_TYPENAME -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell >:: -ValueType>::Zero; - -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > -const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, -TOutputImage, TFunction, TIdCell >::StatusType -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > -::m_StatusNull = NumericTraits< ITK_TYPENAME -MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, TOutputImage, TFunction, TIdCell >:: -StatusType >::NonpositiveMin(); - -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > -const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, -TOutputImage, TFunction, TIdCell >::StatusType -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > -::m_StatusChanging = -1; - -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > -const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, -TOutputImage, TFunction, TIdCell >::StatusType -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > -::m_StatusActiveChangingUp = -2; - -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > -const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, -TOutputImage, TFunction, TIdCell >::StatusType -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > -::m_StatusActiveChangingDown = -3; - -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > -const ITK_TYPENAME MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, -TOutputImage, TFunction, TIdCell >::StatusType -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > -::m_StatusBoundaryPixel = -4; - -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > -::MultiphaseSparseFiniteDifferenceImageFilter() -{ - this->m_CurrentFunctionIndex = 0; - this->m_IsoSurfaceValue = m_ValueZero; - this->m_NumberOfLayers = ImageDimension; - this->SetRMSChange ( NumericTraits< double >::Zero ); - this->m_InterpolateSurfaceLocation = true; - this->m_BoundsCheckingActive = false; -} - -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +template<class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > void -MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, TOutputImage, TFunction, TIdCell > +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::CopyInputToOutput() { for( IdCellType i = 0; i < this->m_FunctionCount; i++ ) { - SparseDataStruct * sparsePtr = this->m_SparseData[i]; - OutputImagePointer input = this->m_LevelSet[i]; - - // This is used as a temporary buffer in this specific instance - // However, we need to use it later on. Therefore, its instantiation - // is important. DO NOT DELETE. - sparsePtr->m_ShiftedImage = OutputImageType::New(); - sparsePtr->m_ShiftedImage->SetRegions( input->GetRequestedRegion() ); - sparsePtr->m_ShiftedImage->Allocate(); - sparsePtr->m_ShiftedImage->CopyInformation( input ); - - // Copy input to ShiftedImage - // TODO: Is there a better way to do this?? - // - OutputRegionType region = input->GetRequestedRegion(); - ImageRegionIterator<OutputImageType> lIt( input, region ); - ImageRegionIterator<OutputImageType> sIt( sparsePtr->m_ShiftedImage, region ); + InputImagePointer input = this->m_LevelSet[i]; + + // This is used as a temporary buffer + InputImagePointer tempImage = InputImageType::New(); + tempImage->SetRegions( input->GetRequestedRegion() ); + tempImage->CopyInformation( input ); + tempImage->Allocate(); + + // Compute Heaviside of input image + // Copy input to temp + InputRegionType region = input->GetRequestedRegion(); + ImageRegionIterator< InputImageType > lIt( input, region ); + ImageRegionIterator< InputImageType > tIt( tempImage, region ); lIt.GoToBegin(); - sIt.GoToBegin(); + tIt.GoToBegin(); while( !lIt.IsAtEnd() ) { - sIt.Set( lIt.Get() ); - ++sIt; + tIt.Set( lIt.Get() ); + ++tIt; ++lIt; } // TODO: Can the zeroCrossingFilter have the same input and output? ZeroCrossingFilterPointer zeroCrossingFilter = ZeroCrossingFilterType::New(); - zeroCrossingFilter->SetInput( sparsePtr->m_ShiftedImage ); + zeroCrossingFilter->SetInput( tempImage ); zeroCrossingFilter->SetBackgroundValue( m_ValueOne ); zeroCrossingFilter->SetForegroundValue( m_ValueZero ); zeroCrossingFilter->Update(); - this->m_LevelSet[i] = zeroCrossingFilter->GetOutput(); - this->m_LevelSet[i]->DisconnectPipeline(); + // The levelset image has a 0 where the zero contour exists and + outside and - inside + ImageRegionIterator< InputImageType > zIt( zeroCrossingFilter->GetOutput(), region ); + + lIt.GoToBegin(); + zIt.GoToBegin(); + + while( !lIt.IsAtEnd() ) + { + if ( zIt.Get() == 0 ) + { + lIt.Set( 0 ); + } + ++zIt; + ++lIt; + } } } -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +template< class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > void -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::InitializeIteration() { Superclass::InitializeIteration(); + m_RMSSum = 0.; + m_RMSCounter = 0; // counter + // Set the values in the output image for the active layer. this->InitializeActiveLayerValues(); - // Initialize layer values using the active layer as seeds. + // Initialize layer values using the active layer as seeds this->PropagateAllLayerValues(); + + // Determine the average RMS of change during this iteration + if ( m_RMSCounter == 0 ) + { + this->SetRMSChange ( static_cast<double> ( 0. ) ); + } + else + { + this->SetRMSChange ( vcl_sqrt ( m_RMSSum / m_RMSCounter ) ); + } } -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +template< class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > void -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::Initialize() { - IdCellType functionIndex; - - for ( functionIndex = 0; functionIndex < this->m_FunctionCount; - functionIndex++ ) + // Initialize m_PixelDistance values for the corresponding neighborhood list + // This stores the distance between neighbors. Usually same as 1 except when + // the image spacing is different. + InputSpacingType spacing = this->m_LevelSet[0]->GetSpacing(); + OffsetType offset; + this->m_PixelDistance.clear(); + this->m_PixelDistance.resize ( m_NeighborList.GetSize() ); + for ( unsigned int i = 0; i < m_NeighborList.GetSize(); ++i ) { - SparseDataStruct *sparsePtr = this->m_SparseData[functionIndex]; + offset = m_NeighborList.GetNeighborhoodOffset ( i ); + m_PixelDistance[i] = 0; + for( unsigned int j = 0; j < ImageDimension; j++ ) + { + m_PixelDistance[i] += offset[j]*spacing[j]*offset[j]*spacing[j]; + } + m_PixelDistance[i] = vcl_sqrt( m_PixelDistance[i] ); + } - unsigned int i; + + for ( IdCellType fId = 0; fId < this->m_FunctionCount; ++fId ) + { + SparseDataStruct *sparsePtr = this->m_SparseData[fId]; // Allocate the status image. sparsePtr->m_StatusImage = StatusImageType::New(); sparsePtr->m_StatusImage->SetRegions ( - this->m_LevelSet[functionIndex]->GetRequestedRegion() ); + this->m_LevelSet[fId]->GetRequestedRegion() ); + sparsePtr->m_StatusImage->CopyInformation( this->m_LevelSet[fId] ); sparsePtr->m_StatusImage->Allocate(); sparsePtr->m_StatusImage->FillBuffer( m_StatusNull );//NonpositiveMin // Initialize the boundary pixels in the status image to // m_StatusBoundaryPixel values. Uses the face calculator to find all of // the region faces. - typedef NeighborhoodAlgorithm::ImageBoundaryFacesCalculator< StatusImageType > BFCType; - BFCType faceCalculator; typename BFCType::FaceListType faceList; - typename BFCType::SizeType sz; + + // Set the difference function radius here + typename BFCType::SizeType sz = this->m_DifferenceFunctions[fId]->GetRadius(); typename BFCType::FaceListType::iterator fit; - sz.Fill ( 1 ); // Set the difference function radius here + // Compute the boundary pixel regions set in a container faceList = faceCalculator ( sparsePtr->m_StatusImage, sparsePtr->m_StatusImage->GetRequestedRegion(), sz ); - fit = faceList.begin(); + // Iterate over the boundary region sets + fit = faceList.begin(); for( ++fit; fit != faceList.end(); ++fit ) { + // For each region, set the pixel in m_StatusImage to m_StatusBoundaryPixel ImageRegionIterator<StatusImageType> statusIt( sparsePtr->m_StatusImage, *fit ); statusIt.GoToBegin(); while( ! statusIt.IsAtEnd() ) { - statusIt.Set ( m_StatusBoundaryPixel );// -4 : FIXME: What does "-4" means here ? + statusIt.Set ( m_StatusBoundaryPixel ); ++statusIt; } } - // Erase all existing layer lists. - for ( i = 0; i < sparsePtr->m_Layers.size(); ++i ) + // Erase all existing layer lists -- element by element + for ( unsigned int i = 0; i < sparsePtr->m_Layers.size(); ++i ) { while ( ! sparsePtr->m_Layers[i]->Empty() ) { @@ -991,18 +1079,24 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunctio } } + // Set the background constants required to be set outside the sparse layer + this->InitializeBackgroundConstants(); + // Construct the active layer and initialize the first layers inside and - // outside of the active layer. + // outside of the active layer for all level-set functions. this->ConstructActiveLayer(); - for ( functionIndex = 0; functionIndex < this->m_FunctionCount; functionIndex++ ) + for ( IdCellType fId = 0; fId < this->m_FunctionCount; ++fId ) { - SparseDataStruct *sparsePtr = this->m_SparseData[functionIndex]; + SparseDataStruct *sparsePtr = this->m_SparseData[fId]; // Construct the rest of the non-active set layers using the first two // layers. Inside layers are odd numbers, outside layers are even numbers. + // We need to loop from i = 1 to m_Layers.size()-2 since the last two layers + // are constructed in the previous iteration for ( unsigned int i = 1; i < sparsePtr->m_Layers.size() - 2; ++i ) { + // Construct layer i+2 from layer i. Note that layer i+1 is on the other side this->ConstructLayer( sparsePtr, i, i+2 ); } } @@ -1010,57 +1104,57 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunctio // Set the values in the output image for the active layer. this->InitializeActiveLayerValues(); - // Initialize layer values using the active layer as seeds. + // Initialize layer values using the active layer as seeds this->PropagateAllLayerValues(); - // Initialize pixels inside and outside the sparse field layers to positive - // and negative values, respectively?? This is not necessary for the + // Initialize pixels outside the sparse field layers to positive + // and negative values, respectively. This is not necessary for the // calculations, but is useful for presenting a more intuitive output to the // filter. See PostProcessOutput method for more information. this->InitializeBackgroundPixels(); +} - // for ( functionIndex = 0; functionIndex < this->m_FunctionCount; functionIndex++ ) - // { - // // Delete status image - // this->m_SparseData[functionIndex]->m_ShiftedImage->Delete(); - // } +template< class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > +void +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > +::InitializeBackgroundConstants() +{ + // Determine the maximum spacing to set the background pixel values + // outside the sparse field + float maxSpacing = NumericTraits<float>::min(); + InputSpacingType spacing = this->m_LevelSet[0]->GetSpacing(); + for( unsigned int i = 0; i < ImageDimension; i++ ) + maxSpacing = vnl_math_max( maxSpacing, static_cast<float>( spacing[i] ) ); + + // Assign background pixels OUTSIDE the sparse field layers to a new level + // set with value greater than the outermost layer. Assign background pixels + // INSIDE the sparse field layers to a new level set with value less than + // the innermost layer. + const ValueType max_layer = static_cast<ValueType> ( this->m_NumberOfLayers ); + + this->m_BackgroundValue = ( max_layer + 1 ) * maxSpacing; } -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > + +template< class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > void -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::InitializeBackgroundPixels() { - for ( IdCellType functionIndex = 0; functionIndex < this->m_FunctionCount; - functionIndex++ ) + for ( IdCellType fId = 0; fId < this->m_FunctionCount; fId++ ) { - SparseDataStruct *sparsePtr = this->m_SparseData[functionIndex]; - - // Assign background pixels OUTSIDE the sparse field layers to a new level - // set - // with value greater than the outermost layer. Assign background pixels - // INSIDE the sparse field layers to a new level set with value less than - // the innermost layer. - const ValueType max_layer = static_cast<ValueType> ( this->m_NumberOfLayers ); - - const ValueType outside_value = max_layer + m_ConstantGradientValue; - const ValueType inside_value = - ( max_layer + m_ConstantGradientValue ); + SparseDataStruct *sparsePtr = this->m_SparseData[fId]; ImageRegionConstIterator<StatusImageType> statusIt ( sparsePtr->m_StatusImage, - this->m_LevelSet[functionIndex]->GetRequestedRegion() ); - - ImageRegionIterator<OutputImageType> outputIt ( - this->m_LevelSet[functionIndex], - this->m_LevelSet[functionIndex]->GetRequestedRegion() ); + this->m_LevelSet[fId]->GetRequestedRegion() ); - ImageRegionIterator<OutputImageType> shiftedIt ( - sparsePtr->m_ShiftedImage, - this->m_LevelSet[functionIndex]->GetRequestedRegion() ); + ImageRegionIterator< InputImageType > outputIt ( + this->m_LevelSet[fId], + this->m_LevelSet[fId]->GetRequestedRegion() ); outputIt.GoToBegin(); - shiftedIt.GoToBegin(); statusIt.GoToBegin(); while( !outputIt.IsAtEnd() ) @@ -1068,16 +1162,15 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunctio if( statusIt.Get() == m_StatusNull || statusIt.Get() == m_StatusBoundaryPixel ) { - if( shiftedIt.Get() > m_ValueZero ) + if( outputIt.Get() > 0 ) { - outputIt.Set ( outside_value ); + outputIt.Set ( this->m_BackgroundValue ); } - else + if( outputIt.Get() < 0 ) { - outputIt.Set ( inside_value ); + outputIt.Set ( - this->m_BackgroundValue ); } } - ++shiftedIt; ++outputIt; ++statusIt; } @@ -1085,15 +1178,15 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunctio } -template< class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +template< class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > void -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::ConstructActiveLayer() { - for ( IdCellType functionIndex = 0; functionIndex < this->m_FunctionCount; - functionIndex++ ) + // We construct active layers for all level-set functions + for ( IdCellType fId = 0; fId < this->m_FunctionCount; fId++ ) { - SparseDataStruct *sparsePtr = this->m_SparseData[functionIndex]; + SparseDataStruct *sparsePtr = this->m_SparseData[fId]; // We find the active layer by searching for 0's in the zero crossing // image (output image). The first inside and outside layers are also @@ -1106,46 +1199,43 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunctio // location. If this is the case, then we need to do active bounds // checking in the solver. - unsigned int i; - NeighborhoodIterator< OutputImageType > - outputIt ( sparsePtr->m_NeighborList.GetRadius(), - this->m_LevelSet[functionIndex], - this->m_LevelSet[functionIndex]->GetRequestedRegion() ); + NeighborhoodIterator< InputImageType > + outputIt ( m_NeighborList.GetRadius(), + this->m_LevelSet[fId], + this->m_LevelSet[fId]->GetRequestedRegion() ); NeighborhoodIterator< StatusImageType > - statusIt ( sparsePtr->m_NeighborList.GetRadius(), + statusIt ( m_NeighborList.GetRadius(), sparsePtr->m_StatusImage, - this->m_LevelSet[functionIndex]->GetRequestedRegion() ); - - NeighborhoodIterator< OutputImageType > - shiftedIt ( sparsePtr->m_NeighborList.GetRadius(), - sparsePtr->m_ShiftedImage, - this->m_LevelSet[functionIndex]->GetRequestedRegion() ); + this->m_LevelSet[fId]->GetRequestedRegion() ); - OutputIndexType center_index, offset_index; + InputIndexType center_index, offset_index; LayerNodeType *node; bool bounds_status; - ValueType value; StatusType layer_number; - OutputIndexType lowerBounds; - OutputSizeType upperBounds; - lowerBounds = this->m_LevelSet[functionIndex]->GetRequestedRegion().GetIndex(); - upperBounds = this->m_LevelSet[functionIndex]->GetRequestedRegion().GetSize(); + // Determine image bounds for checking if sparse layers touch boundaries + InputIndexType lowerBounds; + InputSizeType upperBounds; + lowerBounds = this->m_LevelSet[fId]->GetRequestedRegion().GetIndex(); + upperBounds = this->m_LevelSet[fId]->GetRequestedRegion().GetSize(); + // Iterate over the output image outputIt.GoToBegin(); - while( !outputIt.IsAtEnd() ) { + // Check if the center pixel has a value 0. The zeroCrossingFilter has + // already placed 0s on the active layer pixels and 1 everywhere else. if ( outputIt.GetCenterPixel() == m_ValueZero ) { // Grab the neighborhood in the status image. center_index = outputIt.GetIndex(); + statusIt.SetLocation ( center_index ); // Check to see if any of the sparse field touches a boundary. If so, // then activate bounds checking. - for ( i = 0; i < ImageDimension; i++ ) + for ( unsigned int i = 0; i < ImageDimension; i++ ) { if ( ( center_index[i] + static_cast< long > ( this->m_NumberOfLayers ) >= static_cast< long>( upperBounds[i] - 1 ) ) @@ -1165,37 +1255,32 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunctio sparsePtr->m_Layers[0]->PushFront ( node ); statusIt.SetCenterPixel ( 0 ); - // Grab the neighborhood in the image of shifted input values. - shiftedIt.SetLocation ( center_index ); - // Search the neighborhood pixels for first inside & outside layer // members. Construct these lists and set status list values. - for ( i = 0; i < sparsePtr->m_NeighborList.GetSize(); ++i ) + for ( unsigned int i = 0; i < m_NeighborList.GetSize(); ++i ) { - offset_index = center_index + sparsePtr->m_NeighborList.GetNeighborhoodOffset ( i ); - - if ( outputIt.GetPixel( sparsePtr->m_NeighborList.GetArrayIndex( i ) ) != m_ValueZero ) + // If the neighborhood pixel is not on the active layer + // determine its sign to assign to outside or inside layers + unsigned int neighborIndex = m_NeighborList.GetArrayIndex( i ); + if ( outputIt.GetPixel( neighborIndex ) != m_ValueZero ) { - value = shiftedIt.GetPixel ( sparsePtr->m_NeighborList.GetArrayIndex ( i ) ); + // Determine if the neighbor belongs to layer 1 (inside) or 2 (outside) + layer_number = ( outputIt.GetPixel ( neighborIndex ) > 0 ) ? 2 : 1; - if ( value < m_ValueZero ) // Assign to first inside layer. - { - layer_number = 1; - } - else // Assign to first outside layer + // This check is to prevent the same pixel from being included more than once + // in the list + if ( statusIt.GetPixel( neighborIndex ) == m_StatusNull ) { - layer_number = 2; + statusIt.SetPixel ( neighborIndex, layer_number, bounds_status ); + + if ( bounds_status ) // In bounds. + { + offset_index = center_index + m_NeighborList.GetNeighborhoodOffset ( i ); + node = sparsePtr->m_LayerNodeStore->Borrow(); + node->m_Value = offset_index; + sparsePtr->m_Layers[layer_number]->PushFront ( node ); + } // else do nothing. } - - statusIt.SetPixel ( sparsePtr->m_NeighborList.GetArrayIndex ( i ), - layer_number, bounds_status ); - - if ( bounds_status ) // In bounds. - { - node = sparsePtr->m_LayerNodeStore->Borrow(); - node->m_Value = offset_index; - sparsePtr->m_Layers[layer_number]->PushFront ( node ); - } // else do nothing. } } } @@ -1204,20 +1289,23 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunctio } } -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +template< class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > void -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::ConstructLayer ( SparseDataStruct *sparsePtr, StatusType from, StatusType to ) { LayerNodeType *node; bool boundary_status; - typename LayerType::ConstIterator fromIt; - NeighborhoodIterator<StatusImageType> - statusIt ( sparsePtr->m_NeighborList.GetRadius(), sparsePtr->m_StatusImage, + + NeighborhoodIterator<StatusImageType> statusIt ( + m_NeighborList.GetRadius(), sparsePtr->m_StatusImage, this->m_LevelSet[sparsePtr->m_Index]->GetRequestedRegion() ); - // For all indices in the "from" layer... + + typename LayerType::ConstIterator fromIt; fromIt = sparsePtr->m_Layers[from]->Begin(); + + // For all indices in the "from" layer... while( fromIt != sparsePtr->m_Layers[from]->End() ) { // Search the neighborhood of this index in the status image for @@ -1225,15 +1313,17 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunctio // assign them values in the status image. Status pixels outside the // boundary will be ignored. statusIt.SetLocation ( fromIt->m_Value ); - for ( unsigned int i = 0; i < sparsePtr->m_NeighborList.GetSize(); ++i ) + for ( unsigned int i = 0; i < m_NeighborList.GetSize(); ++i ) { - if ( statusIt.GetPixel ( sparsePtr->m_NeighborList.GetArrayIndex ( i ) ) == m_StatusNull ) + // If the pixel is not a boundary pixel or belongs to another layer + unsigned int neighborIndex = m_NeighborList.GetArrayIndex ( i ); + if ( statusIt.GetPixel ( neighborIndex ) == m_StatusNull ) { - statusIt.SetPixel ( sparsePtr->m_NeighborList.GetArrayIndex ( i ), to, boundary_status ); + statusIt.SetPixel ( neighborIndex, to, boundary_status ); if ( boundary_status == true ) // in bounds { node = sparsePtr->m_LayerNodeStore->Borrow(); - node->m_Value = statusIt.GetIndex() + sparsePtr->m_NeighborList.GetNeighborhoodOffset ( i ); + node->m_Value = statusIt.GetIndex() + m_NeighborList.GetNeighborhoodOffset ( i ); sparsePtr->m_Layers[to]->PushFront ( node ); } } @@ -1242,28 +1332,9 @@ MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunctio } } -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +template< class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > void -MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > -::AllocateUpdateBuffer() -{ - for ( IdCellType i = 0; i < this->m_FunctionCount; i++ ) - { - SparseDataStruct *sparsePtr = this->m_SparseData[i]; - - // Preallocate the update buffer. NOTE: There is currently no way to - // downsize a std::vector. This means that the update buffer will grow - // dynamically but not shrink. In newer implementations there may be a - // squeeze method which can do this. Alternately, we can implement our - // own strategy for downsizing. - sparsePtr->m_UpdateBuffer.clear(); - sparsePtr->m_UpdateBuffer.reserve ( sparsePtr->m_Layers[0]->Size() ); - } -} - -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > -void -MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, TOutputImage, TFunction, TIdCell > +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::PostProcessOutput() { // Get the output pointer and clear its contents @@ -1275,26 +1346,29 @@ MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, TOutputImage, TFunction // Initialize layer values using the active layer as seeds. this->PropagateAllLayerValues(); - for ( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + // Initialize pixels outside the sparse field layers to positive + // and negative values, respectively. This is not necessary for the + // calculations, but is useful for presenting a more intuitive output to the + // filter. + this->InitializeBackgroundPixels(); + + for ( IdCellType fId = 0; fId < this->m_FunctionCount; fId++ ) { - InputImagePointer input = this->m_LevelSet[i]; + InputImagePointer input = this->m_LevelSet[fId]; InputPointType origin = input->GetOrigin(); InputSpacingType spacing = input->GetSpacing(); // Local iterator - ImageRegionIterator< InputImageType > inIt ( this->m_LevelSet[i], - this->m_LevelSet[i]->GetLargestPossibleRegion() ); + ImageRegionIterator< InputImageType > inIt ( this->m_LevelSet[fId], + this->m_LevelSet[fId]->GetRequestedRegion() ); // In the context of the global coordinates OutputIndexType start; - for ( unsigned int j = 0; j < ImageDimension; j++ ) - { - start[j] = static_cast<OutputIndexValueType>( origin[j]/spacing[j] ); - } + output->TransformPhysicalPointToIndex( origin, start ); // Defining sub-region in the global coordinates OutputRegionType region; - region.SetSize( input->GetLargestPossibleRegion().GetSize() ); + region.SetSize( input->GetRequestedRegion().GetSize() ); region.SetIndex( start ); if ( !input || !output ) @@ -1304,7 +1378,7 @@ MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, TOutputImage, TFunction ImageRegionIterator< OutputImageType > outIt ( output, region ); - OutputPixelType p = static_cast<OutputPixelType> ( this->m_Lookup[i] ); + OutputPixelType p = static_cast< OutputPixelType > ( this->m_Lookup[fId] ); inIt.GoToBegin(); outIt.GoToBegin(); @@ -1321,9 +1395,9 @@ MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, TOutputImage, TFunction } } -template<class TInputImage, class TOutputImage, class TFunction, typename TIdCell > +template< class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, typename TIdCell > void -MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, TOutputImage, TFunction, TIdCell > +MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, TFunction, TIdCell > ::PrintSelf ( std::ostream& os, Indent indent ) const { Superclass::PrintSelf(os,indent); diff --git a/Utilities/ITK/Code/Review/itkOptImageToImageMetric.h b/Utilities/ITK/Code/Review/itkOptImageToImageMetric.h index 0180737fc184a591e0565c71739021f19046cba4..8a8819e0aee08ae4bd724bba5ca7cafebbf60cd0 100755 --- a/Utilities/ITK/Code/Review/itkOptImageToImageMetric.h +++ b/Utilities/ITK/Code/Review/itkOptImageToImageMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptImageToImageMetric.h,v $ Language: C++ - Date: $Date: 2008-07-30 20:56:17 $ - Version: $Revision: 1.22 $ + Date: $Date: 2009-08-20 09:08:41 $ + Version: $Revision: 1.31 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -21,7 +21,6 @@ #include "itkImageBase.h" #include "itkTransform.h" #include "itkInterpolateImageFunction.h" -#include "itkSingleValuedCostFunction.h" #include "itkExceptionObject.h" #include "itkGradientRecursiveGaussianImageFilter.h" #include "itkSpatialObject.h" @@ -140,15 +139,15 @@ public: this mask will be considered for the computation of the metric */ typedef SpatialObject< itkGetStaticConstMacro(FixedImageDimension) > FixedImageMaskType; - typedef typename FixedImageMaskType::Pointer FixedImageMaskPointer; - typedef typename FixedImageMaskType::ConstPointer FixedImageMaskConstPointer; + typedef typename FixedImageMaskType::Pointer FixedImageMaskPointer; + typedef typename FixedImageMaskType::ConstPointer FixedImageMaskConstPointer; /** Type for the mask of the moving image. Only pixels that are "inside" this mask will be considered for the computation of the metric */ typedef SpatialObject< itkGetStaticConstMacro(MovingImageDimension) > MovingImageMaskType; - typedef typename MovingImageMaskType::Pointer MovingImageMaskPointer; - typedef typename MovingImageMaskType::ConstPointer MovingImageMaskConstPointer; + typedef typename MovingImageMaskType::Pointer MovingImageMaskPointer; + typedef typename MovingImageMaskType::ConstPointer MovingImageMaskConstPointer; /** Type of the measure. */ @@ -185,32 +184,36 @@ public: itkGetConstObjectMacro( Interpolator, InterpolatorType ); /** Get the number of pixels considered in the computation. */ - itkGetConstReferenceMacro( NumberOfMovingImageSamples, unsigned long ); - unsigned long GetNumberOfPixelsCounter( void ) + unsigned long GetNumberOfMovingImageSamples( void ) { - return GetNumberOfMovingImageSamples(); + return this->GetNumberOfPixelsCounted(); } + itkGetConstReferenceMacro( NumberOfPixelsCounted, unsigned long ); /** Set the region over which the metric will be computed */ - itkSetMacro( FixedImageRegion, FixedImageRegionType ); + void SetFixedImageRegion( const FixedImageRegionType reg ); /** Get the region over which the metric will be computed */ itkGetConstReferenceMacro( FixedImageRegion, FixedImageRegionType ); /** Set/Get the moving image mask. */ + itkSetObjectMacro( MovingImageMask, MovingImageMaskType ); itkSetConstObjectMacro( MovingImageMask, MovingImageMaskType ); itkGetConstObjectMacro( MovingImageMask, MovingImageMaskType ); /** Set/Get the fixed image mask. */ + itkSetObjectMacro( FixedImageMask, FixedImageMaskType ); itkSetConstObjectMacro( FixedImageMask, FixedImageMaskType ); itkGetConstObjectMacro( FixedImageMask, FixedImageMaskType ); /** Set the fixed image indexes to be used as the samples when * computing the match metric */ void SetFixedImageIndexes( const FixedImageIndexContainer & indexes ); + void SetUseFixedImageIndexes( bool useIndex ); + itkGetConstReferenceMacro( UseFixedImageIndexes, bool ); /** Set/Get number of threads to use for computations. */ - itkSetMacro( NumberOfThreads, unsigned int ); + void SetNumberOfThreads( unsigned int numberOfThreads ); itkGetConstReferenceMacro( NumberOfThreads, unsigned int ); /** Set/Get gradient computation. */ @@ -240,25 +243,13 @@ public: /** Initialize the components related to supporting multiple threads */ virtual void MultiThreadingInitialize( void ) throw ( ExceptionObject ); - /** Number of spatial samples to used to compute metric */ - virtual void SetNumberOfFixedImageSamples( unsigned long numSamples ) - { - // This is not a macro because we need to also set m_UseAllPixels - itkDebugMacro("Setting NumberOfFixedImageSamples to " << numSamples ); - if (this->m_NumberOfFixedImageSamples != numSamples) - { - if( this->m_NumberOfFixedImageSamples == 0 ) - { - // make sure that there is at least one sample - this->m_NumberOfFixedImageSamples = 1; - } - this->m_UseAllPixels = false; - this->m_NumberOfFixedImageSamples = numSamples; - this->Modified(); - } - } - + /** Number of spatial samples to used to compute metric + * This sets the number of samples. */ + virtual void SetNumberOfFixedImageSamples( unsigned long numSamples ); itkGetConstReferenceMacro( NumberOfFixedImageSamples, unsigned long ); + + /** Number of spatial samples to used to compute metric + * This sets the number of samples. */ void SetNumberOfSpatialSamples( unsigned long num ) { this->SetNumberOfFixedImageSamples( num ); @@ -272,17 +263,30 @@ public: * metric computation */ void SetFixedImageSamplesIntensityThreshold( const FixedImagePixelType & thresh ); itkGetConstReferenceMacro( FixedImageSamplesIntensityThreshold, FixedImagePixelType ); - itkSetMacro( UseFixedImageSamplesIntensityThreshold, bool ); + + void SetUseFixedImageSamplesIntensityThreshold( bool useThresh ); itkGetConstReferenceMacro( UseFixedImageSamplesIntensityThreshold, bool ); /** Select whether the metric will be computed using all the pixels on the - * fixed image region, or only using a set of randomly selected pixels. */ - itkSetMacro( UseAllPixels, bool ); + * fixed image region, or only using a set of randomly selected pixels. + * This value override IntensityThreshold, Masks, and SequentialSampling. */ + void SetUseAllPixels( bool useAllPixels ); + void UseAllPixelsOn( void ) + { + this->SetUseAllPixels( true ); + } + void UseAllPixelsOff( void ) + { + this->SetUseAllPixels( false ); + } itkGetConstReferenceMacro( UseAllPixels, bool ); - itkBooleanMacro( UseAllPixels ); - /** Get the number of pixels considered in the computation. */ - itkGetConstReferenceMacro( NumberOfPixelsCounted, unsigned long ); + /** If set to true, then every pixel in the fixed image will be scanned to + * determine if it should be used in registration metric computation. A + * pixel will be chosen if it meets any mask or threshold limits set. If + * set to false, then UseAllPixels will be set to false. */ + void SetUseSequentialSampling( bool sequentialSampling ); + itkGetConstReferenceMacro( UseSequentialSampling, bool ); /** Reinitialize the seed of the random number generator that selects the * sample of pixels used for estimating the image histograms and the joint @@ -322,8 +326,6 @@ protected: void PrintSelf(std::ostream& os, Indent indent) const; - mutable unsigned long m_NumberOfPixelsCounted; - /** \class FixedImageSamplePoint * A fixed image spatial sample consists of the fixed domain point * and the fixed image value at that point. */ @@ -338,7 +340,7 @@ protected: valueIndex = 0; } ~FixedImageSamplePoint() {}; - + public: FixedImagePointType point; double value; @@ -348,8 +350,9 @@ protected: bool m_UseFixedImageIndexes; FixedImageIndexContainer m_FixedImageIndexes; - FixedImagePixelType m_FixedImageSamplesIntensityThreshold; + bool m_UseFixedImageSamplesIntensityThreshold; + FixedImagePixelType m_FixedImageSamplesIntensityThreshold; /** FixedImageSamplePoint typedef support. */ typedef std::vector<FixedImageSamplePoint> FixedImageSampleContainer; @@ -358,11 +361,11 @@ protected: virtual void SampleFixedImageDomain( FixedImageSampleContainer & samples) const; virtual void SampleFixedImageIndexes( FixedImageSampleContainer & - samples); + samples) const; /** Gather all the pixels from the fixed image domain. */ virtual void SampleFullFixedImageDomain( FixedImageSampleContainer & - samples); + samples) const; /** Container to store a set of points and fixed image values. */ FixedImageSampleContainer m_FixedImageSamples; @@ -370,8 +373,11 @@ protected: unsigned long m_NumberOfParameters; mutable ParametersType m_Parameters; - mutable unsigned long m_NumberOfFixedImageSamples; - mutable unsigned long m_NumberOfMovingImageSamples; + unsigned long m_NumberOfFixedImageSamples; + //m_NumberOfPixelsCounted must be mutable because the const + //thread consolidation functions merge each threads valus + //onto this accumulator variable. + mutable unsigned long m_NumberOfPixelsCounted; FixedImageConstPointer m_FixedImage; MovingImageConstPointer m_MovingImage; @@ -387,12 +393,13 @@ protected: bool m_ComputeGradient; GradientImagePointer m_GradientImage; - FixedImageMaskConstPointer m_FixedImageMask; - MovingImageMaskConstPointer m_MovingImageMask; + FixedImageMaskConstPointer m_FixedImageMask; + MovingImageMaskConstPointer m_MovingImageMask; unsigned int m_NumberOfThreads; bool m_UseAllPixels; + bool m_UseSequentialSampling; bool m_ReseedIterator; @@ -483,18 +490,17 @@ protected: unsigned int threadID ) const; /** Boolean to indicate if the interpolator BSpline. */ - bool m_InterpolatorIsBSpline; + bool m_InterpolatorIsBSpline; /** Pointer to BSplineInterpolator. */ - typename BSplineInterpolatorType::Pointer m_BSplineInterpolator; + typename BSplineInterpolatorType::Pointer m_BSplineInterpolator; /** Pointer to central difference calculator. */ - typename DerivativeFunctionType::Pointer m_DerivativeCalculator; + typename DerivativeFunctionType::Pointer m_DerivativeCalculator; /** Compute image derivatives at a point. */ - virtual void ComputeImageDerivatives( - const MovingImagePointType & mappedPoint, - ImageDerivativesType & gradient, - unsigned int threadID ) const; + virtual void ComputeImageDerivatives( const MovingImagePointType & mappedPoint, + ImageDerivativesType & gradient, + unsigned int threadID ) const; /** @@ -510,85 +516,62 @@ protected: MultiThreaderType::Pointer m_Threader; MultiThreaderParameterType m_ThreaderParameter; - mutable unsigned int m_ThreaderChunkSize; - mutable unsigned int m_ThreaderSizeOfLastChunk; mutable unsigned int * m_ThreaderNumberOfMovingImageSamples; bool m_WithinThreadPreProcess; bool m_WithinThreadPostProcess; - void GetValueMultiThreadedPreProcessInitiate( - void ) const; + void GetValueMultiThreadedPreProcessInitiate( void ) const; void GetValueMultiThreadedInitiate( void ) const; - void GetValueMultiThreadedPostProcessInitiate( - void ) const; + void GetValueMultiThreadedPostProcessInitiate( void ) const; static ITK_THREAD_RETURN_TYPE GetValueMultiThreadedPreProcess( void * arg ); static ITK_THREAD_RETURN_TYPE GetValueMultiThreaded( void * arg ); static ITK_THREAD_RETURN_TYPE GetValueMultiThreadedPostProcess( void * arg ); - void GetValueThread( unsigned int threadID ) const; + virtual inline void GetValueThread( unsigned int threadID ) const; virtual inline void GetValueThreadPreProcess( - unsigned int threadID, - bool withinSampleThread ) const; + unsigned int itkNotUsed(threadID), + bool itkNotUsed(withinSampleThread) ) const + { }; virtual inline bool GetValueThreadProcessSample( - unsigned int itkNotUsed(threadID), - unsigned long itkNotUsed(fixedImageSample), - const MovingImagePointType & itkNotUsed(mappedPoint), - double itkNotUsed(movingImageValue)) const + unsigned int itkNotUsed(threadID), + unsigned long itkNotUsed(fixedImageSample), + const MovingImagePointType & itkNotUsed(mappedPoint), + double itkNotUsed(movingImageValue)) const { return false; }; virtual inline void GetValueThreadPostProcess( - unsigned int itkNotUsed(threadID), - bool itkNotUsed(withinSampleThread) ) const {}; + unsigned int itkNotUsed(threadID), + bool itkNotUsed(withinSampleThread) ) const + { }; - - /* - void InitiateGetDerivativeMultiThreaded( void) const; - static ITK_THREAD_RETURN_TYPE GetDerivativeMultiThreaded( void * arg ); - void GetDerivativeThread( unsigned int threadID ) const; - virtual inline void GetDerivativeThreadProcessSample( unsigned int threadID, - unsigned long fixedImageSample, - MovingImagePointType mappedPoint, - double movingImageValue) const = 0; - */ - - void GetValueAndDerivativeMultiThreadedPreProcessInitiate( - void) const; - void GetValueAndDerivativeMultiThreadedInitiate( void) const; - void GetValueAndDerivativeMultiThreadedPostProcessInitiate( - void) const; - static ITK_THREAD_RETURN_TYPE - GetValueAndDerivativeMultiThreadedPreProcess(void * arg); - - static ITK_THREAD_RETURN_TYPE - GetValueAndDerivativeMultiThreaded(void * arg); - - static ITK_THREAD_RETURN_TYPE - GetValueAndDerivativeMultiThreadedPostProcess(void * arg); - - void GetValueAndDerivativeThread(unsigned int threadID) const; - virtual inline void GetValueAndDerivativeThreadPreProcess( unsigned int itkNotUsed(threadID), - bool itkNotUsed(withinSampleThread)) const {}; + void GetValueAndDerivativeMultiThreadedPreProcessInitiate( void ) const; + void GetValueAndDerivativeMultiThreadedInitiate( void ) const; + void GetValueAndDerivativeMultiThreadedPostProcessInitiate( void ) const; + static ITK_THREAD_RETURN_TYPE GetValueAndDerivativeMultiThreadedPreProcess( void * arg ); + static ITK_THREAD_RETURN_TYPE GetValueAndDerivativeMultiThreaded(void * arg); + static ITK_THREAD_RETURN_TYPE GetValueAndDerivativeMultiThreadedPostProcess(void * arg); + + virtual inline void GetValueAndDerivativeThread(unsigned int threadID) const; + virtual inline void GetValueAndDerivativeThreadPreProcess( + unsigned int itkNotUsed(threadID), + bool itkNotUsed(withinSampleThread)) const + { }; virtual inline bool GetValueAndDerivativeThreadProcessSample( - unsigned int itkNotUsed(threadID), - unsigned long itkNotUsed(fixedImageSample), - const MovingImagePointType & itkNotUsed(mappedPoint), - double itkNotUsed(movingImageValue), - const ImageDerivativesType & itkNotUsed(movingImageGradientValue) ) const - { - return false; - } - + unsigned int itkNotUsed(threadID), + unsigned long itkNotUsed(fixedImageSample), + const MovingImagePointType & itkNotUsed(mappedPoint), + double itkNotUsed(movingImageValue), + const ImageDerivativesType & itkNotUsed(movingImageGradientValue) ) const + { return false; } virtual inline void GetValueAndDerivativeThreadPostProcess( - unsigned int itkNotUsed(threadID), - bool itkNotUsed(withinSampleThread) ) const {}; + unsigned int itkNotUsed(threadID), + bool itkNotUsed(withinSampleThread) ) const + { }; /** Synchronizes the threader transforms with the transform * member variable. */ void SynchronizeTransforms() const; - /** Update sample sizes for the threads. */ - void NumberOfFixedImageSamplesUpdated(); - private: ImageToImageMetric(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Code/Review/itkOptImageToImageMetric.txx b/Utilities/ITK/Code/Review/itkOptImageToImageMetric.txx index a87a1d9073abf296e14a0ba80b68594b9389f88c..b997ac8eb5d512c211f2acff3acf82fc8c1428ad 100755 --- a/Utilities/ITK/Code/Review/itkOptImageToImageMetric.txx +++ b/Utilities/ITK/Code/Review/itkOptImageToImageMetric.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptImageToImageMetric.txx,v $ Language: C++ - Date: $Date: 2008-09-30 18:07:03 $ - Version: $Revision: 1.29 $ + Date: $Date: 2009-08-24 17:42:02 $ + Version: $Revision: 1.37 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -34,6 +34,7 @@ ImageToImageMetric<TFixedImage,TMovingImage> { m_NumberOfFixedImageSamples = 50000; m_UseAllPixels = false; + m_UseSequentialSampling = false; m_UseFixedImageIndexes = false; m_UseFixedImageSamplesIntensityThreshold = false; m_FixedImageSamplesIntensityThreshold = 0; @@ -46,8 +47,6 @@ ImageToImageMetric<TFixedImage,TMovingImage> m_Threader = MultiThreaderType::New(); m_ThreaderParameter.metric = this; - m_ThreaderChunkSize = 0; - m_ThreaderSizeOfLastChunk = 0; m_ThreaderNumberOfMovingImageSamples = NULL; m_WithinThreadPreProcess = false; m_WithinThreadPostProcess = false; @@ -57,6 +56,7 @@ ImageToImageMetric<TFixedImage,TMovingImage> m_MovingImage = 0; // has to be provided by the user. m_MovingImageMask = 0; + m_NumberOfPixelsCounted = 0; m_Transform = NULL; // has to be provided by the user. m_ThreaderTransform = NULL; // constructed at initialization. @@ -107,6 +107,18 @@ ImageToImageMetric<TFixedImage,TMovingImage> m_ThreaderTransform = NULL; } +/** + * Set the number of threads. This will be clamped by the + * multithreader, so we must check to see if it is accepted. + */ +template <class TFixedImage, class TMovingImage> +void +ImageToImageMetric<TFixedImage,TMovingImage> +::SetNumberOfThreads( unsigned int numberOfThreads ) +{ + m_Threader->SetNumberOfThreads( numberOfThreads); + m_NumberOfThreads = m_Threader->GetNumberOfThreads(); +} /** * Set the parameters that define a unique transform @@ -125,16 +137,29 @@ ImageToImageMetric<TFixedImage,TMovingImage> m_Parameters = parameters; } +template <class TFixedImage, class TMovingImage> +void +ImageToImageMetric<TFixedImage,TMovingImage> +::SetNumberOfFixedImageSamples( unsigned long numSamples ) +{ + if( numSamples != m_NumberOfFixedImageSamples ) + { + m_NumberOfFixedImageSamples = numSamples; + if( m_NumberOfFixedImageSamples != this->m_FixedImageRegion.GetNumberOfPixels() ) + { + this->SetUseAllPixels( false ); + } + this->Modified(); + } +} template <class TFixedImage, class TMovingImage> void ImageToImageMetric<TFixedImage,TMovingImage> ::SetFixedImageIndexes( const FixedImageIndexContainer & indexes ) { - m_UseFixedImageIndexes = true; - m_UseAllPixels = false; + this->SetUseFixedImageIndexes( true ); m_NumberOfFixedImageSamples = indexes.size(); - this->NumberOfFixedImageSamplesUpdated(); m_FixedImageIndexes.resize( m_NumberOfFixedImageSamples ); for(unsigned int i=0; i<m_NumberOfFixedImageSamples; i++) { @@ -142,13 +167,112 @@ ImageToImageMetric<TFixedImage,TMovingImage> } } +template <class TFixedImage, class TMovingImage> +void +ImageToImageMetric<TFixedImage,TMovingImage> +::SetUseFixedImageIndexes( bool useIndexes ) +{ + if( useIndexes != m_UseFixedImageIndexes ) + { + m_UseFixedImageIndexes = useIndexes; + if( m_UseFixedImageIndexes ) + { + this->SetUseAllPixels( false ); + } + else + { + this->Modified(); + } + } +} + template <class TFixedImage, class TMovingImage> void ImageToImageMetric<TFixedImage,TMovingImage> ::SetFixedImageSamplesIntensityThreshold( const FixedImagePixelType & thresh ) { - m_UseFixedImageSamplesIntensityThreshold = true; - m_FixedImageSamplesIntensityThreshold = thresh; + if( thresh != m_FixedImageSamplesIntensityThreshold ) + { + m_FixedImageSamplesIntensityThreshold = thresh; + this->SetUseFixedImageSamplesIntensityThreshold( true ); + this->Modified(); + } +} + +template <class TFixedImage, class TMovingImage> +void +ImageToImageMetric<TFixedImage,TMovingImage> +::SetUseFixedImageSamplesIntensityThreshold( bool useThresh ) +{ + if( useThresh != m_UseFixedImageSamplesIntensityThreshold ) + { + m_UseFixedImageSamplesIntensityThreshold = useThresh; + if( m_UseFixedImageSamplesIntensityThreshold ) + { + this->SetUseAllPixels( false ); + } + else + { + this->Modified(); + } + } +} + +template <class TFixedImage, class TMovingImage> +void +ImageToImageMetric<TFixedImage,TMovingImage> +::SetFixedImageRegion( const FixedImageRegionType reg ) +{ + if( reg != m_FixedImageRegion ) + { + m_FixedImageRegion = reg; + if( this->GetUseAllPixels() ) + { + this->SetNumberOfFixedImageSamples( this->m_FixedImageRegion.GetNumberOfPixels() ); + } + } +} + +template <class TFixedImage, class TMovingImage> +void +ImageToImageMetric<TFixedImage,TMovingImage> +::SetUseAllPixels( bool useAllPixels ) +{ + if( useAllPixels != m_UseAllPixels ) + { + m_UseAllPixels = useAllPixels; + if( m_UseAllPixels ) + { + this->SetUseFixedImageSamplesIntensityThreshold( false ); + this->SetNumberOfFixedImageSamples( this->m_FixedImageRegion.GetNumberOfPixels() ); + this->SetUseSequentialSampling( true ); + } + else + { + this->SetUseSequentialSampling( false ); + this->Modified(); + } + } +} + + +template <class TFixedImage, class TMovingImage> +void +ImageToImageMetric<TFixedImage,TMovingImage> +::SetUseSequentialSampling( bool useSequential ) +{ + if( useSequential != m_UseSequentialSampling ) + { + m_UseSequentialSampling = useSequential; + if( !m_UseSequentialSampling ) + { + this->SetUseAllPixels( false ); + } + else + { + this->Modified(); + } + } } /** @@ -215,6 +339,7 @@ ImageToImageMetric<TFixedImage,TMovingImage> // If there are any observers on the metric, call them to give the // user code a chance to set parameters on the metric this->InvokeEvent( InitializeEvent() ); + } @@ -226,15 +351,8 @@ void ImageToImageMetric<TFixedImage,TMovingImage> ::MultiThreadingInitialize(void) throw ( ExceptionObject ) { - m_Threader->SetNumberOfThreads( m_NumberOfThreads ); - if( m_UseAllPixels ) - { - m_NumberOfFixedImageSamples = GetFixedImageRegion().GetNumberOfPixels(); - // NumberOfFixedImageSamplesUpdated called below. - } - - this->NumberOfFixedImageSamplesUpdated(); + m_Threader->SetNumberOfThreads( m_NumberOfThreads ); if(m_ThreaderNumberOfMovingImageSamples != NULL) { @@ -263,8 +381,8 @@ ImageToImageMetric<TFixedImage,TMovingImage> this->m_ThreaderTransform[ithread] = transformCopy; } - m_FixedImageSamples.resize(m_NumberOfFixedImageSamples); - if( m_UseAllPixels ) + m_FixedImageSamples.resize( m_NumberOfFixedImageSamples ); + if( m_UseSequentialSampling ) { // // Take all the pixels within the fixed image region) @@ -276,6 +394,10 @@ ImageToImageMetric<TFixedImage,TMovingImage> { if( m_UseFixedImageIndexes ) { + // + // Use the list of indexes passed to the SetFixedImageIndexes + // member function . + // SampleFixedImageIndexes( m_FixedImageSamples ); } else @@ -409,19 +531,22 @@ ImageToImageMetric<TFixedImage,TMovingImage> /** - * Uniformly sample the fixed image domain using a random walk + * Use the indexes that have been passed to the metric */ template < class TFixedImage, class TMovingImage > void ImageToImageMetric<TFixedImage,TMovingImage> -::SampleFixedImageIndexes( FixedImageSampleContainer & samples ) +::SampleFixedImageIndexes( FixedImageSampleContainer & samples ) const { typename FixedImageSampleContainer::iterator iter; unsigned long len = m_FixedImageIndexes.size(); - m_NumberOfFixedImageSamples = len; - this->NumberOfFixedImageSamplesUpdated(); - samples.resize(len); + if( len != m_NumberOfFixedImageSamples + || samples.size() != m_NumberOfFixedImageSamples ) + { + throw ExceptionObject(__FILE__, __LINE__, + "Index list size does not match desired number of samples" ); + } iter=samples.begin(); for(unsigned long i=0; i<len; i++) @@ -439,11 +564,20 @@ ImageToImageMetric<TFixedImage,TMovingImage> } } +/** + * Sample the fixed image using a random walk + */ template < class TFixedImage, class TMovingImage > void ImageToImageMetric<TFixedImage,TMovingImage> ::SampleFixedImageDomain( FixedImageSampleContainer & samples ) const { + if( samples.size() != m_NumberOfFixedImageSamples ) + { + throw ExceptionObject(__FILE__, __LINE__, + "Sample size does not match desired number of samples" ); + } + // Set up a random interator within the user specified fixed image region. typedef ImageRandomConstIteratorWithIndex<FixedImageType> RandomIterator; RandomIterator randIter( m_FixedImage, GetFixedImageRegion() ); @@ -451,46 +585,61 @@ ImageToImageMetric<TFixedImage,TMovingImage> typename FixedImageSampleContainer::iterator iter; typename FixedImageSampleContainer::const_iterator end=samples.end(); - if( m_FixedImageMask ) + if( m_FixedImageMask.IsNotNull() + || m_UseFixedImageSamplesIntensityThreshold ) { InputPointType inputPoint; iter=samples.begin(); - int count = 0; - int samples_found = 0; - int maxcount = m_NumberOfFixedImageSamples * 10; - randIter.SetNumberOfSamples( m_NumberOfFixedImageSamples * 10 ); + unsigned long int samplesFound = 0; + randIter.SetNumberOfSamples( m_NumberOfFixedImageSamples * 1000 ); randIter.GoToBegin(); while( iter != end ) { - - if ( count > maxcount || randIter.IsAtEnd() ) + if( randIter.IsAtEnd() ) { - m_NumberOfFixedImageSamples = samples_found; - samples.resize(samples_found); + // Must be a small mask since after many random samples we don't + // have enough to fill the desired number. So, we will replicate + // the samples we've found so far to fill-in the desired number + // of samples + unsigned long int count = 0; + while( iter != end ) + { + (*iter).point = samples[count].point; + (*iter).value = samples[count].value; + (*iter).valueIndex = 0; + ++count; + if(count >= samplesFound) + { + count = 0; + } + ++iter; + } break; } - count++; // Get sampled index FixedImageIndexType index = randIter.GetIndex(); // Check if the Index is inside the mask, translate index to point m_FixedImage->TransformIndexToPhysicalPoint( index, inputPoint ); - double val; - if( m_FixedImageMask->ValueAt( inputPoint, val ) ) + if( m_FixedImageMask.IsNotNull() ) { - if( val == 0 ) + double val; + if( m_FixedImageMask->ValueAt( inputPoint, val ) ) + { + if( val == 0 ) + { + ++randIter; // jump to another random position + continue; + } + } + else { ++randIter; // jump to another random position continue; } } - else - { - ++randIter; // jump to another random position - continue; - } if( m_UseFixedImageSamplesIntensityThreshold && randIter.Get() < m_FixedImageSamplesIntensityThreshold ) @@ -505,8 +654,7 @@ ImageToImageMetric<TFixedImage,TMovingImage> (*iter).value = randIter.Get(); (*iter).valueIndex = 0; - ++samples_found; - // Jump to random position + ++samplesFound; ++randIter; ++iter; } @@ -538,8 +686,15 @@ ImageToImageMetric<TFixedImage,TMovingImage> template < class TFixedImage, class TMovingImage > void ImageToImageMetric<TFixedImage,TMovingImage> -::SampleFullFixedImageDomain( FixedImageSampleContainer& samples ) +::SampleFullFixedImageDomain( FixedImageSampleContainer& samples ) const { + + if( samples.size() != m_NumberOfFixedImageSamples ) + { + throw ExceptionObject(__FILE__, __LINE__, + "Sample size does not match desired number of samples" ); + } + // Set up a region interator within the user specified fixed image region. typedef ImageRegionConstIteratorWithIndex<FixedImageType> RegionIterator; RegionIterator regionIter( m_FixedImage, GetFixedImageRegion() ); @@ -549,58 +704,61 @@ ImageToImageMetric<TFixedImage,TMovingImage> typename FixedImageSampleContainer::iterator iter; typename FixedImageSampleContainer::const_iterator end=samples.end(); - if( m_FixedImageMask ) + if( m_FixedImageMask.IsNotNull() + || m_UseFixedImageSamplesIntensityThreshold ) { InputPointType inputPoint; + // repeat until we get enough samples to fill the array iter=samples.begin(); - unsigned long nSamplesPicked = 0; - - while( iter != end && !regionIter.IsAtEnd() ) + while( iter != end ) { // Get sampled index FixedImageIndexType index = regionIter.GetIndex(); // Check if the Index is inside the mask, translate index to point m_FixedImage->TransformIndexToPhysicalPoint( index, inputPoint ); + + if( m_FixedImageMask.IsNotNull() ) + { + // If not inside the mask, ignore the point + if( !m_FixedImageMask->IsInside( inputPoint ) ) + { + ++regionIter; // jump to next pixel + if( regionIter.IsAtEnd() ) + { + regionIter.GoToBegin(); + } + continue; + } + } - // If not inside the mask, ignore the point - if( !m_FixedImageMask->IsInside( inputPoint ) ) + if( m_UseFixedImageSamplesIntensityThreshold && + regionIter.Get() < m_FixedImageSamplesIntensityThreshold ) { ++regionIter; // jump to next pixel + if( regionIter.IsAtEnd() ) + { + regionIter.GoToBegin(); + } continue; } - + // Translate index to point (*iter).point = inputPoint; // Get sampled fixed image value (*iter).value = regionIter.Get(); (*iter).valueIndex = 0; - + ++regionIter; + if( regionIter.IsAtEnd() ) + { + regionIter.GoToBegin(); + } ++iter; - ++nSamplesPicked; - } - - // If we picked fewer samples than the desired number, - // resize the container - if (nSamplesPicked != m_NumberOfFixedImageSamples) - { - m_NumberOfFixedImageSamples = nSamplesPicked; - this->NumberOfFixedImageSamplesUpdated(); - samples.resize(m_NumberOfFixedImageSamples); } } else // not restricting sample throwing to a mask { - // cannot sample more than the number of pixels in the image region - if ( m_NumberOfFixedImageSamples - > GetFixedImageRegion().GetNumberOfPixels()) - { - m_NumberOfFixedImageSamples = GetFixedImageRegion().GetNumberOfPixels(); - this->NumberOfFixedImageSamplesUpdated(); - samples.resize(m_NumberOfFixedImageSamples); - } - for( iter=samples.begin(); iter != end; ++iter ) { // Get sampled index @@ -614,6 +772,10 @@ ImageToImageMetric<TFixedImage,TMovingImage> (*iter).valueIndex = 0; ++regionIter; + if( regionIter.IsAtEnd() ) + { + regionIter.GoToBegin(); + } } } } @@ -739,9 +901,9 @@ template < class TFixedImage, class TMovingImage > void ImageToImageMetric<TFixedImage,TMovingImage> ::TransformPoint( unsigned int sampleNumber, - MovingImagePointType& mappedPoint, - bool& sampleOk, - double& movingImageValue, + MovingImagePointType & mappedPoint, + bool & sampleOk, + double & movingImageValue, unsigned int threadID ) const { sampleOk = true; @@ -1027,6 +1189,7 @@ void ImageToImageMetric<TFixedImage,TMovingImage> ::GetValueMultiThreadedInitiate( void ) const { + this->SynchronizeTransforms(); m_Threader->SetSingleMethod(GetValueMultiThreaded, @@ -1035,7 +1198,7 @@ ImageToImageMetric<TFixedImage,TMovingImage> for( unsigned int threadID = 0; threadID<m_NumberOfThreads-1; threadID++ ) { - this->m_NumberOfMovingImageSamples += m_ThreaderNumberOfMovingImageSamples[threadID]; + this->m_NumberOfPixelsCounted += m_ThreaderNumberOfMovingImageSamples[threadID]; } } @@ -1071,16 +1234,6 @@ ImageToImageMetric<TFixedImage,TMovingImage> } -template < class TFixedImage, class TMovingImage > -inline void -ImageToImageMetric<TFixedImage,TMovingImage> -::GetValueThreadPreProcess( unsigned int itkNotUsed(threadID), - bool itkNotUsed(withinSampleThread) ) const -{ - // intended to be overloaded in derived classes. -} - - /** * Get the match Measure */ @@ -1128,14 +1281,17 @@ void ImageToImageMetric<TFixedImage,TMovingImage> ::GetValueThread( unsigned int threadID ) const { + // Figure out how many samples to process + int chunkSize = m_NumberOfFixedImageSamples / m_NumberOfThreads; + // Skip to this thread's samples to process - unsigned int fixedImageSample = threadID * m_ThreaderChunkSize; + unsigned int fixedImageSample = threadID * chunkSize; - // Figure out how many samples to process - unsigned int chunkSize = m_ThreaderChunkSize; if(threadID == m_NumberOfThreads - 1) { - chunkSize = m_ThreaderSizeOfLastChunk; + chunkSize = m_NumberOfFixedImageSamples + - ((m_NumberOfThreads-1) + * chunkSize); } int numSamples = 0; @@ -1149,11 +1305,11 @@ ImageToImageMetric<TFixedImage,TMovingImage> MovingImagePointType mappedPoint; bool sampleOk; double movingImageValue; - for( unsigned int count=0; count < chunkSize; ++count, ++fixedImageSample ) + for( int count=0; count < chunkSize; ++count, ++fixedImageSample ) { // Get moving image value this->TransformPoint( fixedImageSample, mappedPoint, sampleOk, movingImageValue, - threadID ); + threadID ); if( sampleOk ) { @@ -1172,7 +1328,7 @@ ImageToImageMetric<TFixedImage,TMovingImage> } else { - m_NumberOfMovingImageSamples = numSamples; + m_NumberOfPixelsCounted = numSamples; } if(m_WithinThreadPostProcess) @@ -1206,7 +1362,7 @@ ImageToImageMetric<TFixedImage,TMovingImage> for( unsigned int threadID = 0; threadID<m_NumberOfThreads-1; threadID++ ) { - this->m_NumberOfMovingImageSamples += m_ThreaderNumberOfMovingImageSamples[threadID]; + this->m_NumberOfPixelsCounted += m_ThreaderNumberOfMovingImageSamples[threadID]; } } @@ -1288,14 +1444,17 @@ void ImageToImageMetric<TFixedImage,TMovingImage> ::GetValueAndDerivativeThread( unsigned int threadID ) const { + // Figure out how many samples to process + int chunkSize = m_NumberOfFixedImageSamples / m_NumberOfThreads; + // Skip to this thread's samples to process - unsigned int fixedImageSample = threadID * m_ThreaderChunkSize; + unsigned int fixedImageSample = threadID * chunkSize; - // Figure out how many samples to process - unsigned int chunkSize = m_ThreaderChunkSize; if(threadID == m_NumberOfThreads - 1) { - chunkSize = m_ThreaderSizeOfLastChunk; + chunkSize = m_NumberOfFixedImageSamples + - ((m_NumberOfThreads-1) + * chunkSize); } int numSamples = 0; @@ -1310,7 +1469,7 @@ ImageToImageMetric<TFixedImage,TMovingImage> bool sampleOk; double movingImageValue; ImageDerivativesType movingImageGradientValue; - for( unsigned int count=0; count < chunkSize; ++count, ++fixedImageSample ) + for( int count=0; count < chunkSize; ++count, ++fixedImageSample ) { // Get moving image value TransformPointWithDerivatives( fixedImageSample, mappedPoint, sampleOk, @@ -1320,12 +1479,11 @@ ImageToImageMetric<TFixedImage,TMovingImage> if( sampleOk ) { // CALL USER FUNCTION - if( this->GetValueAndDerivativeThreadProcessSample( - threadID, - fixedImageSample, - mappedPoint, - movingImageValue, - movingImageGradientValue )) + if( this->GetValueAndDerivativeThreadProcessSample( threadID, + fixedImageSample, + mappedPoint, + movingImageValue, + movingImageGradientValue )) { ++numSamples; } @@ -1338,7 +1496,7 @@ ImageToImageMetric<TFixedImage,TMovingImage> } else { - m_NumberOfMovingImageSamples = numSamples; + m_NumberOfPixelsCounted = numSamples; } if(m_WithinThreadPostProcess) @@ -1368,18 +1526,40 @@ ImageToImageMetric<TFixedImage,TMovingImage> os << indent << "UseFixedImageSamplesIntensityThreshold: "; os << m_UseFixedImageSamplesIntensityThreshold << std::endl; + if( m_UseFixedImageIndexes ) + { + os << indent << "Use Fixed Image Indexes: True" << std::endl; + os << indent << "Number of Fixed Image Indexes = " + << m_FixedImageIndexes.size() << std::endl; + } + else + { + os << indent << "Use Fixed Image Indexes: False" << std::endl; + } + + if( m_UseSequentialSampling ) + { + os << indent << "Use Sequential Sampling: True" << std::endl; + } + else + { + os << indent << "Use Sequential Sampling: False" << std::endl; + } + os << indent << "UseAllPixels: "; os << m_UseAllPixels << std::endl; os << indent << "Threader: " << m_Threader << std::endl; os << indent << "Number of Threads: " << m_NumberOfThreads << std::endl; os << indent << "ThreaderParameter: " << std::endl; -// os << (unsigned int)(m_ThreaderParameter.metric) << std::endl; - os << indent << "ThreaderChunkSize: " << m_ThreaderChunkSize << std::endl; - os << indent << "ThreaderSizeOfLastChunk: " << m_ThreaderSizeOfLastChunk - << std::endl; os << indent << "ThreaderNumberOfMovingImageSamples: " << std::endl; -// os << (unsigned int)m_ThreaderNumberOfMovingImageSamples << std::endl; + if( m_ThreaderNumberOfMovingImageSamples ) + { + for(unsigned int i=0; i<m_NumberOfThreads-1; i++) + { + os << " Thread[" << i << "]= " << (unsigned int)m_ThreaderNumberOfMovingImageSamples[i] << std::endl; + } + } os << indent << "ComputeGradient: " << static_cast<typename NumericTraits<bool>::PrintType>(m_ComputeGradient) @@ -1395,9 +1575,7 @@ ImageToImageMetric<TFixedImage,TMovingImage> << std::endl; os << indent << "Fixed Image Mask: " << m_FixedImageMask.GetPointer() << std::endl; - os << indent << "Number of Moving Image Samples: " << m_NumberOfMovingImageSamples - << std::endl; - os << indent << "Number of Pixels Counted: " << m_NumberOfPixelsCounted + os << indent << "Number of Moving Image Samples: " << m_NumberOfPixelsCounted << std::endl; os << indent << "UseCachingOfBSplineWeights: "; @@ -1423,17 +1601,6 @@ ImageToImageMetric<TFixedImage,TMovingImage> } } -template <class TFixedImage, class TMovingImage> -void -ImageToImageMetric<TFixedImage,TMovingImage> -::NumberOfFixedImageSamplesUpdated() -{ - m_ThreaderChunkSize = m_NumberOfFixedImageSamples / m_NumberOfThreads; - m_ThreaderSizeOfLastChunk = m_NumberOfFixedImageSamples - - ((m_NumberOfThreads-1) - * m_ThreaderChunkSize); -} - } // end namespace itk #endif diff --git a/Utilities/ITK/Code/Review/itkOptLinearInterpolateImageFunction.h b/Utilities/ITK/Code/Review/itkOptLinearInterpolateImageFunction.h index e17ae6da7d7984a837f7c55784bf132ff0aae1a2..dc5c08bd40ce602b4932f11402da11376c62bfda 100755 --- a/Utilities/ITK/Code/Review/itkOptLinearInterpolateImageFunction.h +++ b/Utilities/ITK/Code/Review/itkOptLinearInterpolateImageFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptLinearInterpolateImageFunction.h,v $ Language: C++ - Date: $Date: 2009-03-20 10:25:38 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-07-29 07:38:01 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -39,7 +39,7 @@ namespace itk * * \ingroup ImageFunctions ImageInterpolators */ -template <class TInputImage, class TCoordRep = float> +template <class TInputImage, class TCoordRep = double> class ITK_EXPORT LinearInterpolateImageFunction : public InterpolateImageFunction<TInputImage,TCoordRep> { @@ -118,21 +118,29 @@ private: { IndexType basei; - double i = index[0]; - basei[0] = (long)i; - if( i < 0.0 && double(basei[0]) != i) + basei[0] = Math::Floor(index[0]); + if( basei[0] < this->m_StartIndex[0] ) { - basei[0]--; + basei[0] = this->m_StartIndex[0]; } - double distance = i - double(basei[0]); + const double distance = index[0] - static_cast<double>(basei[0]); + + const RealType val0 = this->GetInputImage()->GetPixel( basei ); + + if(distance <= 0.) + { + return( static_cast<OutputType>( val0 ) ); + } - double val0 = this->GetInputImage()->GetPixel( basei ); - double val1 = val0; ++basei[0]; - val1 = this->GetInputImage()->GetPixel( basei ); + if(basei[0]>this->m_EndIndex[0]) + { + return( static_cast<OutputType>( val0 ) ); + } + const RealType val1 = this->GetInputImage()->GetPixel( basei ); - return( static_cast<OutputType>( val0 + distance * ( val1 - val0 ) ) ); + return( static_cast<OutputType>( val0 + ( val1 - val0 ) * distance ) ); } inline OutputType EvaluateOptimized( const Dispatch<2>&, @@ -140,61 +148,76 @@ private: { IndexType basei; - double i = index[0]; - basei[0] = (long)i; - if( i < 0.0 && double(basei[0]) != i) + basei[0] = Math::Floor(index[0]); + if( basei[0] < this->m_StartIndex[0] ) { - basei[0]--; + basei[0] = this->m_StartIndex[0]; } - double distance0 = i - double(basei[0]); + const double distance0 = index[0] - static_cast<double>(basei[0]); - i = index[1]; - basei[1] = (long)i; - if( i < 0.0 && double(basei[1]) != i) + basei[1] = Math::Floor(index[1]); + if( basei[1] < this->m_StartIndex[1] ) { - basei[1]--; + basei[1] = this->m_StartIndex[1]; } - double distance1 = i - double(basei[1]); + const double distance1 = index[1] - static_cast<double>(basei[1]); - double val00 = this->GetInputImage()->GetPixel( basei ); - if(distance0+distance1 == 0) + const RealType val00 = this->GetInputImage()->GetPixel( basei ); + if(distance0 <= 0. && distance1 <= 0.) { return( static_cast<OutputType>( val00 ) ); } - else if(distance1 == 0) // if they have the same "y" + else if(distance1 <= 0.) // if they have the same "y" { ++basei[0]; // then interpolate across "x" if(basei[0]>this->m_EndIndex[0]) { return( static_cast<OutputType>( val00 ) ); } - double val10 = this->GetInputImage()->GetPixel( basei ); - return( static_cast<OutputType>(val00 + distance0 * (val10 - val00)) ); + const RealType val10 = this->GetInputImage()->GetPixel( basei ); + return( static_cast<OutputType>(val00 + (val10 - val00) * distance0) ); } - else if(distance0 == 0) // if they have the same "x" + else if(distance0 <= 0.) // if they have the same "x" { ++basei[1]; // then interpolate across "y" if(basei[1]>this->m_EndIndex[1]) { return( static_cast<OutputType>( val00 ) ); } - double val01 = this->GetInputImage()->GetPixel( basei ); - return( static_cast<OutputType>(val00 + distance1 * (val01 - val00)) ); + const RealType val01 = this->GetInputImage()->GetPixel( basei ); + return( static_cast<OutputType>(val00 + (val01 - val00) * distance1) ); } - else + else // interpolate across "xy" { ++basei[0]; - double val10 = this->GetInputImage()->GetPixel( basei ); + if(basei[0]>this->m_EndIndex[0]) // interpolate across "y" + { + --basei[0]; + ++basei[1]; + if(basei[1]>this->m_EndIndex[1]) + { + return( static_cast<OutputType>( val00 ) ); + } + const RealType val01 = this->GetInputImage()->GetPixel( basei ); + return( static_cast<OutputType>(val00 + (val01 - val00) * distance1) ); + } + const RealType val10 = this->GetInputImage()->GetPixel( basei ); + + const RealType valx0 = val00 + (val10 - val00) * distance0; + ++basei[1]; - double val11 = this->GetInputImage()->GetPixel( basei ); + if(basei[1]>this->m_EndIndex[1]) // interpolate across "x" + { + return( static_cast<OutputType>( valx0 ) ); + } + const RealType val11 = this->GetInputImage()->GetPixel( basei ); --basei[0]; - double val01 = this->GetInputImage()->GetPixel( basei ); - - double val0 = val00 + distance1 * ( val01 - val00 ); // interpolate across "y" - double val1 = val10 + distance1 * ( val11 - val10 ); // interpolate across "y" + const RealType val01 = this->GetInputImage()->GetPixel( basei ); + + const RealType valx1 = val01 + (val11 - val01) * distance0; - return( static_cast<OutputType>( val0 + distance0 * (val1-val0) ) ); // interpolate across "X" + return( static_cast<OutputType>( valx0 + (valx1-valx0) * distance1 ) ); } } @@ -202,166 +225,267 @@ private: const ContinuousIndexType & index) const { IndexType basei; - double val[8]; - - unsigned long min0; - unsigned long max0; - unsigned long min1; - unsigned long max1; - unsigned long min2; - unsigned long max2; - - double i = index[0]; - basei[0] = (long)i; - if( i < 0.0 && double(basei[0]) != i) + + basei[0] = Math::Floor(index[0]); + if( basei[0] < this->m_StartIndex[0] ) { - basei[0]--; + basei[0] = this->m_StartIndex[0]; } - double distance0 = i - double(basei[0]); + const double distance0 = index[0] - static_cast<double>(basei[0]); - i = index[1]; - basei[1] = (long)i; - if( i < 0.0 && double(basei[1]) != i) + basei[1] = Math::Floor(index[1]); + if( basei[1] < this->m_StartIndex[1] ) { - basei[1]--; + basei[1] = this->m_StartIndex[1]; } - double distance1 = i - double(basei[1]); + const double distance1 = index[1] - static_cast<double>(basei[1]); - i = index[2]; - basei[2] = (long)i; - if( i < 0.0 && double(basei[2]) != i) + basei[2] = Math::Floor(index[2]); + if( basei[2] < this->m_StartIndex[2] ) { - basei[2]--; + basei[2] = this->m_StartIndex[2]; } - double distance2 = i - double(basei[2]); + const double distance2 = index[2] - static_cast<double>(basei[2]); - val[0] = this->GetInputImage()->GetPixel( basei ); - if(distance0+distance1+distance2 == 0) - { - return( static_cast<OutputType>( val[0] ) ); - } - if(distance0 > 0.0) - { - min0 = basei[0]; - max0 = basei[0]+1; - if(max0>this->m_EndIndex[0]) - { - max0 = this->m_EndIndex[0]; - } - } - if(distance1 > 0.0) + if(distance0<=0. && distance1<=0. && distance2<=0.) { - min1 = basei[1]; - max1 = basei[1]+1; - if(max1>this->m_EndIndex[1]) - { - max1 = this->m_EndIndex[1]; - } + return( static_cast<OutputType>( this->GetInputImage()->GetPixel( basei ) ) ); } - if(distance2 > 0.0) - { - min2 = basei[2]; - max2 = basei[2]+1; - if(max2>this->m_EndIndex[2]) - { - max2 = this->m_EndIndex[2]; - } - } - if(distance2 == 0) + + typedef typename IndexType::IndexValueType IndexValueType; + + const RealType val000 = this->GetInputImage()->GetPixel( basei ); + + if(distance2 <= 0.) { - if(distance1 == 0) + if(distance1 <= 0.) // interpolate across "x" { - basei[0] = max0; - val[1] = this->GetInputImage()->GetPixel( basei ); - - double val0 = val[0] + distance0 * (val[1]-val[0]); + ++basei[0]; + if(basei[0]>this->m_EndIndex[0]) + { + return( static_cast<OutputType>( val000 ) ); + } + const RealType val100 = this->GetInputImage()->GetPixel( basei ); - return( static_cast<OutputType>( val0 ) ); + return static_cast<OutputType>( val000 + (val100-val000) * distance0 ); } - else if(distance0 == 0) + else if(distance0 <= 0.) // interpolate across "y" { - basei[1] = max1; - val[2] = this->GetInputImage()->GetPixel( basei ); - - double val0 = val[0] + distance1 * (val[2]-val[0]); + ++basei[1]; + if(basei[1]>this->m_EndIndex[1]) + { + return( static_cast<OutputType>( val000 ) ); + } + const RealType val010 = this->GetInputImage()->GetPixel( basei ); - return( static_cast<OutputType>( val0 ) ); + return static_cast<OutputType>( val000 + (val010-val000) * distance1 ); } - else + else // interpolate across "xy" { - basei[0] = max0; - val[1] = this->GetInputImage()->GetPixel( basei ); - basei[1] = max1; - val[3] = this->GetInputImage()->GetPixel( basei ); - basei[0] = min0; - val[2] = this->GetInputImage()->GetPixel( basei ); - - double val0 = val[0] + distance0 * (val[1]-val[0]); - double val1 = val[2] + distance0 * (val[3]-val[2]); + ++basei[0]; + if(basei[0]>this->m_EndIndex[0]) // interpolate across "y" + { + --basei[0]; + ++basei[1]; + if(basei[1]>this->m_EndIndex[1]) + { + return( static_cast<OutputType>( val000 ) ); + } + const RealType val010 = this->GetInputImage()->GetPixel( basei ); + + return static_cast<OutputType>( val000 + (val010-val000) * distance1 ); + } + const RealType val100 = this->GetInputImage()->GetPixel( basei ); + + const RealType valx00 = val000 + (val100-val000) * distance0; - return( static_cast<OutputType>( val0 + distance1 * (val1 - val0) ) ); + ++basei[1]; + if(basei[1]>this->m_EndIndex[1]) // interpolate across "x" + { + return( static_cast<OutputType>( valx00 ) ); + } + const RealType val110 = this->GetInputImage()->GetPixel( basei ); + + --basei[0]; + const RealType val010 = this->GetInputImage()->GetPixel( basei ); + + const RealType valx10 = val010 + (val110-val010) * distance0; + + return static_cast<OutputType>( valx00 + (valx10-valx00) * distance1 ); } } else { - basei[2] = max2; - val[4] = this->GetInputImage()->GetPixel( basei ); - if(distance1 == 0) + if(distance1 <= 0.) { - if(distance0 == 0) + if(distance0 <= 0.) // interpolate across "z" { - return( static_cast<OutputType>( val[0] + distance2 - * (val[4] - val[0]) ) ); + ++basei[2]; + if(basei[2]>this->m_EndIndex[2]) + { + return( static_cast<OutputType>( val000 ) ); + } + const RealType val001 = this->GetInputImage()->GetPixel( basei ); + + return static_cast<OutputType>( val000 + (val001-val000) * distance2 ); } - else + else // interpolate across "xz" { - basei[0] = max0; - val[5] = this->GetInputImage()->GetPixel( basei ); - basei[2] = min2; - val[1] = this->GetInputImage()->GetPixel( basei ); - - double val0 = val[0] + distance0 * (val[1]-val[0]); - double val1 = val[4] + distance0 * (val[5]-val[4]); - - return( static_cast<OutputType>( val0 + distance2 * (val1 - val0) ) ); + ++basei[0]; + if(basei[0]>this->m_EndIndex[0]) // interpolate across "z" + { + --basei[0]; + ++basei[2]; + if(basei[2]>this->m_EndIndex[2]) + { + return( static_cast<OutputType>( val000 ) ); + } + const RealType val001 = this->GetInputImage()->GetPixel( basei ); + + return static_cast<OutputType>( val000 + (val001-val000) * distance2 ); + } + const RealType val100 = this->GetInputImage()->GetPixel( basei ); + + const RealType valx00 = val000 + (val100-val000) * distance0; + + ++basei[2]; + if(basei[2]>this->m_EndIndex[2]) // interpolate across "x" + { + return( static_cast<OutputType>( valx00 ) ); + } + const RealType val101 = this->GetInputImage()->GetPixel( basei ); + + --basei[0]; + const RealType val001 = this->GetInputImage()->GetPixel( basei ); + + const RealType valx01 = val001 + (val101-val001) * distance0; + + return static_cast<OutputType>( valx00 + (valx01-valx00) * distance2 ); } } - else if(distance0 == 0) + else if(distance0 <= 0.) // interpolate across "yz" { - basei[1] = max1; - val[6] = this->GetInputImage()->GetPixel( basei ); - basei[2] = min2; - val[2] = this->GetInputImage()->GetPixel( basei ); - - double val0 = val[0] + distance1 * (val[2]-val[0]); - double val1 = val[4] + distance1 * (val[6]-val[4]); - - return( static_cast<OutputType>( val0 + distance2 * (val1 - val0) ) ); + ++basei[1]; + if(basei[1]>this->m_EndIndex[1]) // interpolate across "z" + { + --basei[1]; + ++basei[2]; + if(basei[2]>this->m_EndIndex[2]) + { + return( static_cast<OutputType>( val000 ) ); + } + const RealType val001 = this->GetInputImage()->GetPixel( basei ); + + return static_cast<OutputType>( val000 + (val001-val000) * distance2 ); + } + const RealType val010 = this->GetInputImage()->GetPixel( basei ); + + const RealType val0x0 = val000 + (val010-val000) * distance1; + + ++basei[2]; + if(basei[2]>this->m_EndIndex[2]) // interpolate across "y" + { + return( static_cast<OutputType>( val0x0 ) ); + } + const RealType val011 = this->GetInputImage()->GetPixel( basei ); + + --basei[1]; + const RealType val001 = this->GetInputImage()->GetPixel( basei ); + + const RealType val0x1 = val001 + (val011-val001) * distance1; + + return static_cast<OutputType>( val0x0 + (val0x1-val0x0) * distance2 ); } - else + else // interpolate across "xyz" { - basei[0] = max0; - val[5] = this->GetInputImage()->GetPixel( basei ); - basei[1] = max1; - val[7] = this->GetInputImage()->GetPixel( basei ); - basei[0] = min0; - val[6] = this->GetInputImage()->GetPixel( basei ); - basei[2] = min2; - val[2] = this->GetInputImage()->GetPixel( basei ); - basei[0] = max0; - val[3] = this->GetInputImage()->GetPixel( basei ); - basei[1] = min1; - val[1] = this->GetInputImage()->GetPixel( basei ); - - double val00 = val[0] + distance0 * (val[1]-val[0]); - double val01 = val[2] + distance0 * (val[3]-val[2]); - double val0 = val00 + distance1 * (val01-val00); - - double val10 = val[4] + distance0 * (val[5]-val[4]); - double val11 = val[6] + distance0 * (val[7]-val[6]); - double val1 = val10 + distance1 * (val11-val10); - - return( static_cast<OutputType>( val0 + distance2 * (val1-val0) ) ); + ++basei[0]; + if(basei[0]>this->m_EndIndex[0]) // interpolate across "yz" + { + --basei[0]; + ++basei[1]; + if(basei[1]>this->m_EndIndex[1]) // interpolate across "z" + { + --basei[1]; + ++basei[2]; + if(basei[2]>this->m_EndIndex[2]) + { + return( static_cast<OutputType>( val000 ) ); + } + const RealType val001 = this->GetInputImage()->GetPixel( basei ); + + return static_cast<OutputType>( val000 + (val001-val000) * distance2 ); + } + const RealType val010 = this->GetInputImage()->GetPixel( basei ); + + const RealType val0x0 = val000 + (val010-val000) * distance1; + + ++basei[2]; + if(basei[2]>this->m_EndIndex[2]) // interpolate across "y" + { + return( static_cast<OutputType>( val0x0 ) ); + } + const RealType val011 = this->GetInputImage()->GetPixel( basei ); + + --basei[1]; + const RealType val001 = this->GetInputImage()->GetPixel( basei ); + + const RealType val0x1 = val001 + (val011-val001) * distance1; + + return static_cast<OutputType>( val0x0 + (val0x1-val0x0) * distance2 ); + } + const RealType val100 = this->GetInputImage()->GetPixel( basei ); + + const RealType valx00 = val000 + (val100-val000) * distance0; + + ++basei[1]; + if(basei[1]>this->m_EndIndex[1]) // interpolate across "xz" + { + --basei[1]; + ++basei[2]; + if(basei[2]>this->m_EndIndex[2]) // interpolate across "x" + { + return( static_cast<OutputType>( valx00 ) ); + } + const RealType val101 = this->GetInputImage()->GetPixel( basei ); + + --basei[0]; + const RealType val001 = this->GetInputImage()->GetPixel( basei ); + + const RealType valx01 = val001 + (val101-val001) * distance0; + + return static_cast<OutputType>( valx00 + (valx01-valx00) * distance2 ); + } + const RealType val110 = this->GetInputImage()->GetPixel( basei ); + + --basei[0]; + const RealType val010 = this->GetInputImage()->GetPixel( basei ); + + const RealType valx10 = val010 + (val110-val010) * distance0; + + const RealType valxx0 = valx00 + (valx10-valx00) * distance1; + + + ++basei[2]; + if(basei[2]>this->m_EndIndex[2]) // interpolate across "xy" + { + return( static_cast<OutputType>( valxx0 ) ); + } + const RealType val011 = this->GetInputImage()->GetPixel( basei ); + + ++basei[0]; + const RealType val111 = this->GetInputImage()->GetPixel( basei ); + + --basei[1]; + const RealType val101 = this->GetInputImage()->GetPixel( basei ); + + --basei[0]; + const RealType val001 = this->GetInputImage()->GetPixel( basei ); + + const RealType valx01 = val001 + (val101-val001) * distance0; + const RealType valx11 = val011 + (val111-val011) * distance0; + const RealType valxx1 = valx01 + (valx11-valx01) * distance1; + + return( static_cast<OutputType>( valxx0 + (valxx1-valxx0) * distance2 ) ); } } } diff --git a/Utilities/ITK/Code/Review/itkOptLinearInterpolateImageFunction.txx b/Utilities/ITK/Code/Review/itkOptLinearInterpolateImageFunction.txx index 039d3e7c392530734c74979dcb84bd063ad53a87..9813cf2e7540686dbcbe1421691d767324482141 100755 --- a/Utilities/ITK/Code/Review/itkOptLinearInterpolateImageFunction.txx +++ b/Utilities/ITK/Code/Review/itkOptLinearInterpolateImageFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptLinearInterpolateImageFunction.txx,v $ Language: C++ - Date: $Date: 2009-03-20 10:25:37 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-07-29 07:38:01 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -17,7 +17,7 @@ #ifndef __itkOptLinearInterpolateImageFunction_txx #define __itkOptLinearInterpolateImageFunction_txx -#include "itkLinearInterpolateImageFunction.h" +#include "itkOptLinearInterpolateImageFunction.h" #include "vnl/vnl_math.h" @@ -77,27 +77,11 @@ LinearInterpolateImageFunction< TInputImage, TCoordRep > */ signed long baseIndex[ImageDimension]; double distance[ImageDimension]; - long tIndex; for( dim = 0; dim < ImageDimension; dim++ ) { - // The following "if" block is equivalent to the following line without - // having to call floor. - // baseIndex[dim] = (long) vcl_floor(index[dim] ); - if (index[dim] >= 0.0) - { - baseIndex[dim] = (long) index[dim]; - } - else - { - tIndex = (long) index[dim]; - if (double(tIndex) != index[dim]) - { - tIndex--; - } - baseIndex[dim] = tIndex; - } - distance[dim] = index[dim] - static_cast< RealType >( baseIndex[dim] ); + baseIndex[dim] = Math::Floor( index[dim] ); + distance[dim] = index[dim] - static_cast< double >( baseIndex[dim] ); } /** @@ -124,11 +108,27 @@ LinearInterpolateImageFunction< TInputImage, TCoordRep > if ( upper & 1 ) { neighIndex[dim] = baseIndex[dim] + 1; +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + // Take care of the case where the pixel is just + // in the outer upper boundary of the image grid. + if( neighIndex[dim] > this->m_EndIndex[dim] ) + { + neighIndex[dim] = this->m_EndIndex[dim]; + } +#endif overlap *= distance[dim]; } else { neighIndex[dim] = baseIndex[dim]; +#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY + // Take care of the case where the pixel is just + // in the outer lower boundary of the image grid. + if( neighIndex[dim] < this->m_StartIndex[dim] ) + { + neighIndex[dim] = this->m_StartIndex[dim]; + } +#endif overlap *= 1.0 - distance[dim]; } diff --git a/Utilities/ITK/Code/Review/itkOptMattesMutualInformationImageToImageMetric.h b/Utilities/ITK/Code/Review/itkOptMattesMutualInformationImageToImageMetric.h index 67ccfbfa7947f3e3f6ad6bd47fd268f38f876a24..77521e439faa01693a12fb80ccbf585e43ed4c7b 100755 --- a/Utilities/ITK/Code/Review/itkOptMattesMutualInformationImageToImageMetric.h +++ b/Utilities/ITK/Code/Review/itkOptMattesMutualInformationImageToImageMetric.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptMattesMutualInformationImageToImageMetric.h,v $ Language: C++ - Date: $Date: 2008-04-03 12:34:38 $ - Version: $Revision: 1.6 $ + Date: $Date: 2009-07-28 21:47:09 $ + Version: $Revision: 1.7 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -311,25 +311,25 @@ private: mutable bool m_ImplicitDerivativesSecondPass; - inline void GetValueThreadPreProcess( unsigned int threadID, + virtual inline void GetValueThreadPreProcess( unsigned int threadID, bool withinSampleThread ) const; - inline bool GetValueThreadProcessSample( unsigned int threadID, + virtual inline bool GetValueThreadProcessSample( unsigned int threadID, unsigned long fixedImageSample, const MovingImagePointType & mappedPoint, double movingImageValue ) const; - inline void GetValueThreadPostProcess( unsigned int threadID, + virtual inline void GetValueThreadPostProcess( unsigned int threadID, bool withinSampleThread ) const; - inline void GetValueAndDerivativeThreadPreProcess( + virtual inline void GetValueAndDerivativeThreadPreProcess( unsigned int threadID, bool withinSampleThread ) const; - inline bool GetValueAndDerivativeThreadProcessSample( unsigned int threadID, + virtual inline bool GetValueAndDerivativeThreadProcessSample( unsigned int threadID, unsigned long fixedImageSample, const MovingImagePointType & mappedPoint, double movingImageValue, const ImageDerivativesType & movingImageGradientValue ) const; - inline void GetValueAndDerivativeThreadPostProcess( + virtual inline void GetValueAndDerivativeThreadPostProcess( unsigned int threadID, bool withinSampleThread ) const; diff --git a/Utilities/ITK/Code/Review/itkOptMattesMutualInformationImageToImageMetric.txx b/Utilities/ITK/Code/Review/itkOptMattesMutualInformationImageToImageMetric.txx index 21237e2e6f0af91f7a35560ca2ae6973b30b6f81..b80676948f700591a89ef1c5a9cb98e486458c81 100755 --- a/Utilities/ITK/Code/Review/itkOptMattesMutualInformationImageToImageMetric.txx +++ b/Utilities/ITK/Code/Review/itkOptMattesMutualInformationImageToImageMetric.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptMattesMutualInformationImageToImageMetric.txx,v $ Language: C++ - Date: $Date: 2008-04-07 03:09:27 $ - Version: $Revision: 1.30 $ + Date: $Date: 2009-08-25 11:48:31 $ + Version: $Revision: 1.33 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -504,7 +504,7 @@ MattesMutualInformationImageToImageMetric<TFixedImage,TMovingImage> } else { - // Reset the joint pdfs to zero + // zero-th thread uses the variables directly memset( m_JointPDF->GetBufferPointer(), 0, m_JointPDFBufferSize ); @@ -517,11 +517,10 @@ MattesMutualInformationImageToImageMetric<TFixedImage,TMovingImage> template < class TFixedImage, class TMovingImage > inline bool MattesMutualInformationImageToImageMetric<TFixedImage,TMovingImage> -::GetValueThreadProcessSample( - unsigned int threadID, - unsigned long fixedImageSample, - const MovingImagePointType & itkNotUsed(mappedPoint), - double movingImageValue) const +::GetValueThreadProcessSample( unsigned int threadID, + unsigned long fixedImageSample, + const MovingImagePointType & itkNotUsed(mappedPoint), + double movingImageValue) const { /** * Compute this sample's contribution to the marginal and @@ -589,9 +588,9 @@ MattesMutualInformationImageToImageMetric<TFixedImage,TMovingImage> double movingImageParzenWindowArg = static_cast<double>( pdfMovingIndex ) - - static_cast<double>( movingImageParzenWindowTerm ); + - movingImageParzenWindowTerm; - while (pdfMovingIndex <= pdfMovingIndexMax) + while( pdfMovingIndex <= pdfMovingIndexMax ) { *(pdfPtr++) += static_cast<PDFValueType>( m_CubicBSplineKernel ->Evaluate( @@ -705,11 +704,11 @@ MattesMutualInformationImageToImageMetric<TFixedImage,TMovingImage> } } - if( this->m_NumberOfMovingImageSamples < - this->m_NumberOfFixedImageSamples / 4 ) + if( this->m_NumberOfPixelsCounted < + this->m_NumberOfFixedImageSamples / 16 ) { itkExceptionMacro( "Too many samples map outside moving image buffer: " - << this->m_NumberOfMovingImageSamples << " / " + << this->m_NumberOfPixelsCounted << " / " << this->m_NumberOfFixedImageSamples << std::endl ); } @@ -810,14 +809,12 @@ MattesMutualInformationImageToImageMetric<TFixedImage,TMovingImage> template < class TFixedImage, class TMovingImage > inline bool MattesMutualInformationImageToImageMetric<TFixedImage,TMovingImage> -::GetValueAndDerivativeThreadProcessSample( - unsigned int threadID, - unsigned long fixedImageSample, - const MovingImagePointType & itkNotUsed(mappedPoint), - double movingImageValue, - const ImageDerivativesType & - movingImageGradientValue - ) const +::GetValueAndDerivativeThreadProcessSample( unsigned int threadID, + unsigned long fixedImageSample, + const MovingImagePointType & itkNotUsed(mappedPoint), + double movingImageValue, + const ImageDerivativesType & + movingImageGradientValue) const { /** * Compute this sample's contribution to the marginal @@ -903,7 +900,7 @@ MattesMutualInformationImageToImageMetric<TFixedImage,TMovingImage> double movingImageParzenWindowArg = static_cast<double>( pdfMovingIndex ) - static_cast<double>( movingImageParzenWindowTerm ); - while (pdfMovingIndex <= pdfMovingIndexMax) + while( pdfMovingIndex <= pdfMovingIndexMax ) { *(pdfPtr++) += static_cast<PDFValueType>( m_CubicBSplineKernel ->Evaluate( @@ -968,7 +965,7 @@ MattesMutualInformationImageToImageMetric<TFixedImage,TMovingImage> } double nFactor = 1.0 / (m_MovingImageBinSize - * this->m_NumberOfMovingImageSamples); + * this->m_NumberOfPixelsCounted); pdfDPtr = pdfDPtrStart; tPdfDPtrEnd = pdfDPtrStart + maxI; @@ -1056,11 +1053,11 @@ MattesMutualInformationImageToImageMetric<TFixedImage,TMovingImage> } } - if( this->m_NumberOfMovingImageSamples < - this->m_NumberOfFixedImageSamples / 4 ) + if( this->m_NumberOfPixelsCounted < + this->m_NumberOfFixedImageSamples / 16 ) { itkExceptionMacro( "Too many samples map outside moving image buffer: " - << this->m_NumberOfMovingImageSamples << " / " + << this->m_NumberOfPixelsCounted << " / " << this->m_NumberOfFixedImageSamples << std::endl ); } @@ -1086,7 +1083,7 @@ MattesMutualInformationImageToImageMetric<TFixedImage,TMovingImage> double sum = 0.0; const double nFactor = 1.0 / (m_MovingImageBinSize - * this->m_NumberOfMovingImageSamples); + * this->m_NumberOfPixelsCounted); for( unsigned int fixedIndex = 0; fixedIndex < m_NumberOfHistogramBins; diff --git a/Utilities/ITK/Code/Review/itkOptMeanSquaresImageToImageMetric.txx b/Utilities/ITK/Code/Review/itkOptMeanSquaresImageToImageMetric.txx index 4c1f414b1880e0773cfb6519b8886f6ebfe0f6c6..5b4ff0c8fd76b46e90b09402b5c14885b4fba4fa 100755 --- a/Utilities/ITK/Code/Review/itkOptMeanSquaresImageToImageMetric.txx +++ b/Utilities/ITK/Code/Review/itkOptMeanSquaresImageToImageMetric.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptMeanSquaresImageToImageMetric.txx,v $ Language: C++ - Date: $Date: 2008-02-05 16:03:07 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-08-24 17:42:02 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -44,7 +44,8 @@ MeanSquaresImageToImageMetric<TFixedImage,TMovingImage> // For backward compatibility, the default behavior is to use all the pixels // in the fixed image. - this->UseAllPixelsOn(); + // This should be fixed in ITKv4 so that this metric behaves as the others. + this->SetUseAllPixels( true ); } template < class TFixedImage, class TMovingImage > @@ -110,14 +111,12 @@ MeanSquaresImageToImageMetric<TFixedImage,TMovingImage> template < class TFixedImage, class TMovingImage > inline bool MeanSquaresImageToImageMetric<TFixedImage,TMovingImage> -::GetValueThreadProcessSample( - unsigned int threadID, - unsigned long fixedImageSample, - const MovingImagePointType & itkNotUsed(mappedPoint), - double movingImageValue) const +::GetValueThreadProcessSample( unsigned int threadID, + unsigned long fixedImageSample, + const MovingImagePointType & itkNotUsed(mappedPoint), + double movingImageValue) const { - double diff = movingImageValue - - this->m_FixedImageSamples[fixedImageSample].value; + double diff = movingImageValue - this->m_FixedImageSamples[fixedImageSample].value; m_ThreaderMSE[threadID] += diff*diff; @@ -149,15 +148,15 @@ MeanSquaresImageToImageMetric<TFixedImage,TMovingImage> this->GetValueMultiThreadedInitiate(); itkDebugMacro( "Ratio of voxels mapping into moving image buffer: " - << this->m_NumberOfMovingImageSamples << " / " + << this->m_NumberOfPixelsCounted << " / " << this->m_NumberOfFixedImageSamples << std::endl ); - if( this->m_NumberOfMovingImageSamples < + if( this->m_NumberOfPixelsCounted < this->m_NumberOfFixedImageSamples / 4 ) { itkExceptionMacro( "Too many samples map outside moving image buffer: " - << this->m_NumberOfMovingImageSamples << " / " + << this->m_NumberOfPixelsCounted << " / " << this->m_NumberOfFixedImageSamples << std::endl ); } @@ -167,7 +166,7 @@ MeanSquaresImageToImageMetric<TFixedImage,TMovingImage> { mse += m_ThreaderMSE[t]; } - mse /= this->m_NumberOfMovingImageSamples; + mse /= this->m_NumberOfPixelsCounted; return mse; } @@ -176,17 +175,14 @@ MeanSquaresImageToImageMetric<TFixedImage,TMovingImage> template < class TFixedImage, class TMovingImage > inline bool MeanSquaresImageToImageMetric<TFixedImage,TMovingImage> -::GetValueAndDerivativeThreadProcessSample( - unsigned int threadID, - unsigned long fixedImageSample, - const MovingImagePointType & itkNotUsed(mappedPoint), - double movingImageValue, - const ImageDerivativesType & - movingImageGradientValue - ) const +::GetValueAndDerivativeThreadProcessSample( unsigned int threadID, + unsigned long fixedImageSample, + const MovingImagePointType & itkNotUsed(mappedPoint), + double movingImageValue, + const ImageDerivativesType & + movingImageGradientValue ) const { - double diff = movingImageValue - - this->m_FixedImageSamples[fixedImageSample].value; + double diff = movingImageValue - this->m_FixedImageSamples[fixedImageSample].value; m_ThreaderMSE[threadID] += diff*diff; @@ -271,15 +267,15 @@ MeanSquaresImageToImageMetric<TFixedImage,TMovingImage> this->GetValueAndDerivativeMultiThreadedInitiate(); itkDebugMacro( "Ratio of voxels mapping into moving image buffer: " - << this->m_NumberOfMovingImageSamples << " / " + << this->m_NumberOfPixelsCounted << " / " << this->m_NumberOfFixedImageSamples << std::endl ); - if( this->m_NumberOfMovingImageSamples < + if( this->m_NumberOfPixelsCounted < this->m_NumberOfFixedImageSamples / 4 ) { itkExceptionMacro( "Too many samples map outside moving image buffer: " - << this->m_NumberOfMovingImageSamples << " / " + << this->m_NumberOfPixelsCounted << " / " << this->m_NumberOfFixedImageSamples << std::endl ); } @@ -295,11 +291,11 @@ MeanSquaresImageToImageMetric<TFixedImage,TMovingImage> } } - value /= this->m_NumberOfMovingImageSamples; + value /= this->m_NumberOfPixelsCounted; for(unsigned int parameter = 0; parameter < this->m_NumberOfParameters; parameter++) { - derivative[parameter] /= this->m_NumberOfMovingImageSamples; + derivative[parameter] /= this->m_NumberOfPixelsCounted; } } diff --git a/Utilities/ITK/Code/Review/itkOptResampleImageFilter.txx b/Utilities/ITK/Code/Review/itkOptResampleImageFilter.txx index e51ad8e881ff305f8a78d3ab7942c77e310fdd6a..c9ec7e72a3681f59fc5d2efabc4e1d0c1f3606af 100755 --- a/Utilities/ITK/Code/Review/itkOptResampleImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkOptResampleImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkOptResampleImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-11-15 11:06:55 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-08-24 13:49:19 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -754,12 +754,9 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> // get pointers to the input and output InputImagePointer inputPtr = const_cast< TInputImage *>( this->GetInput() ); - + // Request the entire input image - InputImageRegionType inputRegion; - inputRegion = inputPtr->GetLargestPossibleRegion(); - inputPtr->SetLargestPossibleRegion(inputRegion); - inputPtr->SetRequestedRegion(inputRegion); + inputPtr->SetRequestedRegionToLargestPossibleRegion(); return; } @@ -854,6 +851,7 @@ ResampleImageFilter<TInputImage,TOutputImage,TInterpolatorPrecisionType> outputPtr->SetOrigin( m_OutputOrigin ); outputPtr->SetDirection( m_OutputDirection ); } + return; } diff --git a/Utilities/ITK/Code/Review/itkPadLabelMapFilter.h b/Utilities/ITK/Code/Review/itkPadLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..efef9fe7c94f10024e622119c26f67c5fd7a0729 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkPadLabelMapFilter.h @@ -0,0 +1,126 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkPadLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-07-23 22:27:53 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + Portions of this code are covered under the VTK copyright. + See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkPadLabelMapFilter_h +#define __itkPadLabelMapFilter_h + +#include "itkChangeRegionLabelMapFilter.h" + +namespace itk +{ + +/** \class PadLabelMapFilter + * \brief Pad a LabelMap image + * + * This filter pads a label map. + * + * The SetPadSize() method can be used to set the pad size of the lower and + * the upper boundaries in a single call. + * By default, the filter doesn't pad anything. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * \sa CropLabelMapFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template <class TInputImage> +class ITK_EXPORT PadLabelMapFilter : public ChangeRegionLabelMapFilter<TInputImage> +{ +public: + /** Standard class typedefs. */ + typedef PadLabelMapFilter Self; + typedef ChangeRegionLabelMapFilter<TInputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(PadLabelMapFilter, ChangeRegionImageFilter); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Superclass typedefs. */ + typedef typename Superclass::OutputImageType OutputImageType; + typedef typename Superclass::OutputImagePointer OutputImagePointer; + typedef typename Superclass::OutputImageRegionType OutputImageRegionType; + typedef typename Superclass::OutputImagePixelType OutputImagePixelType; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename InputImageType::LabelObjectType LabelObjectType; + + typedef typename InputImageType::PixelType PixelType; + typedef typename InputImageType::IndexType IndexType; + typedef typename InputImageType::SizeType SizeType; + typedef typename InputImageType::RegionType RegionType; + + typedef TInputImage TOutputImage; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, TOutputImage::ImageDimension); + itkStaticConstMacro(ImageDimension, unsigned int, TOutputImage::ImageDimension); + + /** Set/Get the cropping sizes for the upper and lower boundaries. */ + itkSetMacro(UpperBoundaryPadSize, SizeType); + itkGetMacro(UpperBoundaryPadSize, SizeType); + itkSetMacro(LowerBoundaryPadSize, SizeType); + itkGetMacro(LowerBoundaryPadSize, SizeType); + + void SetPadSize( const SizeType & size ) + { + this->SetUpperBoundaryPadSize( size ); + this->SetLowerBoundaryPadSize( size ); + } + +protected: + PadLabelMapFilter() + { + m_UpperBoundaryPadSize.Fill(0); + m_LowerBoundaryPadSize.Fill(0); + } + ~PadLabelMapFilter() {}; + + virtual void GenerateOutputInformation(); + + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + PadLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + SizeType m_UpperBoundaryPadSize; + SizeType m_LowerBoundaryPadSize; +}; + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkPadLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkPadLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkPadLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..1979852ae409d67a58e97a275005757d44238e36 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkPadLabelMapFilter.txx @@ -0,0 +1,74 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkPadLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-07-23 22:27:53 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + Portions of this code are covered under the VTK copyright. + See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkPadLabelMapFilter_txx +#define __itkPadLabelMapFilter_txx +#include "itkPadLabelMapFilter.h" + +namespace itk +{ + +template <class TInputImage> +void +PadLabelMapFilter<TInputImage> +::GenerateOutputInformation() +{ + const TInputImage * inputPtr = this->GetInput(); + if( !inputPtr ) + { + return; + } + + // Compute the new region size. + RegionType croppedRegion; + SizeType size; + IndexType index; + + SizeType inputSize = inputPtr->GetLargestPossibleRegion().GetSize(); + IndexType inputIndex = inputPtr->GetLargestPossibleRegion().GetIndex(); + + SizeType originalPadSize = m_UpperBoundaryPadSize + m_LowerBoundaryPadSize; + + index = inputIndex - m_LowerBoundaryPadSize; + size = inputSize + ( originalPadSize ); + + croppedRegion.SetSize(size); + croppedRegion.SetIndex(index); + + // Set extraction region in the superclass. + this->SetRegion(croppedRegion); + + Superclass::GenerateOutputInformation(); +} + + +template <class TInputImage> +void +PadLabelMapFilter<TInputImage> +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "UpperBoundaryPadSize: " << m_UpperBoundaryPadSize << std::endl; + os << indent << "LowerBoundaryPadSize: " << m_LowerBoundaryPadSize << std::endl; +} + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkQuadEdge.h b/Utilities/ITK/Code/Review/itkQuadEdge.h index c56604c72349d0f2b75c0c00d336d233259b573d..98be784971526c432dc4f4aecd121212757728ad 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdge.h +++ b/Utilities/ITK/Code/Review/itkQuadEdge.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdge.h,v $ Language: C++ - Date: $Date: 2009-05-13 21:52:25 $ - Version: $Revision: 1.19 $ + Date: $Date: 2009-09-08 20:00:56 $ + Version: $Revision: 1.20 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -208,14 +208,14 @@ namespace itk /** \class QuadEdge * \brief Base class for the implementation of a quad-edge data structure as - * proposed in \ref DoxyReferencesGuibasStolfi "Guibas and Stolfi 1985" + * proposed in "Guibas and Stolfi 1985" * * \author Alexandre Gouaillard, Leonardo Florez-Valencia, Eric Boix * * This implementation was contributed as a paper to the Insight Journal * http://insight-journal.org/midas/handle.php?handle=1926/306 * - * \sa \ref DoxyWalkingLocalShort "Accessing adjacent edges." + * \sa "Accessing adjacent edges." * * \ingroup MeshObjects */ @@ -253,7 +253,7 @@ public: inline void SetRot( Self* rot ) { this->m_Rot = rot; } /** Sub-algebra Get methods. - * Returns edge with same Origin (see \ref DoxyWalkingLocalShort + * Returns edge with same Origin (see * "Accessing adjacent edges"). */ inline Self* GetOnext() {return this->m_Onext;} inline Self* GetRot() {return this->m_Rot;} @@ -273,11 +273,12 @@ public: * \warning This class only handles of the connectivity and is not aware * of the geometry that lies at the \ref GeometricalQuadEdge level. * It is strongly discouraged to use this method. Instead you should - * use \ref itkQE::Mesh::Splice it's geometry aware version. + * use itk::QuadEdgeMesh::Splice it's geometry aware version. * - * \sa \ref DoxySurgeryConnectivity */ - inline void Splice( Self* b ) +// TODO fix this ref +// * \sa \ref DoxySurgeryConnectivity + inline void Splice( Self* b ) { Self * aNext = this->GetOnext(); Self * bNext = b->GetOnext(); @@ -296,7 +297,7 @@ public: // Second order accessors. /** Returns the symetric edge - * (see \ref DoxyWalkingLocalShort "Accessing adjacent edges"). */ + * (see "Accessing adjacent edges"). */ inline Self* GetSym() { if(this->m_Rot) @@ -315,42 +316,42 @@ public: } /** Returns next edge with same Left face - * (see \ref DoxyWalkingLocalShort "Accessing adjacent edges"). */ + * (see "Accessing adjacent edges"). */ Self* GetLnext(); const Self* GetLnext() const; /** Returns next edge with same Right face. The first edge * encountered when moving counter-clockwise from e around e->Right. - * (see \ref DoxyWalkingLocalShort "Accessing adjacent edges"). */ + * (see "Accessing adjacent edges"). */ Self* GetRnext(); const Self* GetRnext() const; /** Returns next edge with same right face and same Destination. The * first edge encountered when moving counter-clockwise from e - * (see \ref DoxyWalkingLocalShort "Accessing adjacent edges"). */ + * (see "Accessing adjacent edges"). */ Self* GetDnext(); const Self* GetDnext() const; /** Returns previous edge with same Origin - * (see \ref DoxyWalkingLocalShort "Accessing adjacent edges"). */ + * (see "Accessing adjacent edges"). */ Self* GetOprev(); const Self* GetOprev() const; /** Returns previous edge with same Left face. The first edge * encountered when moving clockwise from e around e->Left. - * (see \ref DoxyWalkingLocalShort "Accessing adjacent edges"). */ + * (see "Accessing adjacent edges"). */ Self* GetLprev(); const Self* GetLprev() const; /** Returns the previous edge with same Right face. The first edge * encountered when moving clockwise from e around e->Right. - * (see \ref DoxyWalkingLocalShort "Accessing adjacent edges"). */ + * (see "Accessing adjacent edges"). */ Self* GetRprev(); const Self* GetRprev() const; /** Returns the previous edge with same Right face and same Destination. * The first edge encountered when moving clockwise from e around e->Dest. - * (see \ref DoxyWalkingLocalShort "Accessing adjacent edges"). */ + * (see "Accessing adjacent edges"). */ Self* GetDprev(); const Self* GetDprev() const; diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeCellTraitsInfo.h b/Utilities/ITK/Code/Review/itkQuadEdgeCellTraitsInfo.h index 29726ea8f574b35226bb7052a5557b7a07acb9ec..2e34faaa4951230a1102c6625512337bd2f4f9ec 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeCellTraitsInfo.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeCellTraitsInfo.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeCellTraitsInfo.h,v $ Language: C++ - Date: $Date: 2008-02-07 15:58:06 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-07-31 14:23:01 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -18,6 +18,11 @@ #ifndef __itkQuadEdgeCellTraitsInfo_h #define __itkQuadEdgeCellTraitsInfo_h +#include "itkQuadEdgeMeshPoint.h" +#include "itkMapContainer.h" +#include <set> +#include "itkGeometricalQuadEdge.h" + namespace itk { /** \class QuadEdgeMeshCellTraitsInfo @@ -29,11 +34,16 @@ namespace itk * http://insight-journal.org/midas/handle.php?handle=1926/306 * */ -template< int VPointDimension, typename TCoordRep, - typename TInterpolationWeight, typename TPointIdentifier, - typename TCellIdentifier, typename TCellFeatureIdentifier, - typename TPoint, typename TPointsContainer, - typename TUsingCellsContainer, typename TQE > +template< int VPointDimension, + typename TCoordRep=float, + typename TInterpolationWeight=float, + typename TPointIdentifier=unsigned long, + typename TCellIdentifier=unsigned long, + typename TCellFeatureIdentifier=unsigned char, + typename TPoint=QuadEdgeMeshPoint< TCoordRep, VPointDimension >, + typename TPointsContainer=MapContainer< unsigned long, TPoint >, + typename TUsingCellsContainer=std::set< TPointIdentifier >, + typename TQE=GeometricalQuadEdge< unsigned long, unsigned long, bool, bool, true > > class QuadEdgeMeshCellTraitsInfo { public: diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMesh.h b/Utilities/ITK/Code/Review/itkQuadEdgeMesh.h index a3e8e065e07f16ff2c150b6b32826e8384c3ebbb..63258065480bfad5df223d8e90d8127bb5caf8fc 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMesh.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMesh.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMesh.h,v $ Language: C++ - Date: $Date: 2009-04-08 23:10:20 $ - Version: $Revision: 1.34 $ + Date: $Date: 2009-09-08 20:00:56 $ + Version: $Revision: 1.38 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -32,7 +32,7 @@ #include "itkQuadEdgeMeshFrontIterator.h" #include "itkConceptChecking.h" -/** +/**** * \brief Documentation of itkQE namespace * \todo More comments here ! * @@ -244,9 +244,10 @@ public: itkNewMacro( Self ); itkTypeMacro( QuadEdgeMesh, Mesh ); +#if !defined(CABLE_CONFIGURATION) /** FrontIterator definitions */ itkQEDefineFrontIteratorMethodsMacro( Self ); - +#endif public: @@ -261,9 +262,9 @@ public: /** another way of deleting all the cells */ virtual void Clear(); - CellsContainerPointer GetEdgeCells() {return m_EdgeCellsContainer;} - const CellsContainerPointer GetEdgeCells() const {return m_EdgeCellsContainer;} - void SetEdgeCells(CellsContainerPointer edgeCells) + CellsContainer * GetEdgeCells() {return m_EdgeCellsContainer;} + const CellsContainer * GetEdgeCells() const {return m_EdgeCellsContainer;} + void SetEdgeCells(CellsContainer * edgeCells) {m_EdgeCellsContainer = edgeCells;} void SetEdgeCell(CellIdentifier cellId, CellAutoPointer & cellPointer ) {m_EdgeCellsContainer->InsertElement(cellId,cellPointer.ReleaseOwnership());} @@ -284,6 +285,7 @@ public: /** overloaded method for backward compatibility */ void BuildCellLinks() { } +#if !defined(CABLE_CONFIGURATION) /** overloaded method for backward compatibility */ void SetBoundaryAssignments(int dimension, BoundaryAssignmentsContainer* container) @@ -306,6 +308,7 @@ public: (void)dimension; return( (const BoundaryAssignmentsContainerPointer)0 ); } +#endif /** overloaded method for backward compatibility */ void SetBoundaryAssignment(int dimension, CellIdentifier cellId, diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMesh.txx b/Utilities/ITK/Code/Review/itkQuadEdgeMesh.txx index 609e37af9c090c47dab8ea62927c729e580db65d..5db5098901e9887fa4acaabc47146f7ae3bcf902 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMesh.txx +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMesh.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMesh.txx,v $ Language: C++ - Date: $Date: 2009-04-08 23:10:22 $ - Version: $Revision: 1.54 $ + Date: $Date: 2009-07-13 22:57:53 $ + Version: $Revision: 1.55 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -1050,7 +1050,8 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > { if( this->GetEdgeCells()->size() == 0 ) return( (QEPrimal*)0 ); - CellsContainerIterator cit = this->GetEdgeCells()->Begin(); + const CellsContainer * edgeCells = this->GetEdgeCells(); + CellsContainerConstIterator cit = edgeCells->Begin(); EdgeCellType* e = dynamic_cast< EdgeCellType* >( cit.Value( ) ); return( e->GetQEGeom( ) ); } diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshFrontIterator.h b/Utilities/ITK/Code/Review/itkQuadEdgeMeshFrontIterator.h index 339df9224d64f005516603a439fdf6575fc50cdd..757dd07cfbec2ac4c20c2653a44e73ee5c83f6a6 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshFrontIterator.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshFrontIterator.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshFrontIterator.h,v $ Language: C++ - Date: $Date: 2009-02-10 05:07:49 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-08-05 20:26:37 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -107,7 +107,7 @@ protected: { } virtual ~FrontAtom( ) { } FrontAtom& operator=( const FrontAtom& r ) - { m_Edge = r.m_Edge; m_Cost = r.m_Cost; } + { m_Edge = r.m_Edge; m_Cost = r.m_Cost; return *this; } bool operator==( const FrontAtom& r ) const { return( m_Edge == r.m_Edge ); } bool operator!=( const FrontAtom& r ) const @@ -175,6 +175,8 @@ public: Self & operator++( ); Self & operator++( int ) { return( this->operator++( ) ); } + + MeshType* GetMesh() const { return this->m_Mesh; } protected: /** Find a default seed by taking any edge (with proper type) in diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshLineCell.h b/Utilities/ITK/Code/Review/itkQuadEdgeMeshLineCell.h index da9a6ec325cbf9f07c3dbd890642059da2ee12fd..dd6f1563d651fc6b2cdf59cecd5a7bf8b99ed2f1 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshLineCell.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshLineCell.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshLineCell.h,v $ Language: C++ - Date: $Date: 2008-10-03 21:23:51 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-07-30 21:17:33 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -107,9 +107,6 @@ public: CellIdentifier GetIdent(); - /** Implement the standard CellInterface. */ - SelfAutoPointer New(); - /** TCellInterface abstract methods definition. */ virtual void Accept( unsigned long cellId, MultiVisitor* mv ); virtual CellGeometry GetType() const; diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshLineCell.txx b/Utilities/ITK/Code/Review/itkQuadEdgeMeshLineCell.txx index fc077b6da5d223614619bfde4437a8012f4c4126..cbe16dceef3093b2f843d10d97d32f39ecc7bb20 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshLineCell.txx +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshLineCell.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshLineCell.txx,v $ Language: C++ - Date: $Date: 2007-10-08 21:38:18 $ - Version: $Revision: 1.16 $ + Date: $Date: 2009-07-30 21:17:33 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -98,17 +98,6 @@ QuadEdgeMeshLineCell< TCellInterface > } } -// --------------------------------------------------------------------- -template< class TCellInterface > -typename QuadEdgeMeshLineCell< TCellInterface >::SelfAutoPointer -QuadEdgeMeshLineCell< TCellInterface > -::New() -{ - SelfAutoPointer ptr( new Self ); - ptr.TakeOwnership(); - return( ptr ); -} - // --------------------------------------------------------------------- template< class TCellInterface > void diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshPoint.h b/Utilities/ITK/Code/Review/itkQuadEdgeMeshPoint.h index 7f02f114c86d6984e08093443dcea66607f8e00c..6ca6c5f48235a82579dd895579c8a1038c791c72 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshPoint.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshPoint.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshPoint.h,v $ Language: C++ - Date: $Date: 2008-07-19 14:49:01 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-09-08 20:00:56 $ + Version: $Revision: 1.12 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -19,6 +19,7 @@ #include "itkPoint.h" #include "itkConceptChecking.h" +#include "itkGeometricalQuadEdge.h" namespace itk { @@ -28,7 +29,7 @@ namespace itk * \brief Wrapper around a itk::Point in order to add a reference * to an entry in the edge ring. */ -template< class TCoordRep, unsigned int VPointDimension, typename TQuadEdge > +template< class TCoordRep, unsigned int VPointDimension, typename TQuadEdge=GeometricalQuadEdge< unsigned long, unsigned long, bool, bool, true > > class QuadEdgeMeshPoint : public Point< TCoordRep, VPointDimension > { public: @@ -52,8 +53,6 @@ public: #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ - itkConceptMacro(DimensionShouldBe3, - (Concept::SameDimension<itkGetStaticConstMacro(PointDimension),3>)); /** End concept checking */ #endif @@ -71,10 +70,10 @@ public: Self & operator=( const ValueType r[VPointDimension] ); - /** Accessor on \ref m_Edge */ + /** Accessor on m_Edge */ void SetEdge( TQuadEdge * inputEdge ); - /** Accessor on \ref m_Edge */ + /** Accessor on m_Edge */ TQuadEdge * GetEdge(); TQuadEdge * GetEdge() const; diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshScalarDataVTKPolyDataWriter.h b/Utilities/ITK/Code/Review/itkQuadEdgeMeshScalarDataVTKPolyDataWriter.h index 2d9a4ccdcf70d462c33ba94b20fc67983bafc5b5..286c807b80978cc21df47a9f555fe54d81e64dd4 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshScalarDataVTKPolyDataWriter.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshScalarDataVTKPolyDataWriter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshScalarDataVTKPolyDataWriter.h,v $ Language: C++ - Date: $Date: 2009-01-02 18:43:05 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-06-21 16:25:08 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -58,11 +58,17 @@ public: typedef typename MeshType::PointDataContainerConstPointer PointDataContainerConstPointer; typedef typename MeshType::PointDataContainerIterator PointDataContainerIterator; - typedef typename MeshType::CellsContainerPointer CellsContainerPointer; - typedef typename MeshType::CellsContainerIterator CellsContainerIterator; - - typedef typename MeshType::CellDataContainerPointer CellDataContainerPointer; - typedef typename MeshType::CellDataContainerIterator CellDataContainerIterator; + typedef typename MeshType::CellsContainer CellsContainer; + typedef typename CellsContainer::Pointer CellsContainerPointer; + typedef typename CellsContainer::ConstPointer CellsContainerConstPointer; + typedef typename CellsContainer::Iterator CellsContainerIterator; + typedef typename CellsContainer::ConstIterator CellsContainerConstIterator; + + typedef typename MeshType::CellDataContainer CellDataContainer; + typedef typename CellDataContainer::Iterator CellDataContainerIterator; + typedef typename CellDataContainer::ConstIterator CellDataContainerConstIterator; + typedef typename CellDataContainer::Pointer CellDataContainerPointer; + typedef typename CellDataContainer::ConstPointer CellDataContainerConstPointer; /** Set/Get the name of the CellDataName where data are written. */ itkSetStringMacro(CellDataName); diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshScalarDataVTKPolyDataWriter.txx b/Utilities/ITK/Code/Review/itkQuadEdgeMeshScalarDataVTKPolyDataWriter.txx index 66aa2dd9632368e8f5dce2135f7d66f89b3a86a2..18fe121e2e269242b9b9771720623ae118bcad8e 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshScalarDataVTKPolyDataWriter.txx +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshScalarDataVTKPolyDataWriter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshScalarDataVTKPolyDataWriter.txx,v $ Language: C++ - Date: $Date: 2009-01-02 18:43:05 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-06-21 16:25:08 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -58,7 +58,7 @@ void QuadEdgeMeshScalarDataVTKPolyDataWriter<TMesh> ::WriteCellData() { - CellDataContainerPointer celldata = this->m_Input->GetCellData(); + CellDataContainerConstPointer celldata = this->m_Input->GetCellData(); if( celldata ) { @@ -82,12 +82,12 @@ QuadEdgeMeshScalarDataVTKPolyDataWriter<TMesh> unsigned long k(0); - CellsContainerPointer cells = this->m_Input->GetCells(); - CellsContainerIterator it = cells->Begin(); + CellsContainerConstPointer cells = this->m_Input->GetCells(); + CellsContainerConstIterator it = cells->Begin(); - for( CellDataContainerIterator c_it = celldata->Begin(); - c_it != celldata->End(); - ++c_it, ++it ) + CellDataContainerConstIterator c_it = celldata->Begin(); + + while( c_it != celldata->End() ) { CellType* cellPointer = it.Value(); if( cellPointer->GetType() != 1 ) @@ -98,6 +98,9 @@ QuadEdgeMeshScalarDataVTKPolyDataWriter<TMesh> outputFile <<std::endl; } } + + ++c_it; + ++it; } outputFile <<std::endl; outputFile.close(); diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshToQuadEdgeMeshFilter.h b/Utilities/ITK/Code/Review/itkQuadEdgeMeshToQuadEdgeMeshFilter.h index 6dd3f02c3d600d113b39beb412a8d9bc9142102d..f739943f77af767f64b07b4e29a79faca1698807 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshToQuadEdgeMeshFilter.h +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshToQuadEdgeMeshFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshToQuadEdgeMeshFilter.h,v $ Language: C++ - Date: $Date: 2009-04-22 01:41:45 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-07-13 23:02:40 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -52,10 +52,19 @@ public: typedef typename InputMeshType::QEPrimal InputQEPrimal; typedef typename InputMeshType::VectorType InputVectorType; + typedef typename InputMeshType::PointDataContainer InputPointDataContainer; + typedef typename InputMeshType::CellDataContainer InputCellDataContainer; + + typedef typename InputPointDataContainer::ConstPointer + InputPointDataContainerConstPointer; typedef typename InputMeshType::PointsContainerConstIterator - InputPointsContainerConstIterator; + InputPointsContainerConstIterator; + typedef typename InputMeshType::PointsContainerConstPointer + InputPointsContainerConstPointer; typedef typename InputMeshType::CellsContainerConstIterator - InputCellsContainerConstIterator; + InputCellsContainerConstIterator; + typedef typename InputMeshType::CellsContainerConstPointer + InputCellsContainerConstPointer; typedef typename InputMeshType::EdgeCellType InputEdgeCellType; typedef typename InputMeshType::PolygonCellType InputPolygonCellType; @@ -78,16 +87,30 @@ public: typedef typename OutputQEPrimal::IteratorGeom OutputQEIterator; typedef typename OutputMeshType::PointsContainerIterator OutputPointsContainerIterator; + typedef typename OutputMeshType::PointsContainerPointer + OutputPointsContainerPointer; + typedef typename OutputMeshType::PointsContainerConstPointer + OutputPointsContainerConstPointer; + + typedef typename OutputMeshType::PointDataContainer OutputPointDataContainer; + typedef typename OutputMeshType::CellDataContainer OutputCellDataContainer; public: itkNewMacro( Self ); itkTypeMacro( QuadEdgeMeshToQuadEdgeMeshFilter, MeshToMeshFilter ); protected: - QuadEdgeMeshToQuadEdgeMeshFilter( ); - virtual ~QuadEdgeMeshToQuadEdgeMeshFilter( ) { } - - virtual void CopyInputMeshToOutputMesh( ); + QuadEdgeMeshToQuadEdgeMeshFilter(); + virtual ~QuadEdgeMeshToQuadEdgeMeshFilter() { } + + virtual void CopyInputMeshToOutputMesh(); + virtual void CopyInputMeshToOutputMeshGeometry(); + virtual void CopyInputMeshToOutputMeshPoints(); + virtual void CopyInputMeshToOutputMeshCells(); + virtual void CopyInputMeshToOutputMeshEdgeCells(); + virtual void CopyInputMeshToOutputMeshFieldData(); + virtual void CopyInputMeshToOutputMeshPointData(); + virtual void CopyInputMeshToOutputMeshCellData(); private: QuadEdgeMeshToQuadEdgeMeshFilter( const Self& ); // Not impl. diff --git a/Utilities/ITK/Code/Review/itkQuadEdgeMeshToQuadEdgeMeshFilter.txx b/Utilities/ITK/Code/Review/itkQuadEdgeMeshToQuadEdgeMeshFilter.txx index 641016d0661bceefd1f3ed05b720c60209aba358..173c6b09942b4a69166f07696cdebc4e9e13dcfd 100644 --- a/Utilities/ITK/Code/Review/itkQuadEdgeMeshToQuadEdgeMeshFilter.txx +++ b/Utilities/ITK/Code/Review/itkQuadEdgeMeshToQuadEdgeMeshFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkQuadEdgeMeshToQuadEdgeMeshFilter.txx,v $ Language: C++ - Date: $Date: 2009-04-22 01:41:45 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-07-13 23:02:46 $ + Version: $Revision: 1.17 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -39,55 +39,192 @@ void QuadEdgeMeshToQuadEdgeMeshFilter< TInputMesh, TOutputMesh > ::CopyInputMeshToOutputMesh() { + this->CopyInputMeshToOutputMeshGeometry(); + this->CopyInputMeshToOutputMeshFieldData(); +} + +// --------------------------------------------------------------------- +template< class TInputMesh, class TOutputMesh > +void +QuadEdgeMeshToQuadEdgeMeshFilter< TInputMesh, TOutputMesh > +::CopyInputMeshToOutputMeshGeometry() +{ + this->CopyInputMeshToOutputMeshPoints(); + this->CopyInputMeshToOutputMeshEdgeCells(); + this->CopyInputMeshToOutputMeshCells(); +} + +// --------------------------------------------------------------------- +template< class TInputMesh, class TOutputMesh > +void +QuadEdgeMeshToQuadEdgeMeshFilter< TInputMesh, TOutputMesh > +::CopyInputMeshToOutputMeshFieldData() +{ + this->CopyInputMeshToOutputMeshPointData(); + this->CopyInputMeshToOutputMeshCellData(); +} + +// --------------------------------------------------------------------- +template< class TInputMesh, class TOutputMesh > +void +QuadEdgeMeshToQuadEdgeMeshFilter< TInputMesh, TOutputMesh > +::CopyInputMeshToOutputMeshPoints() +{ + InputMeshConstPointer in = this->GetInput(); OutputMeshPointer out = this->GetOutput(); // Copy points - InputPointsContainerConstIterator inIt = in->GetPoints()->Begin(); - while( inIt != in->GetPoints()->End() ) + InputPointsContainerConstPointer inPoints = in->GetPoints(); + + if( inPoints ) { - OutputPointType pOut; - pOut.CastFrom( inIt.Value() ); - out->SetPoint( inIt.Index(), pOut ); - inIt++; - } + InputPointsContainerConstIterator inIt = inPoints->Begin(); + while( inIt != inPoints->End() ) + { + OutputPointType pOut; + pOut.CastFrom( inIt.Value() ); + out->SetPoint( inIt.Index(), pOut ); + inIt++; + } + } +} + +// --------------------------------------------------------------------- +template< class TInputMesh, class TOutputMesh > +void +QuadEdgeMeshToQuadEdgeMeshFilter< TInputMesh, TOutputMesh > +::CopyInputMeshToOutputMeshEdgeCells() +{ + InputMeshConstPointer in = this->GetInput(); + OutputMeshPointer out = this->GetOutput(); // Copy Edge Cells - InputCellsContainerConstIterator ecIt = in->GetEdgeCells()->Begin(); - while( ecIt != in->GetEdgeCells()->End() ) + InputCellsContainerConstPointer inEdgeCells = in->GetEdgeCells(); + + if( inEdgeCells ) { - InputEdgeCellType* pe = - dynamic_cast< InputEdgeCellType* >( ecIt.Value()); - //if( pe ) + InputCellsContainerConstIterator ecIt = inEdgeCells->Begin(); + while( ecIt != inEdgeCells->End() ) { - out->AddEdgeWithSecurePointList( pe->GetQEGeom()->GetOrigin(), - pe->GetQEGeom()->GetDestination() ); + InputEdgeCellType* pe = dynamic_cast< InputEdgeCellType* >( ecIt.Value()); + if( pe ) + { + out->AddEdgeWithSecurePointList( pe->GetQEGeom()->GetOrigin(), + pe->GetQEGeom()->GetDestination() ); + } + ecIt++; } - ecIt++; } +} +// --------------------------------------------------------------------- +template< class TInputMesh, class TOutputMesh > +void +QuadEdgeMeshToQuadEdgeMeshFilter< TInputMesh, TOutputMesh > +::CopyInputMeshToOutputMeshCells() +{ + InputMeshConstPointer in = this->GetInput(); + OutputMeshPointer out = this->GetOutput(); + // Copy cells - InputCellsContainerConstIterator cIt = in->GetCells()->Begin(); - while( cIt != in->GetCells()->End() ) + InputCellsContainerConstPointer inCells = in->GetCells(); + + if( inCells ) { - InputPolygonCellType* pe = - dynamic_cast< InputPolygonCellType* >( cIt.Value()); - //if( pe ) + InputCellsContainerConstIterator cIt = inCells->Begin(); + while( cIt != inCells->End() ) { - InputPointIdList points; - InputPointsIdInternalIterator pit = pe->InternalPointIdsBegin(); - while( pit != pe->InternalPointIdsEnd( ) ) + InputPolygonCellType * pe = dynamic_cast< InputPolygonCellType* >( cIt.Value()); + if( pe ) { - points.push_back( ( *pit ) ); - ++pit; + InputPointIdList points; + InputPointsIdInternalIterator pit = pe->InternalPointIdsBegin(); + while( pit != pe->InternalPointIdsEnd( ) ) + { + points.push_back( ( *pit ) ); + ++pit; + } + out->AddFaceWithSecurePointList( points, false ); } - out->AddFaceWithSecurePointList( points, false ); + cIt++; } - cIt++; } } +// --------------------------------------------------------------------- +template< class TInputMesh, class TOutputMesh > +void +QuadEdgeMeshToQuadEdgeMeshFilter< TInputMesh, TOutputMesh > +::CopyInputMeshToOutputMeshPointData() +{ + + InputMeshConstPointer in = this->GetInput(); + OutputMeshPointer out = this->GetOutput(); + + typedef typename OutputPointDataContainer::Pointer OutputPointDataContainerPointer; + + InputPointDataContainerConstPointer inputPointData = in->GetPointData(); + + if( inputPointData.IsNull() ) + { + // There is nothing to copy + itkWarningMacro("Input mesh point data is NULL"); + return; + } + + OutputPointDataContainerPointer outputPointData = OutputPointDataContainer::New(); + outputPointData->Reserve( inputPointData->Size() ); + + // Copy point data + typedef typename InputPointDataContainer::ConstIterator InputPointDataContainerConstIterator; + InputPointDataContainerConstIterator inIt = inputPointData->Begin(); + while( inIt != inputPointData->End() ) + { + outputPointData->SetElement( inIt.Index(), inIt.Value() ); + inIt++; + } + + out->SetPointData( outputPointData ); +} + + +// --------------------------------------------------------------------- +template< class TInputMesh, class TOutputMesh > +void +QuadEdgeMeshToQuadEdgeMeshFilter< TInputMesh, TOutputMesh > +::CopyInputMeshToOutputMeshCellData() +{ + + InputMeshConstPointer in = this->GetInput(); + OutputMeshPointer out = this->GetOutput(); + + typedef typename InputCellDataContainer::ConstPointer InputCellDataContainerConstPointer; + typedef typename OutputCellDataContainer::Pointer OutputCellDataContainerPointer; + + InputCellDataContainerConstPointer inputCellData = in->GetCellData(); + + if( inputCellData.IsNull() ) + { + // There is nothing to copy + return; + } + + OutputCellDataContainerPointer outputCellData = OutputCellDataContainer::New(); + outputCellData->Reserve( inputCellData->Size() ); + + // Copy point data + typedef typename InputCellDataContainer::ConstIterator InputCellDataContainerConstIterator; + InputCellDataContainerConstIterator inIt = inputCellData->Begin(); + while( inIt != inputCellData->End() ) + { + outputCellData->SetElement( inIt.Index(), inIt.Value() ); + inIt++; + } + + out->SetCellData( outputCellData ); +} } // end namespace itk #endif diff --git a/Utilities/ITK/Code/Review/itkRankImageFilter.h b/Utilities/ITK/Code/Review/itkRankImageFilter.h index a1f1c073cae295855f2e65f567a793308e18e9a2..8dab713a1839d5fd591b24d5d79bc855d679ff61 100644 --- a/Utilities/ITK/Code/Review/itkRankImageFilter.h +++ b/Utilities/ITK/Code/Review/itkRankImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRankImageFilter.h,v $ Language: C++ - Date: $Date: 2009-04-23 03:43:42 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-06-03 12:48:05 $ + Version: $Revision: 1.5 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -111,7 +111,7 @@ protected: void PrintSelf(std::ostream& os, Indent indent) const; - bool useVectorBasedHistogram() + bool UseVectorBasedHistogram() { // bool, short and char are acceptable for vector based algorithm: they do not require // too much memory. Other types are not usable with that algorithm diff --git a/Utilities/ITK/Code/Review/itkRankImageFilter.txx b/Utilities/ITK/Code/Review/itkRankImageFilter.txx index fd03949c99e92994397fb54f05f43dfd260c77fb..3949b44e0f832739cbd11917811772dcb4ca4678 100644 --- a/Utilities/ITK/Code/Review/itkRankImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkRankImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRankImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-08-07 13:36:49 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-06-03 12:48:05 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -48,7 +48,7 @@ RankImageFilter<TInputImage, TOutputImage, TKernel> ::NewHistogram() { HistogramType * hist; - if (useVectorBasedHistogram()) + if (UseVectorBasedHistogram()) { hist = new VHistogram(); } diff --git a/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunction.h b/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunction.h index 281f6dc35531fbe37265bebadef6e69b3c83897f..5f8b67cbc981337c665580375e911e60a23abcc6 100644 --- a/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunction.h +++ b/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRegionBasedLevelSetFunction.h,v $ Language: C++ - Date: $Date: 2009-05-13 15:27:45 $ - Version: $Revision: 1.11 $ + Date: $Date: 2009-08-06 01:46:47 $ + Version: $Revision: 1.18 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -57,7 +57,8 @@ namespace itk { * http://www.insight-journal.org/browse/publication/323 * http://hdl.handle.net/1926/1533 * - * + * NOTE: The convention followed is + * inside of the level-set function is negative and outside is positive. */ template < class TInput, // LevelSetImageType class TFeature, // FeatureImageType @@ -100,25 +101,26 @@ public: ScalarValueType null_value = NumericTraits<ScalarValueType>::Zero; m_MaxCurvatureChange = null_value; + m_MaxAdvectionChange = null_value; m_MaxGlobalChange = null_value; } ~GlobalDataStruct() {} -// ScalarValueType m_MaxAdvectionChange; // not used -// ScalarValueType m_MaxPropagationChange; // not used - ScalarValueType m_MaxCurvatureChange; - vnl_matrix_fixed<ScalarValueType, itkGetStaticConstMacro(ImageDimension), itkGetStaticConstMacro(ImageDimension)> m_dxy; ScalarValueType m_dx[itkGetStaticConstMacro(ImageDimension)]; - ScalarValueType m_dx_forward[itkGetStaticConstMacro(ImageDimension)]; - ScalarValueType m_dx_backward[itkGetStaticConstMacro(ImageDimension)]; + ScalarValueType m_dx_forward[ itkGetStaticConstMacro( ImageDimension ) ]; + ScalarValueType m_dx_backward[ itkGetStaticConstMacro( ImageDimension ) ]; ScalarValueType m_GradMagSqr; + ScalarValueType m_GradMag; + + ScalarValueType m_MaxCurvatureChange; + ScalarValueType m_MaxAdvectionChange; ScalarValueType m_MaxGlobalChange; }; @@ -138,6 +140,7 @@ public: typedef typename FeatureImageType::ConstPointer FeatureImageConstPointer; typedef typename FeatureImageType::PixelType FeaturePixelType; typedef typename FeatureImageType::IndexType FeatureIndexType; + typedef typename FeatureImageType::SpacingType FeatureSpacingType; typedef typename FeatureImageType::OffsetType FeatureOffsetType; typedef TSharedData SharedDataType; @@ -196,7 +199,20 @@ public: virtual const FeatureImageType *GetFeatureImage() const { return m_FeatureImage.GetPointer(); } virtual void SetFeatureImage(const FeatureImageType *f) - { m_FeatureImage = f; } + { + m_FeatureImage = f; + + FeatureSpacingType spacing = m_FeatureImage->GetSpacing(); + for(unsigned int i = 0; i < ImageDimension; i++) + { + this->m_InvSpacing[i] = 1/spacing[i]; + } + } + + /** Advection field. Default implementation returns a vector of zeros. */ + virtual VectorType AdvectionField(const NeighborhoodType &, + const FloatOffsetType &, GlobalDataStruct * = 0) const + { return this->m_ZeroVectorConstant; } /** Nu. Area regularization values */ void SetAreaWeight( const ScalarValueType& nu) @@ -228,11 +244,16 @@ public: ScalarValueType GetCurvatureWeight() const { return m_CurvatureWeight; } + void SetAdvectionWeight( const ScalarValueType& iA) + { this->m_AdvectionWeight = iA; } + ScalarValueType GetAdvectionWeight() const + { return this->m_AdvectionWeight; } + /** Weight of the laplacian smoothing term */ - void SetLaplacianSmoothingWeight(const ScalarValueType c) - { m_LaplacianSmoothingWeight = c; } - ScalarValueType GetLaplacianSmoothingWeight() const - { return m_LaplacianSmoothingWeight; } + void SetReinitializationSmoothingWeight(const ScalarValueType c) + { m_ReinitializationSmoothingWeight = c; } + ScalarValueType GetReinitializationSmoothingWeight() const + { return m_ReinitializationSmoothingWeight; } /** Volume matching weight. */ void SetVolumeMatchingWeight( const ScalarValueType& tau ) @@ -253,7 +274,7 @@ public: virtual void ReleaseGlobalDataPointer(void *GlobalData) const { delete (GlobalDataStruct *) GlobalData; } - virtual ScalarValueType ComputeCurvatureTerm(const NeighborhoodType &, + virtual ScalarValueType ComputeCurvature(const NeighborhoodType &, const FloatOffsetType &, GlobalDataStruct *gd ); /** \brief Laplacian smoothing speed can be used to spatially modify the @@ -270,6 +291,12 @@ public: ) const { return NumericTraits<ScalarValueType>::One; } + /** This method must be defined in a subclass to implement a working function + * object. This method is called before the solver begins its work to + * produce the speed image used as the level set function's Advection field + * term. See LevelSetFunction for more information. */ + virtual void CalculateAdvectionImage() {} + protected: RegionBasedLevelSetFunction(); @@ -305,14 +332,17 @@ protected: /** Curvature Regularization Weight */ ScalarValueType m_CurvatureWeight; + ScalarValueType m_AdvectionWeight; + /** Laplacian Regularization Weight */ - ScalarValueType m_LaplacianSmoothingWeight; + ScalarValueType m_ReinitializationSmoothingWeight; unsigned int m_FunctionId; std::slice x_slice[itkGetStaticConstMacro(ImageDimension)]; ::size_t m_Center; ::size_t m_xStride[itkGetStaticConstMacro(ImageDimension)]; + double m_InvSpacing[itkGetStaticConstMacro(ImageDimension)]; static double m_WaveDT; static double m_DT; @@ -363,8 +393,6 @@ protected: YEAR = "2005", PAGES = "I: 430-436"} \endverbatim */ - ScalarValueType ComputeLaplacianTerm( const NeighborhoodType &, - const FloatOffsetType &, GlobalDataStruct *gd ); /** \brief Compute the laplacian \return \f$ \Delta \phi \f$ */ @@ -378,9 +406,18 @@ protected: virtual void ComputeParameters() = 0; /** \brief Update and save the inner and outer parameters in the shared data - data structure. */ + structure. */ virtual void UpdateSharedDataParameters() = 0; + bool m_UpdateC; + + /** This method's only purpose is to initialize the zero vector + * constant. */ + static VectorType InitializeZeroVectorConstant(); + + /** Zero vector constant. */ + static VectorType m_ZeroVectorConstant; + private: RegionBasedLevelSetFunction(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunction.txx b/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunction.txx index d58e7c67a28a08000392dac33027ca7143942542..0c731104445878f6269904c1c78e013e17fc59d9 100644 --- a/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunction.txx +++ b/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRegionBasedLevelSetFunction.txx,v $ Language: C++ - Date: $Date: 2009-05-21 22:03:29 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-08-06 16:09:56 $ + Version: $Revision: 1.28 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -51,8 +51,8 @@ RegionBasedLevelSetFunction< TInput, m_OverlapPenaltyWeight = NumericTraits<ScalarValueType>::Zero; m_AreaWeight = NumericTraits<ScalarValueType>::Zero; m_VolumeMatchingWeight = NumericTraits<ScalarValueType>::Zero; - m_LaplacianSmoothingWeight = NumericTraits<ScalarValueType>::Zero; - m_CurvatureWeight = NumericTraits<ScalarValueType>::Zero; + m_ReinitializationSmoothingWeight = NumericTraits<ScalarValueType>::Zero; + m_CurvatureWeight = m_AdvectionWeight = NumericTraits<ScalarValueType>::Zero; m_Volume = NumericTraits<ScalarValueType>::Zero; m_FunctionId = 0; @@ -60,8 +60,34 @@ RegionBasedLevelSetFunction< TInput, m_SharedData = 0; m_InitialImage = 0; m_FeatureImage = 0; + m_UpdateC = false; + + for(unsigned int i = 0; i < ImageDimension; i++) + { + m_InvSpacing[i] = 1; + } } +template < class TInput, class TFeature, class TSharedData > +typename RegionBasedLevelSetFunction< TInput, TFeature, TSharedData >::VectorType +RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > +::InitializeZeroVectorConstant() +{ + VectorType ans; + for (unsigned int i = 0; i < ImageDimension; ++i) + { + ans[i] = NumericTraits<ScalarValueType>::Zero; + } + + return ans; +} + +template < class TInput, class TFeature, class TSharedData > +typename RegionBasedLevelSetFunction< TInput, TFeature, TSharedData >::VectorType +RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > +::m_ZeroVectorConstant = +RegionBasedLevelSetFunction< TInput, TFeature, TSharedData >::InitializeZeroVectorConstant(); + /* Computes the Heaviside function and stores it in m_HeavisideFunctionOfLevelSetImage */ template < class TInput, class TFeature, @@ -85,6 +111,7 @@ void RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > while( !constIt.IsAtEnd() ) { + // Convention is inside of level-set function is negative ScalarValueType hVal = m_DomainFunction->Evaluate( - constIt.Get() ); It.Set( hVal ); ++It; @@ -103,12 +130,19 @@ RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > { // Must update all H before updating C this->ComputeHImage(); + this->m_UpdateC = false; } else { - this->ComputeParameters(); + if ( !this->m_UpdateC ) + { + this->ComputeParameters(); + this->m_UpdateC = true; + } this->UpdateSharedDataParameters(); } + + return; } template < class TInput, @@ -126,9 +160,9 @@ RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > if (vnl_math_abs(d->m_MaxCurvatureChange) > vnl_math::eps) { - if (d->m_MaxGlobalChange > vnl_math::eps) + if (d->m_MaxAdvectionChange > vnl_math::eps) { - dt = vnl_math_min( ( this->m_WaveDT / d->m_MaxGlobalChange ), + dt = vnl_math_min( (m_WaveDT / d->m_MaxAdvectionChange), ( this->m_DT / d->m_MaxCurvatureChange ) ); } else @@ -138,16 +172,17 @@ RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > } else { - if (d->m_MaxGlobalChange > vnl_math::eps) + if (d->m_MaxAdvectionChange > vnl_math::eps) { //NOTE: What's the difference between this->m_WaveDT and this->m_DT? - dt = this->m_WaveDT / d->m_MaxGlobalChange; + dt = this->m_WaveDT / d->m_MaxAdvectionChange; } } // Reset the values d->m_MaxCurvatureChange = NumericTraits<ScalarValueType>::Zero; d->m_MaxGlobalChange = NumericTraits<ScalarValueType>::Zero; + d->m_MaxAdvectionChange = NumericTraits<ScalarValueType>::Zero; return dt; } @@ -159,12 +194,12 @@ typename RegionBasedLevelSetFunction< TInput, ScalarValueType RegionBasedLevelSetFunction< TInput, TFeature, TSharedData >:: -ComputeCurvatureTerm( - const NeighborhoodType &itkNotUsed(neighborhood), +ComputeCurvature( + const NeighborhoodType &itkNotUsed(it), const FloatOffsetType &itkNotUsed(offset), GlobalDataStruct *gd) { // Calculate the mean curvature - ScalarValueType curvature_term = NumericTraits<ScalarValueType>::Zero; + ScalarValueType curvature = NumericTraits<ScalarValueType>::Zero; unsigned int i, j; @@ -174,20 +209,22 @@ ComputeCurvatureTerm( { if(j != i) { - curvature_term -= gd->m_dx[i] * gd->m_dx[j] * gd->m_dxy[i][j]; - curvature_term += gd->m_dxy[j][j] * gd->m_dx[i] * gd->m_dx[i]; + curvature -= gd->m_dx[i] * gd->m_dx[j] * gd->m_dxy[i][j]; + curvature += gd->m_dxy[j][j] * gd->m_dx[i] * gd->m_dx[i]; } } } - if( gd->m_GradMagSqr > vnl_math::eps ) + if( gd->m_GradMag > vnl_math::eps ) { - return (curvature_term / gd->m_GradMagSqr ); + curvature /= gd->m_GradMag * gd->m_GradMag * gd->m_GradMag; } else { - return 0.; + curvature /= 1 + gd->m_GradMagSqr; } + + return curvature; } // Compute the Hessian matrix and various other derivatives. Some of these @@ -202,6 +239,7 @@ RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > const ScalarValueType inputValue = it.GetCenterPixel(); gd->m_GradMagSqr = 0.; + gd->m_GradMag = 0.; unsigned int i, j; for (i = 0; i < ImageDimension; i++) @@ -211,13 +249,18 @@ RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > const unsigned int positionB = static_cast< unsigned int >( this->m_Center - this->m_xStride[i] ); - gd->m_dx[i] = 0.5 * ( it.GetPixel( positionA ) - it.GetPixel( positionB ) ); - gd->m_dxy[i][i] = - it.GetPixel( positionA ) + it.GetPixel( positionB ) - 2.0 * inputValue; - gd->m_dx_forward[i] = it.GetPixel( positionA ) - inputValue; - gd->m_dx_backward[i] = inputValue - it.GetPixel( positionB ); + gd->m_dx[i] = 0.5 * ( this->m_InvSpacing[i] ) * + ( it.GetPixel( positionA ) - it.GetPixel( positionB ) ); + gd->m_dx_forward[i] = ( this->m_InvSpacing[i] ) * + ( it.GetPixel( positionA ) - inputValue ); + gd->m_dx_backward[i] = ( this->m_InvSpacing[i] ) * + ( inputValue - it.GetPixel( positionB ) ); + gd->m_GradMagSqr += gd->m_dx[i] * gd->m_dx[i]; + gd->m_dxy[i][i] = ( this->m_InvSpacing[i] ) * + ( gd->m_dx_forward[i] - gd->m_dx_backward[i] ); + for (j = i+1; j < ImageDimension; j++ ) { const unsigned int positionAa = static_cast<unsigned int>( @@ -229,13 +272,13 @@ RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > const unsigned int positionDa = static_cast<unsigned int>( this->m_Center + this->m_xStride[i] + this->m_xStride[j] ); - gd->m_dxy[i][j] = gd->m_dxy[j][i] = 0.25 *( - it.GetPixel( positionAa ) - - it.GetPixel( positionBa ) - - it.GetPixel( positionCa ) + - it.GetPixel( positionDa ) ); + gd->m_dxy[i][j] = gd->m_dxy[j][i] = 0.25 * + ( this->m_InvSpacing[i] ) * ( this->m_InvSpacing[j] ) * + ( it.GetPixel( positionAa ) - it.GetPixel( positionBa ) + + it.GetPixel( positionDa ) - it.GetPixel( positionCa ) ); } } + gd->m_GradMag = vcl_sqrt( gd->m_GradMagSqr ); } template < class TInput, @@ -249,10 +292,12 @@ RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > // Access the neighborhood center pixel of phi const ScalarValueType inputValue = it.GetCenterPixel(); - ScalarValueType laplacian_term = 0.; - ScalarValueType curvature_term = 0.; - ScalarValueType curvature = 0.; - ScalarValueType globalTerm = 0.; + ScalarValueType laplacian_term = NumericTraits<ScalarValueType>::Zero; + ScalarValueType curvature_term = NumericTraits<ScalarValueType>::Zero; + ScalarValueType curvature = NumericTraits<ScalarValueType>::Zero; + ScalarValueType globalTerm = NumericTraits<ScalarValueType>::Zero; + VectorType advection_field; + ScalarValueType x_energy, advection_term = NumericTraits<ScalarValueType>::Zero; // Access the global data structure GlobalDataStruct *gd = (GlobalDataStruct *)globalData; @@ -266,14 +311,9 @@ RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > if ( ( dh != 0. ) && ( this->m_CurvatureWeight != NumericTraits< ScalarValueType >::Zero ) ) { - //NOTE: Why the curvature_term is multiplied by gd->m_GradMagSqr? - //NOTE: in ComputeCurvatureTerm the result has been divided by gd->m_GradMagSqr... - //NOTE: According to the definition of the mean curavture it must not be, so - // I commented this product - curvature = this->ComputeCurvatureTerm( it, offset, gd ); - curvature_term *= this->m_CurvatureWeight * //gd->m_GradMagSqr * - this->CurvatureSpeed(it, offset) * - dh; + curvature = this->ComputeCurvature( it, offset, gd ); + curvature_term = this->m_CurvatureWeight * curvature * + this->CurvatureSpeed(it,offset, gd) * dh; gd->m_MaxCurvatureChange = vnl_math_max( gd->m_MaxCurvatureChange, vnl_math_abs( curvature_term ) ); @@ -281,25 +321,37 @@ RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > // Computing the laplacian term // Used in maintaining squared distance function - if( this->m_LaplacianSmoothingWeight != NumericTraits<ScalarValueType>::Zero) + if( this->m_ReinitializationSmoothingWeight != NumericTraits<ScalarValueType>::Zero ) { - if( this->m_CurvatureWeight != NumericTraits< ScalarValueType >::Zero ) - { - laplacian_term = this->ComputeLaplacian( gd ) - curvature; - } - else - { - laplacian_term = this->ComputeLaplacianTerm( it, offset, gd ); - } - // Use the laplacian to maintain signed distance function + laplacian_term = this->ComputeLaplacian( gd ) - curvature; - laplacian_term *= this->m_LaplacianSmoothingWeight * + laplacian_term *= this->m_ReinitializationSmoothingWeight * this->LaplacianSmoothingSpeed(it,offset, gd); } - // Update value from curvature length and laplacian term - PixelType updateVal = - static_cast< PixelType >( curvature_term + laplacian_term ); + if ( ( dh != 0. ) && ( m_AdvectionWeight != NumericTraits<ScalarValueType>::Zero ) ) + { + advection_field = this->AdvectionField(it, offset, gd); + + for( unsigned int i = 0; i < ImageDimension; i++ ) + { + x_energy = m_AdvectionWeight * advection_field[i]; + + // TODO: Is this condition right ? + if (x_energy > NumericTraits<ScalarValueType>::Zero ) + { + advection_term += advection_field[i] * gd->m_dx_backward[i]; + } + else + { + advection_term += advection_field[i] * gd->m_dx_forward[i]; + } + + gd->m_MaxAdvectionChange + = vnl_math_max(gd->m_MaxAdvectionChange, vnl_math_abs(x_energy)); + } + advection_term *= m_AdvectionWeight*dh; + } /* Compute the globalTerm - rms difference of image with c_0 or c_1*/ if ( dh != 0. ) @@ -310,7 +362,8 @@ RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > /* Final update value is the local terms of curvature lengths and laplacian squared distances - global terms of rms differences of image and piecewise constant regions*/ - updateVal = updateVal - globalTerm; + PixelType updateVal = + static_cast< PixelType >( curvature_term + laplacian_term + globalTerm + advection_term ); /* If MaxGlobalChange recorded is lower than the current globalTerm */ if( vnl_math_abs( gd->m_MaxGlobalChange) < vnl_math_abs( globalTerm ) ) @@ -321,19 +374,6 @@ RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > return updateVal; } -template < class TInput, class TFeature, class TSharedData > -typename RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > -::ScalarValueType -RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > -::ComputeLaplacianTerm( const NeighborhoodType &neighborhood, - const FloatOffsetType &offset, GlobalDataStruct *gd ) -{ - ScalarValueType laplacian = ComputeLaplacian( gd ); - ScalarValueType curvature = ComputeCurvatureTerm( neighborhood, offset, gd ); - - return laplacian - curvature; -} - template < class TInput, class TFeature, class TSharedData > typename RegionBasedLevelSetFunction< TInput, TFeature, TSharedData > @@ -400,9 +440,7 @@ const InputIndexType& inputIndex ) ScalarValueType regularizationTerm = this->m_VolumeMatchingWeight * ComputeVolumeRegularizationTerm() - this->m_AreaWeight; - //NOTE: regularizationTerm here MUST take into account the curvature term!!! - - ScalarValueType globalTerm = - inTerm + outTerm - overlapTerm - regularizationTerm; + ScalarValueType globalTerm = + inTerm - outTerm + overlapTerm + regularizationTerm; return globalTerm; } diff --git a/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionData.h b/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionData.h index 0ff3b651d12364495cac39d26d313b747a46398c..dae673f22d4f36df1b3f08228e8b678b10d45c26 100644 --- a/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionData.h +++ b/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionData.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRegionBasedLevelSetFunctionData.h,v $ Language: C++ - Date: $Date: 2009-05-14 21:46:48 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-06-08 04:36:32 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -104,8 +104,12 @@ public: typedef typename FeatureImageType::IndexType FeatureIndexType; typedef typename FeatureImageType::PointType FeaturePointType; + // Allocates m_HeavisideFunctionOfLevelSetImage to have same origin, + // spacing and size as image. Also sets the m_Start and m_End indices. void CreateHeavisideFunctionOfLevelSetImage( const InputImageType * image ); + // Checks if the given index lies in the domain of the current + // level-set function. The domain is defined by the start and end indices. template< class TIndex > bool VerifyInsideRegion( const TIndex& featureIndex ) { @@ -120,8 +124,10 @@ public: return true; } + // Get the index into the domain of the current level-set function InputIndexType GetIndex( const FeatureIndexType& featureIndex ); + // Get the index in the domain of the feature image FeatureIndexType GetFeatureIndex( const InputIndexType& inputIndex ); diff --git a/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionData.txx b/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionData.txx index a2146d645d5f273f4ff67c86359b8d692f9e873f..12b98a47425683e832f3bafdf69d54fed2d41965 100644 --- a/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionData.txx +++ b/Utilities/ITK/Code/Review/itkRegionBasedLevelSetFunctionData.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkRegionBasedLevelSetFunctionData.txx,v $ Language: C++ - Date: $Date: 2009-05-14 21:46:48 $ - Version: $Revision: 1.1 $ + Date: $Date: 2009-06-05 14:58:45 $ + Version: $Revision: 1.2 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -38,6 +38,7 @@ RegionBasedLevelSetFunctionData< TInputImage, TFeatureImage > ::CreateHeavisideFunctionOfLevelSetImage( const InputImageType * image ) { const InputRegionType region = image->GetLargestPossibleRegion(); + this->m_HeavisideFunctionOfLevelSetImage = InputImageType::New(); this->m_HeavisideFunctionOfLevelSetImage->CopyInformation( image ); this->m_HeavisideFunctionOfLevelSetImage->SetRegions( region ); @@ -45,13 +46,11 @@ RegionBasedLevelSetFunctionData< TInputImage, TFeatureImage > this->m_HeavisideFunctionOfLevelSetImage->FillBuffer( 0 ); const InputPointType origin = image->GetOrigin(); - const InputSpacingType spacing = image->GetSpacing(); + + this->m_HeavisideFunctionOfLevelSetImage->TransformPhysicalPointToIndex( origin, this->m_Start ); for( unsigned int i = 0; i < ImageDimension; i++ ) { - // FIXME : This computation of Start index is suspicious. - // See similar computation in the Shrink image filter. - this->m_Start[i] = static_cast< InputIndexValueType >( origin[i] / spacing[i] ); this->m_End[i] = this->m_Start[i] + static_cast< InputIndexValueType >( region.GetSize()[i] ) - 1; } } diff --git a/Utilities/ITK/Code/Review/itkRegionFromReferenceLabelMapFilter.h b/Utilities/ITK/Code/Review/itkRegionFromReferenceLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..1d3e4391c1572146b78829fe31a9d8384dc8bb1d --- /dev/null +++ b/Utilities/ITK/Code/Review/itkRegionFromReferenceLabelMapFilter.h @@ -0,0 +1,131 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkRegionFromReferenceLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-07-24 11:58:45 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + Portions of this code are covered under the VTK copyright. + See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkRegionFromReferenceLabelMapFilter_h +#define __itkRegionFromReferenceLabelMapFilter_h + +#include "itkChangeRegionLabelMapFilter.h" + +namespace itk +{ + +/** \class RegionFromReferenceLabelMapFilter + * \brief Set the region from a reference image + * + * Change the region of a label map to be the same as one of a reference image. + * This filter implements the same feature as its superclass, but with the input region + * well integrated in the pipeline architecture. + * If the output cannot contain some of the objects' lines, they are truncated or removed. + * All objects fully outside the output region are removed. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template <class TInputImage> +class ITK_EXPORT RegionFromReferenceLabelMapFilter : public ChangeRegionLabelMapFilter<TInputImage> +{ +public: + /** Standard class typedefs. */ + typedef RegionFromReferenceLabelMapFilter Self; + typedef ChangeRegionLabelMapFilter<TInputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + + /** Run-time type information (and related methods). */ + itkTypeMacro(RegionFromReferenceLabelMapFilter, ChangeRegionImageFilter); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Superclass typedefs. */ + typedef typename Superclass::OutputImageType OutputImageType; + typedef typename Superclass::OutputImagePointer OutputImagePointer; + typedef typename Superclass::OutputImageRegionType OutputImageRegionType; + typedef typename Superclass::OutputImagePixelType OutputImagePixelType; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename InputImageType::LabelObjectType LabelObjectType; + + typedef typename InputImageType::PixelType PixelType; + typedef typename InputImageType::IndexType IndexType; + typedef typename InputImageType::SizeType SizeType; + typedef typename InputImageType::RegionType RegionType; + + typedef TInputImage TOutputImage; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, TOutputImage::ImageDimension); + itkStaticConstMacro(ImageDimension, unsigned int, TOutputImage::ImageDimension); + + typedef ImageBase< itkGetStaticConstMacro( ImageDimension ) > ReferenceImageType; + + /** Copy the output information from another Image. */ + void SetReferenceImage ( const ReferenceImageType *image ); + + const ReferenceImageType * GetReferenceImage() const; + + /** Set the input image */ + void SetInput1(const TInputImage *input) + { + this->SetInput( input ); + } + + /** Set the reference image */ + void SetInput2(const ReferenceImageType *input) + { + this->SetReferenceImage( input ); + } + + +protected: + RegionFromReferenceLabelMapFilter() + { + this->SetNumberOfRequiredInputs(2); + } + ~RegionFromReferenceLabelMapFilter() {}; + + virtual void GenerateOutputInformation(); + + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + RegionFromReferenceLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkRegionFromReferenceLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkRegionFromReferenceLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkRegionFromReferenceLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..97ec94e40c2e3c00fe78c20f55a1a8b790e67240 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkRegionFromReferenceLabelMapFilter.txx @@ -0,0 +1,76 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkRegionFromReferenceLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-07-23 22:27:53 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + Portions of this code are covered under the VTK copyright. + See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkRegionFromReferenceLabelMapFilter_txx +#define __itkRegionFromReferenceLabelMapFilter_txx +#include "itkRegionFromReferenceLabelMapFilter.h" + +namespace itk +{ + +template <class TInputImage> +void +RegionFromReferenceLabelMapFilter<TInputImage> +::GenerateOutputInformation() +{ + Superclass::GenerateOutputInformation(); + + this->SetRegion( this->GetReferenceImage()->GetLargestPossibleRegion() ); + this->GetOutput()->SetLargestPossibleRegion( this->GetRegion() ); +} + + +template <class TInputImage> +void +RegionFromReferenceLabelMapFilter<TInputImage> +::SetReferenceImage ( const ReferenceImageType *image ) +{ + itkDebugMacro("setting input ReferenceImage to " << image); + if( image != static_cast<const ReferenceImageType *>(this->GetInput( 1 )) ) + { + this->ProcessObject::SetNthInput(1, const_cast< ReferenceImageType *>( image ) ); + this->Modified(); + } +} + +template <class TInputImage> +const typename RegionFromReferenceLabelMapFilter<TInputImage>::ReferenceImageType * +RegionFromReferenceLabelMapFilter<TInputImage> +::GetReferenceImage() const +{ + Self * surrogate = const_cast< Self * >( this ); + + const DataObject * input = surrogate->ProcessObject::GetInput(1); + + const ReferenceImageType * referenceImage = static_cast<const ReferenceImageType *>( input ); + + return referenceImage; +} + +template <class TInputImage> +void +RegionFromReferenceLabelMapFilter<TInputImage> +::PrintSelf(std::ostream& os, Indent indent) const +{ + this->Superclass::PrintSelf(os, indent); +} + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkRelabelLabelMapFilter.h b/Utilities/ITK/Code/Review/itkRelabelLabelMapFilter.h new file mode 100755 index 0000000000000000000000000000000000000000..4bd382eafe5d8b5547c5da484aef05f61584db04 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkRelabelLabelMapFilter.h @@ -0,0 +1,103 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkRelabelLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-07-25 14:51:18 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkRelabelLabelMapFilter_h +#define __itkRelabelLabelMapFilter_h + +#include "itkInPlaceLabelMapFilter.h" + +namespace itk +{ + +/** \class RelabelLabelMapFilter + * \brief This filter relabels the LabelObjects; the new labels are arranged + * consecutively with consideration for the background value. + * + * This filter takes the LabelObjects from the input and reassigns them to the + * output by calling the PushLabelObject method, which by default, attempts to + * reorganize the labels consecutively. The user can assign an arbitrary value + * to the background; the filter will assign the labels consecutively by + * skipping the background value. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * \sa ShapeLabelObject, RelabelComponentImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TImage > +class ITK_EXPORT RelabelLabelMapFilter : + public InPlaceLabelMapFilter<TImage> +{ +public: + /** Standard class typedefs. */ + typedef RelabelLabelMapFilter Self; + typedef InPlaceLabelMapFilter<TImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TImage ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::LabelObjectType LabelObjectType; + typedef typename Superclass::LabelObjectContainerType LabelObjectContainerType; + + /** ImageDimension constants */ + itkStaticConstMacro(ImageDimension, unsigned int, TImage::ImageDimension); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(RelabelLabelMapFilter, InPlaceLabelMapFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ +/* itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>));*/ + /** End concept checking */ +#endif + +protected: + RelabelLabelMapFilter() {}; + ~RelabelLabelMapFilter() {}; + + void PrintSelf(std::ostream& os, Indent indent) const; + + void GenerateData(); + +private: + RelabelLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkRelabelLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkRelabelLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkRelabelLabelMapFilter.txx new file mode 100755 index 0000000000000000000000000000000000000000..4e6de150a0905aab0a423e38f213082a20e84a36 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkRelabelLabelMapFilter.txx @@ -0,0 +1,65 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkRelabelLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-07-25 14:51:18 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkRelabelLabelMapFilter_txx +#define __itkRelabelLabelMapFilter_txx + +#include "itkRelabelLabelMapFilter.h" +#include "itkProgressReporter.h" + + +namespace itk { + +template <class TImage> +void +RelabelLabelMapFilter<TImage> +::GenerateData() +{ + // Allocate the output + this->AllocateOutputs(); + + ImageType * output = this->GetOutput(); + + // get the label objects + LabelObjectContainerType labelObjects = output->GetLabelObjectContainer(); + + ProgressReporter progress( this, 0, labelObjects.size() ); + + // and put back the objects in the map + output->ClearLabels(); + typename LabelObjectContainerType::iterator it = labelObjects.begin(); + while( it != labelObjects.end() ) + { + output->PushLabelObject( it->second ); + + // go to the next label + progress.CompletedPixel(); + it++; + } +} + + +template <class TImage> +void +RelabelLabelMapFilter<TImage> +::PrintSelf(std::ostream& os, Indent indent) const +{ + this->Superclass::PrintSelf(os, indent); +} + + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkScalarChanAndVeseDenseLevelSetImageFilter.h b/Utilities/ITK/Code/Review/itkScalarChanAndVeseDenseLevelSetImageFilter.h index bee35018fb37e42b90fde8cb27344ff2a47125c9..507fe5a3270c35ea68aec041d874eff1df0cf642 100644 --- a/Utilities/ITK/Code/Review/itkScalarChanAndVeseDenseLevelSetImageFilter.h +++ b/Utilities/ITK/Code/Review/itkScalarChanAndVeseDenseLevelSetImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarChanAndVeseDenseLevelSetImageFilter.h,v $ Language: C++ - Date: $Date: 2009-05-16 12:35:10 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-07-29 15:14:09 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -58,13 +58,14 @@ namespace itk template < class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, class TSharedData > class ITK_EXPORT ScalarChanAndVeseDenseLevelSetImageFilter: - public MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction > + public MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, TOutputImage, + TFunction > { public: typedef ScalarChanAndVeseDenseLevelSetImageFilter Self; - typedef MultiphaseDenseFiniteDifferenceImageFilter< - TInputImage, TOutputImage, TFunction > Superclass; + typedef MultiphaseDenseFiniteDifferenceImageFilter< TInputImage, + TFeatureImage, TOutputImage, TFunction > Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; @@ -78,6 +79,12 @@ public: itkStaticConstMacro( ImageDimension, unsigned int, TInputImage::ImageDimension ); /** Inherited typedef from the superclass. */ + typedef typename Superclass::InputImageType InputImageType; + typedef typename Superclass::InputImagePointer InputImagePointer; + typedef typename Superclass::InputPointType InputPointType; + typedef typename Superclass::ValueType ValueType; + typedef typename InputImageType::SpacingType InputSpacingType; + typedef TFeatureImage FeatureImageType; typedef typename FeatureImageType::Pointer FeatureImagePointer; typedef typename FeatureImageType::PixelType FeaturePixelType; @@ -86,19 +93,13 @@ public: typedef typename FeatureImageType::RegionType FeatureRegionType; /** Output image type typedefs */ - typedef typename Superclass::InputImageType InputImageType; - typedef typename Superclass::InputImagePointer InputImagePointer; - typedef typename Superclass::InputPointType InputPointType; - typedef typename Superclass::InputSpacingType InputSpacingType; - typedef TOutputImage OutputImageType; - typedef typename OutputImageType::ValueType ValueType; typedef typename OutputImageType::IndexType IndexType; typedef typename OutputImageType::PixelType OutputPixelType; typedef typename Superclass::TimeStepType TimeStepType; - - typedef typename Superclass::FiniteDifferenceFunctionType FiniteDifferenceFunctionType; + typedef typename Superclass::FiniteDifferenceFunctionType + FiniteDifferenceFunctionType; typedef TFunction FunctionType; typedef typename FunctionType::Pointer FunctionPointer; @@ -110,7 +111,6 @@ public: FeatureImageType, FeatureImageType > ROIFilterType; typedef typename ROIFilterType::Pointer ROIFilterPointer; - #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro(OutputHasNumericTraitsCheck, @@ -120,14 +120,9 @@ public: /** Set/Get the feature image to be used for speed function of the level set * equation. Equivalent to calling Set/GetInput(1, ..) */ - virtual void SetFeatureImage(const FeatureImageType *f) - { - this->ProcessObject::SetNthInput( 0, const_cast< FeatureImageType * >(f) ); - } - - virtual const FeatureImageType * GetFeatureImage() const + virtual void SetFeatureImage( const FeatureImagePointer f ) { - return (static_cast<const FeatureImageType *>(this->ProcessObject::GetInput(0))); + this->SetInput( f ); } protected: diff --git a/Utilities/ITK/Code/Review/itkScalarChanAndVeseDenseLevelSetImageFilter.txx b/Utilities/ITK/Code/Review/itkScalarChanAndVeseDenseLevelSetImageFilter.txx index 10efbe1028ca35a921ae7dc7be288bac455b6d5a..5990a4434dc8a26c4391cabf6835c44f45c6e2e0 100644 --- a/Utilities/ITK/Code/Review/itkScalarChanAndVeseDenseLevelSetImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkScalarChanAndVeseDenseLevelSetImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarChanAndVeseDenseLevelSetImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-05-20 22:03:45 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-08-06 01:46:47 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,33 +22,22 @@ namespace itk { -template < class TInput, - class TFeature, - class TFunction, - class TOutputPixel, +template < class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, class TSharedData > void -ScalarChanAndVeseDenseLevelSetImageFilter< TInput, TFeature, - TFunction, TOutputPixel, TSharedData >:: +ScalarChanAndVeseDenseLevelSetImageFilter< TInputImage, TFeatureImage, TOutputImage, +TFunction, TSharedData >:: Initialize() { // Set the feature image for the individual level-set functions - for( unsigned int i = 0; i < this->m_FunctionCount; i++) + for( unsigned int fId = 0; fId < this->m_FunctionCount; ++fId ) { - InputImagePointer input = this->m_LevelSet[i]; + InputImagePointer input = this->m_LevelSet[fId]; InputPointType origin = input->GetOrigin(); - InputSpacingType spacing = input->GetSpacing(); // In the context of the global coordinates FeatureIndexType start; - - // FIXME: This is suspicious code. It looks like we should - // have used first IndexToPhysicalPoint and then PhysicalPointToIndex - // as it was done in the ShrinkImagefilter... - for ( unsigned int j = 0; j < ImageDimension; j++ ) - { - start[j] = static_cast<FeatureIndexValueType>( origin[j]/spacing[j] ); - } + this->GetInput()->TransformPhysicalPointToIndex( origin, start ); // Defining roi region FeatureRegionType region; @@ -57,14 +46,14 @@ Initialize() // Initialize the ROI filter with the feature image ROIFilterPointer roi = ROIFilterType::New(); - roi->SetInput( this->GetFeatureImage() ); + roi->SetInput( this->GetInput() ); roi->SetRegionOfInterest( region ); roi->Update(); // Assign roi output FeatureImagePointer feature = roi->GetOutput(); - this->m_DifferenceFunctions[i]->SetFeatureImage( feature ); - this->m_DifferenceFunctions[i]->SetInitialImage( input ); + this->m_DifferenceFunctions[fId]->SetFeatureImage( feature ); + this->m_DifferenceFunctions[fId]->CalculateAdvectionImage(); } // Initialize the function count in shared data @@ -76,57 +65,46 @@ Initialize() this->m_SharedData->SetKdTree( this->m_KdTree ); } - for ( unsigned int i = 0; i < this->m_FunctionCount; i++ ) + for ( unsigned int fId = 0; fId < this->m_FunctionCount; ++fId ) { - this->m_DifferenceFunctions[i]->SetFunctionId( i ); + this->m_DifferenceFunctions[fId]->SetFunctionId( fId ); - this->m_SharedData->CreateHeavisideFunctionOfLevelSetImage ( i, this->m_LevelSet[i] ); + this->m_SharedData->CreateHeavisideFunctionOfLevelSetImage ( fId, this->m_LevelSet[fId] ); // Share the this->m_SharedData structure - this->m_DifferenceFunctions[i]->SetSharedData( this->m_SharedData ); + this->m_DifferenceFunctions[fId]->SetSharedData( this->m_SharedData ); } - this->m_SharedData->AllocateListImage( this->GetFeatureImage() ); + this->m_SharedData->AllocateListImage( this->GetInput() ); this->m_SharedData->PopulateListImage(); this->Superclass::Initialize(); - - for (unsigned int i = 0; i < this->m_FunctionCount; i++) - { - this->m_DifferenceFunctions[i]->UpdateSharedData(true); - } - - for ( unsigned int i = 0; i < this->m_FunctionCount; i++ ) - { - this->m_DifferenceFunctions[i]->UpdateSharedData( false ); - } } /** Overrides parent implementation */ // This function is called at the end of each iteration -template < class TInput, - class TFeature, - class TFunction, - class TOutputPixel, +template < class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, class TSharedData > void -ScalarChanAndVeseDenseLevelSetImageFilter< TInput, TFeature, TFunction, TOutputPixel, TSharedData > +ScalarChanAndVeseDenseLevelSetImageFilter< TInputImage, TFeatureImage, TOutputImage, +TFunction, TSharedData > ::InitializeIteration() { this->Superclass::InitializeIteration(); - for( unsigned int i = 0; i < this->m_FunctionCount; i++ ) + for( unsigned int fId = 0; fId < this->m_FunctionCount; ++fId ) { - this->m_DifferenceFunctions[i]->SetInitialImage( this->m_LevelSet[i] ); - this->m_DifferenceFunctions[i]->UpdateSharedData ( true ); + this->m_DifferenceFunctions[fId]->SetInitialImage( this->m_LevelSet[fId] ); + this->m_DifferenceFunctions[fId]->UpdateSharedData ( true ); } - for( unsigned int i = 0; i < this->m_FunctionCount; i++ ) + for( unsigned int fId = 0; fId < this->m_FunctionCount; ++fId ) { - this->m_DifferenceFunctions[i]->UpdateSharedData ( false ); + this->m_DifferenceFunctions[fId]->UpdateSharedData ( false ); } + } } /* end namespace itk */ diff --git a/Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunction.h b/Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunction.h index a612a1e9cbd87c98bf5c6b7d751d2ebf013aef75..eb944fb8be16543422ae51aa3ad1772b964613e1 100644 --- a/Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunction.h +++ b/Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarChanAndVeseLevelSetFunction.h,v $ Language: C++ - Date: $Date: 2009-05-14 21:46:50 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-06-12 09:44:02 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -29,13 +29,18 @@ namespace itk { * This class implements a level set function that computes the speed image by * integrating values on the image domain. * - * Based on the paper: + * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * + * Based on the papers: * * "An active contour model without edges" * T. Chan and L. Vese. * In Scale-Space Theories in Computer Vision, pages 141–151, 1999. * - * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. + * "Segmenting and Tracking Fluorescent Cells in Dynamic 3-D + * Microscopy With Coupled Active Surfaces" + * Dufour, Shinin, Tajbakhsh, Guillen-Aghion, Olivo-Marin + * In IEEE Transactions on Image Processing, vol. 14, No 9, Sep. 2005 * * This code was taken from the Insight Journal paper: * @@ -131,9 +136,9 @@ protected: const FeatureIndexType& iIdx ); void UpdateSharedDataInsideParameters( const unsigned int& iId, - const bool& iBool, const FeaturePixelType&, const ScalarValueType& ); + const FeaturePixelType& iVal, const ScalarValueType& iChange ); void UpdateSharedDataOutsideParameters( const unsigned int& iId, - const bool& iBool, const FeaturePixelType&, const ScalarValueType& ); + const FeaturePixelType& iVal, const ScalarValueType& iChange ); private: ScalarChanAndVeseLevelSetFunction(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunction.txx b/Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunction.txx index a8ac2d7c9a8c48c2c97d10dd52372853e729ea3e..68c06e463b2ce2ae4cac4325730594eadcf7cff6 100644 --- a/Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunction.txx +++ b/Utilities/ITK/Code/Review/itkScalarChanAndVeseLevelSetFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarChanAndVeseLevelSetFunction.txx,v $ Language: C++ - Date: $Date: 2009-05-22 16:46:18 $ - Version: $Revision: 1.15 $ + Date: $Date: 2009-06-12 09:44:02 $ + Version: $Revision: 1.21 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,6 +22,9 @@ namespace itk { +// Computes the foreground constant and background constant value. For the Dense +// image filter, this is called prior to the start of every iteration. For the +// sparse filter, this is only called one during initialization. template < class TInputImage, class TFeatureImage, class TSharedData > void ScalarChanAndVeseLevelSetFunction< TInputImage, TFeatureImage, TSharedData > @@ -33,7 +36,7 @@ ScalarChanAndVeseLevelSetFunction< TInputImage, TFeatureImage, TSharedData > { this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_ForegroundConstantValues = this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_WeightedSumOfPixelValuesInsideLevelSet / - this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_WeightedNumberOfPixelsOutsideLevelSet; + this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_WeightedNumberOfPixelsInsideLevelSet; } else { @@ -50,42 +53,34 @@ ScalarChanAndVeseLevelSetFunction< TInputImage, TFeatureImage, TSharedData > { this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_BackgroundConstantValues = 0; } + } +// update the foreground constant for pixel updates +// Called only when sparse filters are used to prevent iteration through the +// entire image template < class TInputImage, class TFeatureImage, class TSharedData > void ScalarChanAndVeseLevelSetFunction< TInputImage, TFeatureImage, TSharedData > ::UpdateSharedDataInsideParameters( const unsigned int& iId, - const bool& iA, const FeaturePixelType& iVal, const ScalarValueType& iH ) + const FeaturePixelType& iVal, const ScalarValueType& iChange ) { - if( iA ) - { - this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedNumberOfPixelsInsideLevelSet += iH; - this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedSumOfPixelValuesInsideLevelSet += iVal * iH; - } - else - { - this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedNumberOfPixelsInsideLevelSet -= iH; - this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedSumOfPixelValuesInsideLevelSet -= iVal * iH; - } + // update the foreground constant calculation of the current level-set function + this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedNumberOfPixelsInsideLevelSet += iChange; + this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedSumOfPixelValuesInsideLevelSet += iVal * iChange; } +// update the background constant for pixel updates +// Called only when sparse filters are used to prevent iteration through the +// entire image template < class TInputImage, class TFeatureImage, class TSharedData > void ScalarChanAndVeseLevelSetFunction< TInputImage, TFeatureImage, TSharedData > ::UpdateSharedDataOutsideParameters( const unsigned int& iId, - const bool& iA, const FeaturePixelType& iVal, const ScalarValueType& iH ) + const FeaturePixelType& iVal, const ScalarValueType& iChange ) { - if( iA ) - { - this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedNumberOfPixelsOutsideLevelSet += iH; - this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedSumOfPixelValuesOutsideLevelSet += iVal * iH; - } - else - { - this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedNumberOfPixelsOutsideLevelSet -= iH; - this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedSumOfPixelValuesOutsideLevelSet -= iVal * iH; - } + this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedNumberOfPixelsOutsideLevelSet += iChange; + this->m_SharedData->m_LevelSetDataPointerVector[iId]->m_WeightedSumOfPixelValuesOutsideLevelSet += iVal * iChange; } /* Calculates the numerator and denominator for c_i for each region. As part of @@ -106,12 +101,7 @@ ScalarChanAndVeseLevelSetFunction< TInputImage, TFeatureImage, TSharedData > this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_WeightedSumOfPixelValuesOutsideLevelSet = 0; this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_BackgroundConstantValues = 0; - FeatureImageConstPointer featureImage = this->m_FeatureImage; - - ImageIteratorType It( this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_HeavisideFunctionOfLevelSetImage, - this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_HeavisideFunctionOfLevelSetImage->GetLargestPossibleRegion() ); - ConstFeatureIteratorType fIt( this->m_FeatureImage, - this->m_FeatureImage->GetLargestPossibleRegion() ); + ConstFeatureIteratorType fIt( this->m_FeatureImage, this->m_FeatureImage->GetLargestPossibleRegion() ); FeaturePixelType featureVal; FeatureIndexType globalIndex; @@ -119,29 +109,18 @@ ScalarChanAndVeseLevelSetFunction< TInputImage, TFeatureImage, TSharedData > InputPixelType hVal; ListPixelType L; - // Reference: - // Dufour, Shinin, Tajbakhsh, Guillen-Aghion, Olivo-Marin - // Segmenting and Tracking Fluorescent Cells in Dynamic 3-D - // Microscopy With Coupled Active Surfaces - // IEEE Transactions on Image Processing, vol. 14, No 9, September 2005 - // In the paper: - // m_WeightedSumOfPixelValuesInsideLevelSet = \sum I(x) * H(\phi_i(x)) - // m_WeightedNumberOfPixelsInsideLevelSet = \sum H(\phi_i(x)) - // m_WeightedSumOfPixelValuesOutsideLevelSet = \sum \left( I(x) \prod \left( 1 - H(\phi_i(x))\right) \right) - // m_WeightedNumberOfPixelsInsideLevelSet = \sum \prod \left( 1 - H(\phi_i(x))\right) - - for( It.GoToBegin(), fIt.GoToBegin(); !It.IsAtEnd(); - ++It, ++fIt ) + fIt.GoToBegin(); + + while( !fIt.IsAtEnd() ) { featureVal = fIt.Get(); - inputIndex = It.GetIndex(); + inputIndex = fIt.GetIndex(); InputPixelType prod = 1.; globalIndex = this->m_SharedData->m_LevelSetDataPointerVector[fId]->GetFeatureIndex( inputIndex ); L = this->m_SharedData->m_NearestNeighborListImage->GetPixel( globalIndex ); -// bool inBgrnd = true; // assume the pixel is in background for( ListPixelConstIterator it = L.begin(); it != L.end(); ++it ) { itInputIndex = this->m_SharedData->m_LevelSetDataPointerVector[*it]->GetIndex( globalIndex ); @@ -157,6 +136,8 @@ ScalarChanAndVeseLevelSetFunction< TInputImage, TFeatureImage, TSharedData > this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_WeightedSumOfPixelValuesOutsideLevelSet += featureVal * prod; this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_WeightedNumberOfPixelsOutsideLevelSet += prod; + + ++fIt; } } diff --git a/Utilities/ITK/Code/Review/itkScalarChanAndVeseSparseLevelSetImageFilter.h b/Utilities/ITK/Code/Review/itkScalarChanAndVeseSparseLevelSetImageFilter.h index 9c020e985f495ffb617478547cbe2a6e54e69b60..348ac3f15ecd904e473151d02aa6ffc8ef55403f 100644 --- a/Utilities/ITK/Code/Review/itkScalarChanAndVeseSparseLevelSetImageFilter.h +++ b/Utilities/ITK/Code/Review/itkScalarChanAndVeseSparseLevelSetImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarChanAndVeseSparseLevelSetImageFilter.h,v $ Language: C++ - Date: $Date: 2009-05-16 12:35:12 $ - Version: $Revision: 1.4 $ + Date: $Date: 2009-07-29 15:14:15 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -57,12 +57,13 @@ namespace itk template < class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, class TSharedData, typename TIdCell = unsigned int > class ITK_EXPORT ScalarChanAndVeseSparseLevelSetImageFilter : -public MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TOutputImage, TFunction, TIdCell > +public MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, TFeatureImage, + TOutputImage, TFunction, TIdCell > { public: typedef ScalarChanAndVeseSparseLevelSetImageFilter Self; - typedef MultiphaseSparseFiniteDifferenceImageFilter< - TInputImage, TOutputImage, TFunction, TIdCell > Superclass; + typedef MultiphaseSparseFiniteDifferenceImageFilter< TInputImage, + TFeatureImage, TOutputImage, TFunction, TIdCell > Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; @@ -76,21 +77,21 @@ public: itkStaticConstMacro( ImageDimension, unsigned int, TInputImage::ImageDimension ); /** Inherited typedef from the superclass. */ + typedef typename Superclass::InputImageType InputImageType; + typedef typename Superclass::InputImagePointer InputImagePointer; + typedef typename Superclass::InputPointType InputPointType; + typedef typename Superclass::ValueType ValueType; + typedef typename Superclass::InputSpacingType InputSpacingType; + typedef TFeatureImage FeatureImageType; - typedef typename FeatureImageType::Pointer FeatureImagePtr; + typedef typename FeatureImageType::Pointer FeatureImagePointer; typedef typename FeatureImageType::PixelType FeaturePixelType; typedef typename FeatureImageType::IndexType FeatureIndexType; typedef typename FeatureIndexType::IndexValueType FeatureIndexValueType; typedef typename FeatureImageType::RegionType FeatureRegionType; /** Output image type typedefs */ - typedef typename Superclass::InputImageType InputImageType; - typedef typename Superclass::InputImagePointer InputImagePointer; - typedef typename Superclass::InputPointType InputPointType; - typedef typename Superclass::InputSpacingType InputSpacingType; - - typedef typename Superclass::OutputImageType OutputImageType; - typedef typename OutputImageType::ValueType ValueType; + typedef TOutputImage OutputImageType; typedef typename OutputImageType::IndexType IndexType; typedef typename OutputImageType::PixelType OutputPixelType; @@ -110,7 +111,6 @@ public: FeatureImageType, FeatureImageType > ROIFilterType; typedef typename ROIFilterType::Pointer ROIFilterPointer; - #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro(OutputHasNumericTraitsCheck, @@ -120,20 +120,15 @@ public: /** Set/Get the feature image to be used for speed function of the level set * equation. Equivalent to calling Set/GetInput(1, ..) */ - virtual void SetFeatureImage(const FeatureImageType *f) - { - this->ProcessObject::SetNthInput( 0, const_cast< FeatureImageType *>(f) ); - } - - virtual const FeatureImageType * GetFeatureImage() const + virtual void SetFeatureImage( const FeatureImagePointer f ) { - return (static_cast< const FeatureImageType*>(this->ProcessObject::GetInput(0))); + this->SetInput( f ); } protected: ScalarChanAndVeseSparseLevelSetImageFilter() { - this->SetNumberOfLayers(5); // Narrow-band usage + this->SetNumberOfLayers(2); // Narrow-band usage this->m_SharedData = SharedDataType::New(); } @@ -144,7 +139,7 @@ protected: virtual void Initialize(); virtual void InitializeIteration(); virtual void UpdatePixel( unsigned int functionIndex, - unsigned int idx, NeighborhoodIterator< OutputImageType > &iterator, + unsigned int idx, NeighborhoodIterator< InputImageType > &iterator, ValueType &newValue, bool &status ); }; diff --git a/Utilities/ITK/Code/Review/itkScalarChanAndVeseSparseLevelSetImageFilter.txx b/Utilities/ITK/Code/Review/itkScalarChanAndVeseSparseLevelSetImageFilter.txx index f54d34969acebf6d0753b740e3363560a9bffa90..94b74a60bf5c57717938dfb6de6b2ea95ac9282d 100644 --- a/Utilities/ITK/Code/Review/itkScalarChanAndVeseSparseLevelSetImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkScalarChanAndVeseSparseLevelSetImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarChanAndVeseSparseLevelSetImageFilter.txx,v $ Language: C++ - Date: $Date: 2009-05-16 12:35:12 $ - Version: $Revision: 1.3 $ + Date: $Date: 2009-08-06 01:46:47 $ + Version: $Revision: 1.8 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,26 +22,22 @@ namespace itk { -template < class TInput, class TFeature, class TFunction, -class TOutputPixel, class TSharedData, typename TIdCell > +template < class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, +class TSharedData, typename TIdCell > void -ScalarChanAndVeseSparseLevelSetImageFilter< TInput, TFeature, TFunction, -TOutputPixel, TSharedData, TIdCell >:: +ScalarChanAndVeseSparseLevelSetImageFilter< TInputImage, TFeatureImage, TOutputImage, +TFunction, TSharedData, TIdCell >:: Initialize() { // Set the feature image for the individual level-set functions - for( IdCellType i = 0; i < this->m_FunctionCount; i++) + for( IdCellType fId = 0; fId < this->m_FunctionCount; ++fId ) { - InputImagePointer input = this->m_LevelSet[i]; + InputImagePointer input = this->m_LevelSet[fId]; InputPointType origin = input->GetOrigin(); - InputSpacingType spacing = input->GetSpacing(); // In the context of the global coordinates FeatureIndexType start; - for( unsigned int j = 0; j < ImageDimension; j++ ) - { - start[j] = static_cast<FeatureIndexValueType>( origin[j]/spacing[j] ); - } + this->GetInput()->TransformPhysicalPointToIndex( origin, start ); // Defining roi region FeatureRegionType region; @@ -50,14 +46,15 @@ Initialize() // Initialize the ROI filter with the feature image ROIFilterPointer roi = ROIFilterType::New(); - roi->SetInput( this->GetFeatureImage() ); + roi->SetInput( this->GetInput() ); roi->SetRegionOfInterest( region ); roi->Update(); // Assign roi output - FeatureImagePtr feature = roi->GetOutput(); - this->m_DifferenceFunctions[i]->SetFeatureImage( feature ); - this->m_DifferenceFunctions[i]->SetInitialImage( input ); + FeatureImagePointer feature = roi->GetOutput(); + this->m_DifferenceFunctions[fId]->SetFeatureImage( feature ); + this->m_DifferenceFunctions[fId]->SetInitialImage( input ); + this->m_DifferenceFunctions[fId]->CalculateAdvectionImage(); } // Initialize the function count in m_SharedData @@ -69,49 +66,49 @@ Initialize() this->m_SharedData->SetKdTree( this->m_KdTree ); } - for ( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + for ( IdCellType fId = 0; fId < this->m_FunctionCount; ++fId ) { - FunctionPtr typedPointer = this->m_DifferenceFunctions[i]; + FunctionPtr typedPointer = this->m_DifferenceFunctions[fId]; - typedPointer->SetFunctionId( i ); + typedPointer->SetFunctionId( fId ); - this->m_SharedData->CreateHeavisideFunctionOfLevelSetImage ( i, this->m_LevelSet[i] ); + this->m_SharedData->CreateHeavisideFunctionOfLevelSetImage ( fId, this->m_LevelSet[fId] ); // Share the m_SharedData structure typedPointer->SetSharedData( this->m_SharedData ); } - this->m_SharedData->AllocateListImage( this->GetFeatureImage() ); + this->m_SharedData->AllocateListImage( this->GetInput() ); this->m_SharedData->PopulateListImage(); Superclass::Initialize(); - for (IdCellType i = 0; i < this->m_FunctionCount; i++) + for ( IdCellType fId = 0; fId < this->m_FunctionCount; ++fId ) { - this->m_DifferenceFunctions[i]->UpdateSharedData(true); + this->m_DifferenceFunctions[fId]->UpdateSharedData(true); } - for ( IdCellType i = 0; i < this->m_FunctionCount; i++ ) + for ( IdCellType fId = 0; fId < this->m_FunctionCount; ++fId ) { - this->m_DifferenceFunctions[i]->UpdateSharedData( false ); + this->m_DifferenceFunctions[fId]->UpdateSharedData( false ); } } /** Overrides parent implementation */ // This function is called at the end of each iteration -template < class TInput, class TFeature, class TFunction, -class TOutputPixel, class TSharedData, typename TIdCell > +template <class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, +class TSharedData, typename TIdCell > void -ScalarChanAndVeseSparseLevelSetImageFilter< TInput, TFeature, -TFunction, TOutputPixel, TSharedData, TIdCell > :: +ScalarChanAndVeseSparseLevelSetImageFilter<TInputImage, TFeatureImage, TOutputImage, +TFunction, TSharedData, TIdCell > :: InitializeIteration() { Superclass::InitializeIteration(); - for (IdCellType i = 0; i < this->m_FunctionCount; i++) + for (IdCellType fId = 0; fId < this->m_FunctionCount; ++fId) { - this->m_DifferenceFunctions[i]->UpdateSharedData( false ); + this->m_DifferenceFunctions[fId]->UpdateSharedData( false ); } // Estimate the progress of the filter @@ -119,16 +116,16 @@ InitializeIteration() / ( float ) this->m_NumberOfIterations ) ); } -template < class TInput, class TFeature, class TFunction, -class TOutputPixel, class TSharedData, typename TIdCell > +template < class TInputImage, class TFeatureImage, class TOutputImage, class TFunction, +class TSharedData, typename TIdCell > void -ScalarChanAndVeseSparseLevelSetImageFilter< TInput, TFeature, -TFunction, TOutputPixel, TSharedData, TIdCell > :: -UpdatePixel ( unsigned int functionIndex, unsigned int idx, -NeighborhoodIterator< OutputImageType > &iterator, ValueType &newValue, +ScalarChanAndVeseSparseLevelSetImageFilter<TInputImage, TFeatureImage, TOutputImage, +TFunction, TSharedData, TIdCell > :: +UpdatePixel ( unsigned int fId, unsigned int idx, +NeighborhoodIterator< InputImageType > &iterator, ValueType &newValue, bool &status ) { - FunctionPtr typedPointer = this->m_DifferenceFunctions[functionIndex]; + FunctionPtr typedPointer = this->m_DifferenceFunctions[fId]; typedPointer->UpdatePixel( idx, iterator, newValue, status ); iterator.SetPixel(idx, newValue, status); diff --git a/Utilities/ITK/Code/Review/itkScalarRegionBasedLevelSetFunction.h b/Utilities/ITK/Code/Review/itkScalarRegionBasedLevelSetFunction.h index 4108ee43489708940ade54abdfbd5a75e34ee492..5d7df3d2b3775648c75941d4f14417a665f9c77b 100644 --- a/Utilities/ITK/Code/Review/itkScalarRegionBasedLevelSetFunction.h +++ b/Utilities/ITK/Code/Review/itkScalarRegionBasedLevelSetFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarRegionBasedLevelSetFunction.h,v $ Language: C++ - Date: $Date: 2009-05-13 14:23:05 $ - Version: $Revision: 1.7 $ + Date: $Date: 2009-06-12 09:44:02 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -30,7 +30,8 @@ namespace itk { * \brief LevelSet function that computes a speed image based on regional integrals * * This class implements a level set function that computes the speed image by - * integrating values on the image domain. + * integrating values on the image domain. NOTE: The convention followed is + * inside of the level-set function is negative and outside is positive. * * Based on the paper: * @@ -134,10 +135,14 @@ protected: ScalarValueType ComputeOverlapParameters( const FeatureIndexType& featIndex, ScalarValueType& product ); + // update the background and foreground constants for pixel updates + // Called only when sparse filters are used to prevent iteration through the + // entire image virtual void UpdateSharedDataInsideParameters( const unsigned int& iId, - const bool& iBool, const FeaturePixelType& iVal, const ScalarValueType& iH ) = 0; + const FeaturePixelType& iVal, const ScalarValueType& iChange ) = 0; virtual void UpdateSharedDataOutsideParameters( const unsigned int& iId, - const bool& iBool, const FeaturePixelType& iVal, const ScalarValueType& iH ) = 0; + const FeaturePixelType& iVal, const ScalarValueType& iChange ) = 0; + private: ScalarRegionBasedLevelSetFunction(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Code/Review/itkScalarRegionBasedLevelSetFunction.txx b/Utilities/ITK/Code/Review/itkScalarRegionBasedLevelSetFunction.txx index 08d899fa6f0039e002cb67e8b6d11500bda7cce0..7d2df9f0aad56b098461c1dea2482d7005310753 100644 --- a/Utilities/ITK/Code/Review/itkScalarRegionBasedLevelSetFunction.txx +++ b/Utilities/ITK/Code/Review/itkScalarRegionBasedLevelSetFunction.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkScalarRegionBasedLevelSetFunction.txx,v $ Language: C++ - Date: $Date: 2009-05-21 22:03:29 $ - Version: $Revision: 1.14 $ + Date: $Date: 2009-07-25 18:52:39 $ + Version: $Revision: 1.19 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -22,6 +22,8 @@ namespace itk { +// Computes the overlap multiplicative factors for the penalty term (sum) and +// the background intensity fitting terms in multiphase level-sets template < class TInputImage, class TFeatureImage, class TSharedData > typename ScalarRegionBasedLevelSetFunction< TInputImage, TFeatureImage, TSharedData >::ScalarValueType ScalarRegionBasedLevelSetFunction< TInputImage, TFeatureImage, TSharedData > @@ -43,23 +45,24 @@ ScalarRegionBasedLevelSetFunction< TInputImage, TFeatureImage, TSharedData > for ( ListPixelIterator it = L.begin(); it != L.end(); ++it ) { - unsigned int id = *it; - if ( id != fId ) + if ( *it != fId ) { - otherIndex = this->m_SharedData->m_LevelSetDataPointerVector[id]->GetIndex( globalIndex ); - hVal = this->m_SharedData->m_LevelSetDataPointerVector[id]->m_HeavisideFunctionOfLevelSetImage->GetPixel( otherIndex ); + otherIndex = this->m_SharedData->m_LevelSetDataPointerVector[*it]->GetIndex( globalIndex ); + hVal = this->m_SharedData->m_LevelSetDataPointerVector[*it]->m_HeavisideFunctionOfLevelSetImage->GetPixel( otherIndex ); - sum += hVal; - product *= hVal; + sum += (1 - hVal); + product *= ( 1 - hVal ); } } + return sum; } /* Performs the narrow-band update of the Heaviside function for each voxel. The characteristic function of each region is recomputed (note the shared data which contains information from the other level sets). Using the -new H values, the previous c_i are updated. */ +new H values, the previous c_i are updated. Used by only the sparse image +filter */ template < class TInputImage, class TFeatureImage, class TSharedData > void ScalarRegionBasedLevelSetFunction< TInputImage, TFeatureImage, TSharedData > @@ -76,53 +79,33 @@ ScalarRegionBasedLevelSetFunction< TInputImage, TFeatureImage, TSharedData > ScalarValueType oldH = this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_HeavisideFunctionOfLevelSetImage->GetPixel( inputIndex ); ScalarValueType newH = this->m_DomainFunction->Evaluate( - newValue ); + ScalarValueType change = newH - oldH; + + // update the foreground constant for current level-set function + UpdateSharedDataInsideParameters( fId, featureVal, change ); - // Check if it is in other foreground + // Compute the product factor ListPixelType L = this->m_SharedData->m_NearestNeighborListImage->GetPixel( globalIndex ); InputIndexType itInputIndex; ScalarValueType hVal; - bool inBgrnd = true; // assume the pixel is in background + InputPixelType product = 1; for( ListPixelType::const_iterator it = L.begin(); it != L.end(); ++it ) { - itInputIndex = this->m_SharedData->m_LevelSetDataPointerVector[*it]->GetIndex( globalIndex ); - hVal = this->m_SharedData->m_LevelSetDataPointerVector[*it]->m_HeavisideFunctionOfLevelSetImage->GetPixel( itInputIndex ); - - if ( ( hVal > 0.5 ) && ( *it != fId ) ) - { - inBgrnd = false; // belongs to foreground elsewhere - } - } - - // if pixel belonged to current foreground but not anymore so - if ( ( oldH > 0.5 ) && ( newH <= 0.5 ) ) - { - UpdateSharedDataInsideParameters( fId, false, featureVal, newH ); - - // have to update level-set backgrounds overlapping - // at the current pixel - if ( inBgrnd ) + if (*it != fId ) { - for( ListPixelType::const_iterator it = L.begin(); it != L.end(); ++it ) - { - UpdateSharedDataOutsideParameters( *it, true, featureVal, newH ); - } + itInputIndex = this->m_SharedData->m_LevelSetDataPointerVector[*it]->GetIndex( globalIndex ); + hVal = this->m_SharedData->m_LevelSetDataPointerVector[*it]->m_HeavisideFunctionOfLevelSetImage->GetPixel( itInputIndex ); + product *= ( 1 - hVal ); } } + // Determine the change in the product factor + ScalarValueType productChange = -(product * change); - // if pixel entered the foreground - if ( ( oldH <= 0.5 ) && ( newH > 0.5 ) ) + // update the background constant of all level-set functions + for( ListPixelType::const_iterator it = L.begin(); it != L.end(); ++it ) { - UpdateSharedDataInsideParameters( fId, true, featureVal, newH ); - // have to update level-set backgrounds overlapping - // at the current pixel - if ( inBgrnd ) - { - for( ListPixelType::const_iterator it = L.begin(); it != L.end(); ++it ) - { - UpdateSharedDataOutsideParameters( *it, false, featureVal, newH ); - } - } + UpdateSharedDataOutsideParameters( *it, featureVal, productChange ); } this->m_SharedData->m_LevelSetDataPointerVector[fId]->m_HeavisideFunctionOfLevelSetImage->SetPixel( inputIndex, newH ); diff --git a/Utilities/ITK/Code/Review/itkScaleVersor3DTransform.h b/Utilities/ITK/Code/Review/itkScaleVersor3DTransform.h new file mode 100644 index 0000000000000000000000000000000000000000..027ad7580aff5b92e03b94980e3f297ac46e97c3 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkScaleVersor3DTransform.h @@ -0,0 +1,157 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScaleVersor3DTransform.h,v $ + Language: C++ + Date: $Date: 2009-08-09 16:35:47 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkScaleVersor3DTransform_h +#define __itkScaleVersor3DTransform_h + +#include <iostream> +#include "itkVersorRigid3DTransform.h" + +namespace itk +{ + +/** \class ScaleVersor3DTransform + * + * \brief This transform applies a Versor rotation, translation and + * anisotropic scale to the space. + * + * This Transform provides the next set of degrees of freedom after a + * Similarity transform. In a Similarity transform it is possible to do + * rotation, translation and uniform scaling. In this current transform we can + * do rotation, translation and anisotropic scaling. + * + * \author Johnson H.J., Harris G., Williams K. University of Iow Carver + * College of Medicine, Department of Psychiatry NeuroImaging Center + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/1291 or + * http://www.insight-journal.org/browse/publication/180 + * + * \ingroup Transforms + */ +template < class TScalarType=double > // Data type for scalars:float or double +class ITK_EXPORT ScaleVersor3DTransform : public VersorRigid3DTransform< TScalarType > +{ +public: + /** Standard class typedefs. */ + typedef ScaleVersor3DTransform Self; + typedef VersorRigid3DTransform< TScalarType > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** New macro for creation of through a Smart Pointer. */ + itkNewMacro( Self ); + + /** Run-time type information (and related methods). */ + itkTypeMacro( ScaleVersor3DTransform, VersorRigid3DTransform ); + + /** Dimension of parameters. */ + itkStaticConstMacro(InputSpaceDimension, unsigned int, 3); + itkStaticConstMacro(OutputSpaceDimension, unsigned int, 3); + itkStaticConstMacro(ParametersDimension, unsigned int, 9); + + /** Parameters Type */ + typedef typename Superclass::ParametersType ParametersType; + typedef typename Superclass::JacobianType JacobianType; + typedef typename Superclass::ScalarType ScalarType; + typedef typename Superclass::InputPointType InputPointType; + typedef typename Superclass::OutputPointType OutputPointType; + typedef typename Superclass::InputVectorType InputVectorType; + typedef typename Superclass::OutputVectorType OutputVectorType; + typedef typename Superclass::InputVnlVectorType InputVnlVectorType; + typedef typename Superclass::OutputVnlVectorType OutputVnlVectorType; + typedef typename Superclass::InputCovariantVectorType + InputCovariantVectorType; + typedef typename Superclass::OutputCovariantVectorType + OutputCovariantVectorType; + typedef typename Superclass::MatrixType MatrixType; + typedef typename Superclass::InverseMatrixType InverseMatrixType; + typedef typename Superclass::CenterType CenterType; + typedef typename Superclass::OffsetType OffsetType; + typedef typename Superclass::TranslationType TranslationType; + + typedef typename Superclass::VersorType VersorType; + typedef typename Superclass::AxisType AxisType; + typedef typename Superclass::AngleType AngleType; + + /** Scale Vector Type. */ + typedef Vector<TScalarType, 3> ScaleVectorType; + + /** Directly set the matrix of the transform. + * + * \sa MatrixOffsetTransformBase::SetMatrix() */ + virtual void SetMatrix(const MatrixType &matrix); + + /** Set the transformation from a container of parameters + * This is typically used by optimizers. + * There are 9 parameters: + * 0-2 versor + * 3-5 translation + * 6-8 Scale + ** */ + virtual void SetParameters( const ParametersType & parameters ); + virtual const ParametersType& GetParameters(void) const; + + void SetScale( const ScaleVectorType & scale ); + itkGetConstReferenceMacro( Scale, ScaleVectorType ); + + void SetIdentity(); + + /** This method computes the Jacobian matrix of the transformation. + * given point or vector, returning the transformed point or + * vector. The rank of the Jacobian will also indicate if the + * transform is invertible at this point. */ + const JacobianType & GetJacobian(const InputPointType &point ) const; + +protected: + ScaleVersor3DTransform(); + ScaleVersor3DTransform(const MatrixType &matrix, + const OutputVectorType &offset); + ScaleVersor3DTransform(unsigned int outputDims, + unsigned int paramDims); + ~ScaleVersor3DTransform() + { + }; + + void PrintSelf(std::ostream &os, Indent indent) const; + + void SetVarScale(const ScaleVectorType & scale) + { + m_Scale = scale; + } + + /** Compute the components of the rotation matrix in the superclass. */ + void ComputeMatrix(void); + void ComputeMatrixParameters(void); + +private: + ScaleVersor3DTransform(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + /** Vector containing the scale. */ + ScaleVectorType m_Scale; + +}; //class ScaleVersor3DTransform + + +} // namespace itk + + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkScaleVersor3DTransform.txx" +#endif + +#endif /* __ScaleVersor3DTransform_h */ diff --git a/Utilities/ITK/Code/Review/itkScaleVersor3DTransform.txx b/Utilities/ITK/Code/Review/itkScaleVersor3DTransform.txx new file mode 100644 index 0000000000000000000000000000000000000000..b587572ee9e7bd6c0ca8ba17594da52c3bf3753e --- /dev/null +++ b/Utilities/ITK/Code/Review/itkScaleVersor3DTransform.txx @@ -0,0 +1,311 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkScaleVersor3DTransform.txx,v $ + Language: C++ + Date: $Date: 2009-08-09 16:35:47 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkScaleVersor3DTransform_txx +#define __itkScaleVersor3DTransform_txx + +#include "itkScaleVersor3DTransform.h" + + +namespace itk +{ + +// Constructor with default arguments +template <class TScalarType> +ScaleVersor3DTransform<TScalarType> +::ScaleVersor3DTransform() : Superclass(OutputSpaceDimension, ParametersDimension) +{ + m_Scale.Fill( 1.0 ); +} + + +// Constructor with arguments +template<class TScalarType> +ScaleVersor3DTransform<TScalarType>:: +ScaleVersor3DTransform( unsigned int spaceDimension, unsigned int parametersDimension): + Superclass(spaceDimension, parametersDimension) +{ + m_Scale.Fill( 1.0 ); +} + +// Constructor with arguments +template<class TScalarType> +ScaleVersor3DTransform<TScalarType>:: +ScaleVersor3DTransform( const MatrixType & matrix, const OutputVectorType & offset): + Superclass(matrix, offset) +{ + this->ComputeMatrixParameters(); +} + +// Directly set the matrix +template<class TScalarType> +void +ScaleVersor3DTransform<TScalarType> +::SetMatrix( const MatrixType & matrix ) +{ + // Any matrix should work - bypass orthogonality testing + typedef MatrixOffsetTransformBase<TScalarType, 3> Baseclass; + this->Baseclass::SetMatrix( matrix ); +} + +// Set Parameters +template <class TScalarType> +void +ScaleVersor3DTransform<TScalarType> +::SetParameters( const ParametersType & parameters ) +{ + + itkDebugMacro( << "Setting parameters " << parameters ); + + + // Transfer the versor part + + AxisType axis; + + double norm = parameters[0]*parameters[0]; + axis[0] = parameters[0]; + norm += parameters[1]*parameters[1]; + axis[1] = parameters[1]; + norm += parameters[2]*parameters[2]; + axis[2] = parameters[2]; + if( norm > 0) + { + norm = vcl_sqrt(norm); + } + + double epsilon = 1e-10; + if(norm >= 1.0-epsilon) + { + axis = axis / (norm+epsilon*norm); + } + VersorType newVersor; + newVersor.Set(axis); + this->SetVarVersor( newVersor ); + + itkDebugMacro( <<"Versor is now " << newVersor ); + + // Matrix must be defined before translation so that offset can be computed + // from translation + m_Scale[0] = parameters[6]; + m_Scale[1] = parameters[7]; + m_Scale[2] = parameters[8]; + + // Transfer the translation part + TranslationType newTranslation; + newTranslation[0] = parameters[3]; + newTranslation[1] = parameters[4]; + newTranslation[2] = parameters[5]; + this->SetVarTranslation(newTranslation); + this->ComputeMatrix(); + this->ComputeOffset(); + + // Modified is always called since we just have a pointer to the + // parameters and cannot know if the parameters have changed. + this->Modified(); + + itkDebugMacro(<<"After setting parameters "); +} + + +// +// Get Parameters +// +// Parameters are ordered as: +// +// p[0:2] = right part of the versor (axis times vcl_sin(t/2)) +// p[3:5] = translation components +// p[6:8] = Scale +// + +template <class TScalarType> +const typename ScaleVersor3DTransform<TScalarType>::ParametersType & +ScaleVersor3DTransform<TScalarType> +::GetParameters( void ) const +{ + itkDebugMacro( << "Getting parameters "); + + this->m_Parameters[0] = this->GetVersor().GetX(); + this->m_Parameters[1] = this->GetVersor().GetY(); + this->m_Parameters[2] = this->GetVersor().GetZ(); + + this->m_Parameters[3] = this->GetTranslation()[0]; + this->m_Parameters[4] = this->GetTranslation()[1]; + this->m_Parameters[5] = this->GetTranslation()[2]; + + this->m_Parameters[6] = this->GetScale()[0]; + this->m_Parameters[7] = this->GetScale()[1]; + this->m_Parameters[8] = this->GetScale()[2]; + + itkDebugMacro(<<"After getting parameters " << this->m_Parameters ); + + return this->m_Parameters; +} + +template <class TScalarType> +void +ScaleVersor3DTransform<TScalarType> +::SetIdentity() +{ + m_Scale.Fill( 1.0 ); + Superclass::SetIdentity(); +} + + +template <class TScalarType> +void +ScaleVersor3DTransform<TScalarType> +::SetScale( const ScaleVectorType & scale ) +{ + m_Scale = scale; + this->ComputeMatrix(); +} + + +// // THIS is different from VersorRigid3DTransform; +// // it is copied from ScaleSkewVersor3DTransform: +// Compute the matrix +template <class TScalarType> +void +ScaleVersor3DTransform<TScalarType> +::ComputeMatrix( void ) +{ + + VersorType versor = Superclass::GetVersor(); + + const TScalarType vx = versor.GetX(); + const TScalarType vy = versor.GetY(); + const TScalarType vz = versor.GetZ(); + const TScalarType vw = versor.GetW(); + + const TScalarType xx = vx * vx; + const TScalarType yy = vy * vy; + const TScalarType zz = vz * vz; + const TScalarType xy = vx * vy; + const TScalarType xz = vx * vz; + const TScalarType xw = vx * vw; + const TScalarType yz = vy * vz; + const TScalarType yw = vy * vw; + const TScalarType zw = vz * vw; + + MatrixType newMatrix; + newMatrix[0][0] = m_Scale[0] - 2.0 * ( yy + zz ); + newMatrix[1][1] = m_Scale[1] - 2.0 * ( xx + zz ); + newMatrix[2][2] = m_Scale[2] - 2.0 * ( xx + yy ); + newMatrix[0][1] = 2.0 * ( xy - zw ); + newMatrix[0][2] = 2.0 * ( xz + yw ); + newMatrix[1][0] = 2.0 * ( xy + zw ); + newMatrix[1][2] = 2.0 * ( yz - xw ); + newMatrix[2][0] = 2.0 * ( xz - yw ); + newMatrix[2][1] = 2.0 * ( yz + xw ); + this->SetVarMatrix ( newMatrix ); +} + + +template <class TScalarType> +void +ScaleVersor3DTransform<TScalarType> +::ComputeMatrixParameters( void ) +{ + itkExceptionMacro( << "Setting the matrix of a ScaleVersor3D transform is not supported at this time." ); +} + + +// Print self +template<class TScalarType> +void +ScaleVersor3DTransform<TScalarType> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "Scale: " << m_Scale << std::endl; +} + + +// Set parameters +template<class TScalarType> +const typename ScaleVersor3DTransform<TScalarType>::JacobianType & +ScaleVersor3DTransform<TScalarType>:: +GetJacobian( const InputPointType & p ) const +{ + typedef typename VersorType::ValueType ValueType; + + // compute derivatives with respect to rotation + const ValueType vx = this->GetVersor().GetX(); + const ValueType vy = this->GetVersor().GetY(); + const ValueType vz = this->GetVersor().GetZ(); + const ValueType vw = this->GetVersor().GetW(); + + this->m_Jacobian.Fill(0.0); + + const double px = p[0] - this->GetCenter()[0]; + const double py = p[1] - this->GetCenter()[1]; + const double pz = p[2] - this->GetCenter()[2]; + + const double vxx = vx * vx; + const double vyy = vy * vy; + const double vzz = vz * vz; + const double vww = vw * vw; + + const double vxy = vx * vy; + const double vxz = vx * vz; + const double vxw = vx * vw; + + const double vyz = vy * vz; + const double vyw = vy * vw; + + const double vzw = vz * vw; + + + // compute Jacobian with respect to quaternion parameters + this->m_Jacobian[0][0] = 2.0 * ( (vyw+vxz)*py + (vzw-vxy)*pz) + / vw; + this->m_Jacobian[1][0] = 2.0 * ((vyw-vxz)*px -2*vxw *py + (vxx-vww)*pz) + / vw; + this->m_Jacobian[2][0] = 2.0 * ((vzw+vxy)*px + (vww-vxx)*py -2*vxw *pz) + / vw; + + this->m_Jacobian[0][1] = 2.0 * ( -2*vyw *px + (vxw+vyz)*py + (vww-vyy)*pz) + / vw; + this->m_Jacobian[1][1] = 2.0 * ((vxw-vyz)*px + (vzw+vxy)*pz) + / vw; + this->m_Jacobian[2][1] = 2.0 * ((vyy-vww)*px + (vzw-vxy)*py -2*vyw *pz) + / vw; + + this->m_Jacobian[0][2] = 2.0 * ( -2*vzw *px + (vzz-vww)*py + (vxw-vyz)*pz) + / vw; + this->m_Jacobian[1][2] = 2.0 * ((vww-vzz)*px -2*vzw *py + (vyw+vxz)*pz) + / vw; + this->m_Jacobian[2][2] = 2.0 * ((vxw+vyz)*px + (vyw-vxz)*py ) + / vw; + + this->m_Jacobian[0][3] = 1.0; + this->m_Jacobian[1][4] = 1.0; + this->m_Jacobian[2][5] = 1.0; + + // // THIS is different from VersorRigid3DTransform; + // // it is copied from ScaleSkewVersor3DTransform: + this->m_Jacobian[0][6] = px; + this->m_Jacobian[1][7] = py; + this->m_Jacobian[2][8] = pz; + + return this->m_Jacobian; +} + + +} // namespace + +#endif diff --git a/Utilities/ITK/Code/Review/itkShapeKeepNObjectsLabelMapFilter.h b/Utilities/ITK/Code/Review/itkShapeKeepNObjectsLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..9f2793bd79225d6c3d90d07f6d6481ac6174db2d --- /dev/null +++ b/Utilities/ITK/Code/Review/itkShapeKeepNObjectsLabelMapFilter.h @@ -0,0 +1,193 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkShapeKeepNObjectsLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-05 16:08:10 $ + Version: $Revision: 1.4 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkShapeKeepNObjectsLabelMapFilter_h +#define __itkShapeKeepNObjectsLabelMapFilter_h + +#include "itkInPlaceLabelMapFilter.h" +#include "itkLabelObjectAccessors.h" +#include "itkShapeLabelObjectAccessors.h" +#include "itkProgressReporter.h" + +namespace itk { +/** \class ShapeKeepNObjectsLabelMapFilter + * \brief Keep N objects according to their shape attributes. + * + * The ShapeKeepNObjectsLabelMapFilter keeps N objects in a label collection image with the + * highest (or lowest) attribute value. The attributes values are those of the ShapeLabelObject. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * \sa ShapeLabelObject, BinaryShapeKeepNObjectsImageFilter, LabelStatisticsKeepNObjectsImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TImage> +class ITK_EXPORT ShapeKeepNObjectsLabelMapFilter : + public InPlaceLabelMapFilter<TImage> +{ +public: + /** Standard class typedefs. */ + typedef ShapeKeepNObjectsLabelMapFilter Self; + typedef InPlaceLabelMapFilter<TImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TImage ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::LabelObjectType LabelObjectType; + + typedef typename LabelObjectType::AttributeType AttributeType; + + typedef typename Superclass::LabelObjectContainerType LabelObjectContainerType; + + /** ImageDimension constants */ + itkStaticConstMacro(ImageDimension, unsigned int, TImage::ImageDimension); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(ShapeKeepNObjectsLabelMapFilter, InPlaceLabelMapFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ +/* itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>));*/ + /** End concept checking */ +#endif + + /** + * Set/Get the ordering of the objects. By default, the ones with the + * highest value are kept. Turning ReverseOrdering to true make this filter + * keep the objects with the smallest values + */ + itkSetMacro( ReverseOrdering, bool ); + itkGetConstReferenceMacro( ReverseOrdering, bool ); + itkBooleanMacro( ReverseOrdering ); + + /** + * Set/Get the number of objects to keep + */ + itkSetMacro( NumberOfObjects, unsigned long ); + itkGetConstReferenceMacro( NumberOfObjects, unsigned long ); + + /** + * Set/Get the attribute to use to select the object to keep. + * Default is "Size". + */ + itkGetConstMacro( Attribute, AttributeType ); + itkSetMacro( Attribute, AttributeType ); + + void SetAttribute( const std::string & s ) + { + this->SetAttribute( LabelObjectType::GetAttributeFromName( s ) ); + } + + +protected: + ShapeKeepNObjectsLabelMapFilter(); + ~ShapeKeepNObjectsLabelMapFilter() {}; + + void GenerateData(); + + template <class TAttributeAccessor> + void TemplatedGenerateData( const TAttributeAccessor & ) + { + // Allocate the output + this->AllocateOutputs(); + + ImageType * output = this->GetOutput(); + ImageType * output2 = this->GetOutput( 1 ); + + // set the background value for the second output - this is not done in the superclasses + output2->SetBackgroundValue( output->GetBackgroundValue() ); + + const LabelObjectContainerType & labelObjectContainer = output->GetLabelObjectContainer(); + typedef typename LabelObjectType::Pointer LabelObjectPointer; + typedef std::vector< LabelObjectPointer > VectorType; + + ProgressReporter progress( this, 0, 2 * labelObjectContainer.size() ); + + // get the label objects in a vector, so they can be sorted + VectorType labelObjects; + labelObjects.reserve( labelObjectContainer.size() ); + typename LabelObjectContainerType::const_iterator it = labelObjectContainer.begin(); + while( it != labelObjectContainer.end() ) + { + labelObjects.push_back( it->second ); + progress.CompletedPixel(); + it++; + } + + // instantiate the comparator and sort the vector + if( m_NumberOfObjects < labelObjectContainer.size() ) + { + typename VectorType::iterator end = labelObjects.begin() + m_NumberOfObjects; + if( m_ReverseOrdering ) + { + Functor::LabelObjectReverseComparator< LabelObjectType, TAttributeAccessor > comparator; + std::nth_element( labelObjects.begin(), end, labelObjects.end(), comparator ); + } + else + { + Functor::LabelObjectComparator< LabelObjectType, TAttributeAccessor > comparator; + std::nth_element( labelObjects.begin(), end, labelObjects.end(), comparator ); + } + progress.CompletedPixel(); + + // and remove the last objects of the map + for( typename VectorType::const_iterator it2 = end; + it2 != labelObjects.end(); + it2++ ) + { + output2->AddLabelObject( *it2 ); + output->RemoveLabelObject( *it2 ); + progress.CompletedPixel(); + } + } + } + + void PrintSelf(std::ostream& os, Indent indent) const; + + bool m_ReverseOrdering; + unsigned long m_NumberOfObjects; + AttributeType m_Attribute; + +private: + ShapeKeepNObjectsLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkShapeKeepNObjectsLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkShapeKeepNObjectsLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkShapeKeepNObjectsLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..e9339ec6f6828146518bc7c3062e42e70c89abdb --- /dev/null +++ b/Utilities/ITK/Code/Review/itkShapeKeepNObjectsLabelMapFilter.txx @@ -0,0 +1,164 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkShapeKeepNObjectsLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-04 21:25:48 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkShapeKeepNObjectsLabelMapFilter_txx +#define __itkShapeKeepNObjectsLabelMapFilter_txx + +#include "itkShapeKeepNObjectsLabelMapFilter.h" +#include "itkShapeLabelObject.h" + +namespace itk { + +template <class TImage> +ShapeKeepNObjectsLabelMapFilter<TImage> +::ShapeKeepNObjectsLabelMapFilter() +{ + m_ReverseOrdering = false; + m_NumberOfObjects = 1; + m_Attribute = LabelObjectType::SIZE; + + // create the output image for the removed objects + this->SetNumberOfRequiredOutputs(2); + this->SetNthOutput(1, static_cast<TImage*>(this->MakeOutput(1).GetPointer())); +} + + +template <class TImage> +void +ShapeKeepNObjectsLabelMapFilter<TImage> +::GenerateData() +{ + switch( m_Attribute ) + { + case LabelObjectType::LABEL: + { + typedef typename Functor::LabelLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::SIZE: + { + typedef typename Functor::SizeLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::PHYSICAL_SIZE: + { + typedef typename Functor::PhysicalSizeLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::SIZE_REGION_RATIO: + { + typedef typename Functor::SizeRegionRatioLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::REGION_ELONGATION: + { + typedef typename Functor::RegionElongationLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::SIZE_ON_BORDER: + { + typedef typename Functor::SizeOnBorderLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::PHYSICAL_SIZE_ON_BORDER: + { + typedef typename Functor::PhysicalSizeOnBorderLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::FERET_DIAMETER: + { + typedef typename Functor::FeretDiameterLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::BINARY_ELONGATION: + { + typedef typename Functor::BinaryElongationLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::PERIMETER: + { + typedef typename Functor::PerimeterLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::ROUNDNESS: + { + typedef typename Functor::RoundnessLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::EQUIVALENT_RADIUS: + { + typedef typename Functor::EquivalentRadiusLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::EQUIVALENT_PERIMETER: + { + typedef typename Functor::EquivalentPerimeterLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::BINARY_FLATNESS: + { + typedef typename Functor::BinaryFlatnessLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + default: + itkExceptionMacro(<< "Unknown attribute type"); + break; + } +} + + +template <class TImage> +void +ShapeKeepNObjectsLabelMapFilter<TImage> +::PrintSelf( std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "ReverseOrdering: " << m_ReverseOrdering << std::endl; + os << indent << "NumberOfObjects: " << m_NumberOfObjects << std::endl; + os << indent << "Attribute: " << LabelObjectType::GetNameFromAttribute( m_Attribute ) << " (" << m_Attribute << ")" << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkShapeLabelMapFilter.h b/Utilities/ITK/Code/Review/itkShapeLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..8c2da008e1e21b0699f5a7de7503cb556bf0c8d8 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkShapeLabelMapFilter.h @@ -0,0 +1,159 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkShapeLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-11 14:24:44 $ + Version: $Revision: 1.6 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkShapeLabelMapFilter_h +#define __itkShapeLabelMapFilter_h +#include "itkLabelPerimeterEstimationCalculator.h" + +#include "itkInPlaceLabelMapFilter.h" + +namespace itk { + +/** \class ShapeLabelMapFilter + * \brief The valuator class for the ShapeLabelObject + * + * ShapeLabelMapFilter can be used to set the attributes values of the + * ShapeLabelObject in a LabelMap. + * + * ShapeLabelMapFilter takes an optional parameter, used only to + * optimize the computation time and the memory usage when the + * perimeter or the feret diameter is used: the exact copy of the + * input LabelMap is stored in an Image. + * It can be set with SetLabelImage(). It is cleared at the end of the + * computation, so must be reset before running Update() again. It is + * not part of the pipeline management design, to let the subclasses + * of ShapeLabelMapFilter use the pipeline design to specify truly + * required inputs. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ + +template<class TImage, class TLabelImage=Image< ITK_TYPENAME TImage::PixelType, ::itk::GetImageDimension<TImage>::ImageDimension> > +class ITK_EXPORT ShapeLabelMapFilter : +public +InPlaceLabelMapFilter<TImage> +{ +public: + /** Standard class typedefs. */ + typedef ShapeLabelMapFilter Self; + typedef InPlaceLabelMapFilter<TImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TImage ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::SizeType SizeType; + typedef typename ImageType::LabelObjectType LabelObjectType; + typedef typename LabelObjectType::MatrixType MatrixType; + typedef typename LabelObjectType::VectorType VectorType; + + typedef TLabelImage LabelImageType; + typedef typename LabelImageType::Pointer LabelImagePointer; + typedef typename LabelImageType::ConstPointer LabelImageConstPointer; + typedef typename LabelImageType::PixelType LabelPixelType; + + /** ImageDimension constants */ + itkStaticConstMacro(ImageDimension, unsigned int, TImage::ImageDimension ); + + typedef LabelPerimeterEstimationCalculator< LabelImageType > PerimeterCalculatorType; + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(ShapeLabelMapFilter, InPlaceLabelMapFilter ); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ +/* itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>));*/ + /** End concept checking */ +#endif + + /** + * Set/Get whether the maximum Feret diameter should be computed or not. + * Default value is false because of the high computation time required. + */ + itkSetMacro( ComputeFeretDiameter, bool ); + itkGetConstReferenceMacro( ComputeFeretDiameter, bool ); + itkBooleanMacro( ComputeFeretDiameter ); + + /** + * Set/Get whether the perimeter should be computed or not. + * Default value is false because of the high computation time required. + */ + itkSetMacro( ComputePerimeter, bool ); + itkGetConstReferenceMacro( ComputePerimeter, bool ); + itkBooleanMacro( ComputePerimeter ); + + /** Set the label image */ + void SetLabelImage( const TLabelImage *input ) + { + m_LabelImage = input; + } + +protected: + ShapeLabelMapFilter(); + ~ShapeLabelMapFilter() {}; + + virtual void ThreadedProcessLabelObject( LabelObjectType * labelObject ); + virtual void BeforeThreadedGenerateData(); + virtual void AfterThreadedGenerateData(); + + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + ShapeLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + bool m_ComputeFeretDiameter; + bool m_ComputePerimeter; + LabelImageConstPointer m_LabelImage; + typename PerimeterCalculatorType::Pointer m_PerimeterCalculator; + + void ComputeFeretDiameter( LabelObjectType * labelObject ); + + /** utilities */ + static long Factorial( long n ); + static long DoubleFactorial( long n ); + static double GammaN2p1( long n ); + static double HyperSphereVolume( double radius ); + static double HyperSpherePerimeter( double radius ); + static double HyperSphereRadiusFromVolume( double volume ); + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkShapeLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkShapeLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkShapeLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..0f2a87cbdf2410442d8bf6d58825aa1aaab871cb --- /dev/null +++ b/Utilities/ITK/Code/Review/itkShapeLabelMapFilter.txx @@ -0,0 +1,584 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkShapeLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-02 14:57:08 $ + Version: $Revision: 1.6 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkShapeLabelMapFilter_txx +#define __itkShapeLabelMapFilter_txx + +#include "itkShapeLabelMapFilter.h" +#include "itkProgressReporter.h" +#include "itkNeighborhoodIterator.h" +#include "itkLabelMapToLabelImageFilter.h" +#include "itkConstantBoundaryCondition.h" +#include "vnl/algo/vnl_real_eigensystem.h" +#include "vnl/algo/vnl_symmetric_eigensystem.h" +#include "vnl/vnl_math.h" + +namespace itk { + +template <class TImage, class TLabelImage> +ShapeLabelMapFilter<TImage, TLabelImage> +::ShapeLabelMapFilter() +{ + m_ComputeFeretDiameter = false; + m_ComputePerimeter = false; +} + + +template<class TImage, class TLabelImage> +void +ShapeLabelMapFilter<TImage, TLabelImage> +::BeforeThreadedGenerateData() +{ + Superclass::BeforeThreadedGenerateData(); + + // Generate the label image, if needed + if( m_ComputeFeretDiameter || m_ComputePerimeter ) + { + if( !m_LabelImage ) + { + // generate an image of the labelized image + typedef LabelMapToLabelImageFilter< TImage, LabelImageType > LCI2IType; + typename LCI2IType::Pointer lci2i = LCI2IType::New(); + lci2i->SetInput( this->GetOutput() ); + // Respect the number of threads of the filter + lci2i->SetNumberOfThreads( this->GetNumberOfThreads() ); + lci2i->Update(); + m_LabelImage = lci2i->GetOutput(); + } + } + + // Delegate the computation of the perimeter to a dedicated calculator + if( m_ComputePerimeter ) + { + m_PerimeterCalculator = PerimeterCalculatorType::New(); + m_PerimeterCalculator->SetImage( m_LabelImage ); + m_PerimeterCalculator->Compute(); + } + +} + + +template<class TImage, class TLabelImage> +void +ShapeLabelMapFilter<TImage, TLabelImage> +::ThreadedProcessLabelObject( LabelObjectType * labelObject ) +{ + ImageType * output = this->GetOutput(); + const LabelPixelType & label = labelObject->GetLabel(); + + // Compute the size per pixel, to be used later + double sizePerPixel = 1; + for( int i=0; i<ImageDimension; i++ ) + { + sizePerPixel *= output->GetSpacing()[i]; + } + + typename std::vector< double > sizePerPixelPerDimension; + for( int i=0; i<ImageDimension; i++ ) + { + sizePerPixelPerDimension.push_back( sizePerPixel / output->GetSpacing()[i] ); + } + + // Compute the max the index on the border of the image + IndexType borderMin = output->GetLargestPossibleRegion().GetIndex(); + IndexType borderMax = borderMin; + for( int i=0; i<ImageDimension; i++ ) + { + borderMax[i] += output->GetLargestPossibleRegion().GetSize()[i] - 1; + } + + // Init the vars + unsigned long size = 0; + ContinuousIndex< double, ImageDimension> centroid; + centroid.Fill( 0 ); + IndexType mins; + mins.Fill( NumericTraits< long >::max() ); + IndexType maxs; + maxs.Fill( NumericTraits< long >::NonpositiveMin() ); + unsigned long sizeOnBorder = 0; + double physicalSizeOnBorder = 0; + MatrixType centralMoments; + centralMoments.Fill( 0 ); + + typename LabelObjectType::LineContainerType::const_iterator lit; + typename LabelObjectType::LineContainerType & lineContainer = labelObject->GetLineContainer(); + + // Iterate over all the lines + for( lit = lineContainer.begin(); lit != lineContainer.end(); lit++ ) + { + const IndexType & idx = lit->GetIndex(); + unsigned long length = lit->GetLength(); + + // Update the size + size += length; + + // Update the centroid - and report the progress + // First, update the axes that are not 0 + for( int i=1; i<ImageDimension; i++ ) + { + centroid[i] += length * idx[i]; + } + // Then, update the axis 0 + centroid[0] += idx[0] * length + ( length * ( length - 1 ) ) / 2.0; + + // Update the mins and maxs + for( int i=0; i<ImageDimension; i++) + { + if( idx[i] < mins[i] ) + { + mins[i] = idx[i]; + } + if( idx[i] > maxs[i] ) + { + maxs[i] = idx[i]; + } + } + // Must fix the max for the axis 0 + if( idx[0] + (long)length > maxs[0] ) + { + maxs[0] = idx[0] + length - 1; + } + + // Object is on a border ? + bool isOnBorder = false; + for( int i=1; i<ImageDimension; i++) + { + if( idx[i] == borderMin[i] || idx[i] == borderMax[i]) + { + isOnBorder = true; + break; + } + } + if( isOnBorder ) + { + // The line touch a border on a dimension other than 0, so + // all the line touch a border + sizeOnBorder += length; + } + else + { + // We must check for the dimension 0 + bool isOnBorder0 = false; + if( idx[0] == borderMin[0] ) + { + // One more pixel on the border + sizeOnBorder++; + isOnBorder0 = true; + } + if( !isOnBorder0 || length > 1 ) + { + // We can check for the end of the line + if( idx[0] + (long)length - 1 == borderMax[0] ) + { + // One more pixel on the border + sizeOnBorder++; + } + } + } + + // Physical size on border + // First, the dimension 0 + if( idx[0] == borderMin[0] ) + { + // Fhe beginning of the line + physicalSizeOnBorder += sizePerPixelPerDimension[0]; + } + if( idx[0] + (long)length - 1 == borderMax[0] ) + { + // And the end of the line + physicalSizeOnBorder += sizePerPixelPerDimension[0]; + } + // Then the other dimensions + for( int i=1; i<ImageDimension; i++ ) + { + if( idx[i] == borderMin[i] ) + { + // one border + physicalSizeOnBorder += sizePerPixelPerDimension[i] * length; + } + if( idx[i] == borderMax[i] ) + { + // and the other + physicalSizeOnBorder += sizePerPixelPerDimension[i] * length; + } + } + + // moments computation +// **************************************************************** +// that commented code is the basic implementation. The next peace of code +// give the same result in a much efficient way, by using expended formulae +// allowed by the binary case instead of loops. +// **************************************************************** +// long endIdx0 = idx[0] + length; +// for( IndexType iidx = idx; iidx[0]<endIdx0; iidx[0]++) +// { +// typename LabelObjectType::CentroidType pP; +// output->TransformIndexToPhysicalPoint(iidx, pP); +// +// for(unsigned int i=0; i<ImageDimension; i++) +// { +// for(unsigned int j=0; j<ImageDimension; j++) +// { +// centralMoments[i][j] += pP[i] * pP[j]; +// } +// } +// } + // get the physical position and the spacing - they are used several times later + typename LabelObjectType::CentroidType physicalPosition; + output->TransformIndexToPhysicalPoint( idx, physicalPosition ); + const typename ImageType::SpacingType & spacing = output->GetSpacing(); + // the sum of x positions, also reused several times + double sumX = length * ( physicalPosition[0] + ( spacing[0] * ( length - 1 ) ) / 2.0 ); + // the real job - the sum of square of x positions + // that's the central moments for dims 0, 0 + centralMoments[0][0] += length * ( physicalPosition[0] * physicalPosition[0] + + spacing[0] * ( length - 1 ) * ( ( spacing[0] * ( 2 * length - 1 ) ) / 6.0 + physicalPosition[0] ) ); + // the other ones + for( int i = 1; i < ImageDimension; i++ ) + { + // do this one here to avoid the double assigment in the following loop + // when i == j + centralMoments[i][i] += length * physicalPosition[i] * physicalPosition[i]; + // central moments are symetrics, so avoid to compute them 2 times + for( int j = i + 1; j < ImageDimension; j++ ) + { + // note that we won't use that code if the image dimension is less than 3 + // --> the tests should be in 3D at least + double cm = length * physicalPosition[i] * physicalPosition[j]; + centralMoments[i][j] += cm; + centralMoments[j][i] += cm; + } + // the last moments: the ones for the dimension 0 + double cm = sumX * physicalPosition[i]; + centralMoments[i][0] += cm; + centralMoments[0][i] += cm; + } + + } + + // final computation + typename LabelObjectType::RegionType::SizeType regionSize; + double minSize = NumericTraits< double >::max(); + double maxSize = NumericTraits< double >::NonpositiveMin(); + for( int i = 0; i < ImageDimension; i++ ) + { + centroid[i] /= size; + regionSize[i] = maxs[i] - mins[i] + 1; + double s = regionSize[i] * output->GetSpacing()[i]; + minSize = vnl_math_min( s, minSize ); + maxSize = vnl_math_max( s, maxSize ); + for(unsigned int j = 0; j<ImageDimension; j++) + { + centralMoments[i][j] /= size; + } + } + typename LabelObjectType::RegionType region( mins, regionSize ); + typename LabelObjectType::CentroidType physicalCentroid; + output->TransformContinuousIndexToPhysicalPoint( centroid, physicalCentroid ); + + // Center the second order moments + for(unsigned int i=0; i<ImageDimension; i++) + { + for(unsigned int j=0; j<ImageDimension; j++) + { + centralMoments[i][j] -= physicalCentroid[i] * physicalCentroid[j]; + } + } + + // Compute principal moments and axes + VectorType principalMoments; + vnl_symmetric_eigensystem<double> eigen( centralMoments.GetVnlMatrix() ); + vnl_diag_matrix<double> pm = eigen.D; + for(unsigned int i=0; i<ImageDimension; i++) + { + principalMoments[i] = pm(i,i); + } + MatrixType principalAxes = eigen.V.transpose(); + + // Add a final reflection if needed for a proper rotation, + // by multiplying the last row by the determinant + vnl_real_eigensystem eigenrot( principalAxes.GetVnlMatrix() ); + vnl_diag_matrix< vcl_complex<double> > eigenval = eigenrot.D; + vcl_complex<double> det( 1.0, 0.0 ); + + for(unsigned int i=0; i<ImageDimension; i++) + { + det *= eigenval( i, i ); + } + + for(unsigned int i=0; i<ImageDimension; i++) + { + principalAxes[ ImageDimension-1 ][i] *= std::real( det ); + } + + double elongation = 0; + double flatness = 0; + if( ImageDimension < 2 ) + { + elongation = 1; + flatness = 1; + } + else if( principalMoments[0] != 0 ) + { + elongation = vcl_sqrt(principalMoments[ImageDimension-1] / principalMoments[ImageDimension-2]); + flatness = vcl_sqrt(principalMoments[1] / principalMoments[0]); + } + + double physicalSize = size * sizePerPixel; + double equivalentRadius = HyperSphereRadiusFromVolume( physicalSize ); + double equivalentPerimeter = HyperSpherePerimeter( equivalentRadius ); + + // Compute equivalent ellipsoid radius + VectorType ellipsoidSize; + double edet = 1.0; + for(unsigned int i = 0; i < ImageDimension; i++) + { + edet *= principalMoments[i]; + } + edet = vcl_pow( edet, 1.0/ImageDimension ); + for(unsigned int i = 0; i < ImageDimension; i++) + { + if (edet != 0.0) + { + ellipsoidSize[i] = 2.0 * equivalentRadius * vcl_sqrt( principalMoments[i] / edet ); + } + else + { + ellipsoidSize[i] = 0.0; + } + } + + // Set the values in the object + labelObject->SetSize( size ); + labelObject->SetPhysicalSize( physicalSize ); + labelObject->SetRegion( region ); + labelObject->SetCentroid( physicalCentroid ); + if (minSize != 0) + { + labelObject->SetRegionElongation( maxSize / minSize ); + } + if (region.GetNumberOfPixels() != 0) + { + labelObject->SetSizeRegionRatio( size / (double)region.GetNumberOfPixels() ); + } + labelObject->SetSizeOnBorder( sizeOnBorder ); + labelObject->SetPhysicalSizeOnBorder( physicalSizeOnBorder ); + labelObject->SetBinaryPrincipalMoments( principalMoments ); + labelObject->SetBinaryPrincipalAxes( principalAxes ); + labelObject->SetBinaryElongation( elongation ); + labelObject->SetEquivalentRadius( equivalentRadius ); + labelObject->SetEquivalentPerimeter( equivalentPerimeter ); + labelObject->SetEquivalentEllipsoidSize( ellipsoidSize ); + labelObject->SetBinaryFlatness( flatness ); + + if( m_ComputeFeretDiameter ) + { + this->ComputeFeretDiameter( labelObject ); + } + + // Be sure that the calculator has the perimeter estimation for that label. + // The calculator may not have the label if the object is only on a border. + // It will occurre for sure when processing a 2D image with a 3D filter. + if( m_ComputePerimeter && m_PerimeterCalculator->HasLabel( label ) ) + { + double perimeter = m_PerimeterCalculator->GetPerimeter( label ); + labelObject->SetPerimeter( perimeter ); + labelObject->SetRoundness( equivalentPerimeter / perimeter ); + } +} + + +template<class TImage, class TLabelImage> +void +ShapeLabelMapFilter<TImage, TLabelImage> +::ComputeFeretDiameter( LabelObjectType * labelObject ) +{ + const LabelPixelType & label = labelObject->GetLabel(); + + typedef typename std::deque< IndexType > IndexListType; + IndexListType idxList; + + // the iterators + typename LabelObjectType::LineContainerType::const_iterator lit; + typename LabelObjectType::LineContainerType & lineContainer = labelObject->GetLineContainer(); + + typedef typename itk::ConstNeighborhoodIterator< LabelImageType > NeighborIteratorType; + SizeType neighborHoodRadius; + neighborHoodRadius.Fill( 1 ); + NeighborIteratorType it( neighborHoodRadius, m_LabelImage, m_LabelImage->GetBufferedRegion() ); + ConstantBoundaryCondition<LabelImageType> lcbc; + // Use label + 1 to have a label different of the current label on the border + lcbc.SetConstant( label + 1 ); + it.OverrideBoundaryCondition( &lcbc ); + it.GoToBegin(); + + // Iterate over all the lines + for( lit = lineContainer.begin(); lit != lineContainer.end(); lit++ ) + { + const IndexType & firstIdx = lit->GetIndex(); + unsigned long length = lit->GetLength(); + + long endIdx0 = firstIdx[0] + length; + for( IndexType idx = firstIdx; idx[0]<endIdx0; idx[0]++) + { + + // Move the iterator to the new location + it += idx - it.GetIndex(); + + // Push the pixel in the list if it is on the border of the object + for (unsigned i = 0; i < it.Size(); i++) + { + if( it.GetPixel(i) != label ) + { + idxList.push_back( idx ); + break; + } + } + } + } + + ImageType * output = this->GetOutput(); + + const typename ImageType::SpacingType & spacing = output->GetSpacing(); + + typedef typename ImageType::OffsetValueType OffsetValueType; + + // We can now search the feret diameter + double feretDiameter = 0; + for( typename IndexListType::const_iterator iIt1 = idxList.begin(); + iIt1 != idxList.end(); + iIt1++ ) + { + typename IndexListType::const_iterator iIt2 = iIt1; + for( iIt2++; iIt2 != idxList.end(); iIt2++ ) + { + // Compute the length between the 2 indexes + double length = 0; + for( int i = 0; i<ImageDimension; i++ ) + { + const OffsetValueType indexDifference = ( iIt1->operator[]( i ) - iIt2->operator[]( i ) ); + length += vcl_pow( indexDifference * spacing[i], 2 ); + } + if( feretDiameter < length ) + { + feretDiameter = length; + } + } + } + // Final computation + feretDiameter = vcl_sqrt( feretDiameter ); + + // Finally put the values in the label object + labelObject->SetFeretDiameter( feretDiameter ); +} + +template<class TImage, class TLabelImage> +void +ShapeLabelMapFilter<TImage, TLabelImage> +::AfterThreadedGenerateData() +{ + Superclass::AfterThreadedGenerateData(); + + // Release the label image + m_LabelImage = NULL; + // and the perimeter calculator + m_PerimeterCalculator = NULL; +} + + +template<class TImage, class TLabelImage> +void +ShapeLabelMapFilter<TImage, TLabelImage> +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "ComputeFeretDiameter: " << m_ComputeFeretDiameter << std::endl; + os << indent << "ComputePerimeter: " << m_ComputePerimeter << std::endl; +} + + +template<class TImage, class TLabelImage> +long +ShapeLabelMapFilter<TImage, TLabelImage> +::Factorial( long n ) +{ + if( n < 1 ) + { + return 1; + } + return n * Factorial( n - 1 ); +} + + +template<class TImage, class TLabelImage> +long +ShapeLabelMapFilter<TImage, TLabelImage> +::DoubleFactorial( long n ) +{ + if( n < 2 ) + { + return 1; + } + return n * DoubleFactorial( n - 2 ); +} + + +template<class TImage, class TLabelImage> +double +ShapeLabelMapFilter<TImage, TLabelImage> +::GammaN2p1( long n ) +{ + bool even = n % 2 == 0; + if( even ) + { + return Factorial( n / 2 ); + } + else + { + return vcl_sqrt( vnl_math::pi ) * DoubleFactorial( n ) / vcl_pow( 2, ( n + 1 ) / 2.0 ); + } +} + + +template<class TImage, class TLabelImage> +double +ShapeLabelMapFilter<TImage, TLabelImage> +::HyperSphereVolume( double radius ) +{ + return vcl_pow( vnl_math::pi, ImageDimension / 2.0 ) * vcl_pow( radius, ImageDimension ) / GammaN2p1( ImageDimension ); +} + + +template<class TImage, class TLabelImage> +double +ShapeLabelMapFilter<TImage, TLabelImage> +::HyperSpherePerimeter( double radius ) +{ + return ImageDimension * HyperSphereVolume( radius ) / radius; +} + + +template<class TImage, class TLabelImage> +double +ShapeLabelMapFilter<TImage, TLabelImage> +::HyperSphereRadiusFromVolume( double volume ) +{ + return vcl_pow( volume * GammaN2p1( ImageDimension ) / vcl_pow( vnl_math::pi, ImageDimension / 2.0 ), 1.0 / ImageDimension ); +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkShapeLabelObject.h b/Utilities/ITK/Code/Review/itkShapeLabelObject.h new file mode 100644 index 0000000000000000000000000000000000000000..1ad155619e0e66d3ceb66ed895649aac7ef68cec --- /dev/null +++ b/Utilities/ITK/Code/Review/itkShapeLabelObject.h @@ -0,0 +1,584 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkShapeLabelObject.h,v $ + Language: C++ + Date: $Date: 2009-08-11 14:24:44 $ + Version: $Revision: 1.5 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkShapeLabelObject_h +#define __itkShapeLabelObject_h + +#include "itkLabelObject.h" +#include "itkLabelMap.h" +#include "itkAffineTransform.h" +#include "itkMatrix.h" + +namespace itk +{ + +/** \class ShapeLabelObject + * \brief A Label object to store the common attributes related to the shape of the object + * + * ShapeLabelObject stores the common attributes related to the shape of the object + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \ingroup DataRepresentation + */ +template < class TLabel, unsigned int VImageDimension > +class ITK_EXPORT ShapeLabelObject : public LabelObject< TLabel, VImageDimension > +{ +public: + /** Standard class typedefs */ + typedef ShapeLabelObject Self; + typedef LabelObject< TLabel, VImageDimension > Superclass; + typedef typename Superclass::LabelObjectType LabelObjectType; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + typedef WeakPointer<const Self> ConstWeakPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(ShapeLabelObject, LabelObject); + + typedef LabelMap< Self > LabelMapType; + + itkStaticConstMacro(ImageDimension, unsigned int, VImageDimension); + + typedef typename Superclass::IndexType IndexType; + + typedef TLabel LabelType; + + typedef typename Superclass::LineType LineType; + + typedef typename Superclass::LengthType LengthType; + + typedef typename Superclass::LineContainerType LineContainerType; + + typedef typename Superclass::AttributeType AttributeType; + itkStaticConstMacro(SIZE, AttributeType, 100); + itkStaticConstMacro(PHYSICAL_SIZE, AttributeType, 101); + itkStaticConstMacro(REGION_ELONGATION, AttributeType, 102); + itkStaticConstMacro(SIZE_REGION_RATIO, AttributeType, 103); + itkStaticConstMacro(CENTROID, AttributeType, 104); + itkStaticConstMacro(REGION, AttributeType, 105); + itkStaticConstMacro(SIZE_ON_BORDER, AttributeType, 106); + itkStaticConstMacro(PHYSICAL_SIZE_ON_BORDER, AttributeType, 107); + itkStaticConstMacro(FERET_DIAMETER, AttributeType, 108); + itkStaticConstMacro(BINARY_PRINCIPAL_MOMENTS, AttributeType, 109); + itkStaticConstMacro(BINARY_PRINCIPAL_AXES, AttributeType, 110); + itkStaticConstMacro(BINARY_ELONGATION, AttributeType, 111); + itkStaticConstMacro(PERIMETER, AttributeType, 112); + itkStaticConstMacro(ROUNDNESS, AttributeType, 113); + itkStaticConstMacro(EQUIVALENT_RADIUS, AttributeType, 114); + itkStaticConstMacro(EQUIVALENT_PERIMETER, AttributeType, 115); + itkStaticConstMacro(EQUIVALENT_ELLIPSOID_RADIUS, AttributeType, 116); + itkStaticConstMacro(BINARY_FLATNESS, AttributeType, 117); + + static AttributeType GetAttributeFromName( const std::string & s ) + { + if( s == "Size" ) + { + return SIZE; + } + else if( s == "PhysicalSize" ) + { + return PHYSICAL_SIZE; + } + else if( s == "RegionElongation" ) + { + return REGION_ELONGATION; + } + else if( s == "SizeRegionRatio" ) + { + return SIZE_REGION_RATIO; + } + else if( s == "Centroid" ) + { + return CENTROID; + } + else if( s == "Region" ) + { + return REGION; + } + else if( s == "SizeOnBorder" ) + { + return SIZE_ON_BORDER; + } + else if( s == "PhysicalSizeOnBorder" ) + { + return PHYSICAL_SIZE_ON_BORDER; + } + else if( s == "FeretDiameter" ) + { + return FERET_DIAMETER; + } + else if( s == "BinaryPrincipalMoments" ) + { + return BINARY_PRINCIPAL_MOMENTS; + } + else if( s == "BinaryPrincipalAxes" ) + { + return BINARY_PRINCIPAL_AXES; + } + else if( s == "BinaryElongation" ) + { + return BINARY_ELONGATION; + } + else if( s == "Perimeter" ) + { + return PERIMETER; + } + else if( s == "Roundness" ) + { + return ROUNDNESS; + } + else if( s == "EquivalentRadius" ) + { + return EQUIVALENT_RADIUS; + } + else if( s == "EquivalentPerimeter" ) + { + return EQUIVALENT_PERIMETER; + } + else if( s == "EquivalentEllipsoidSize" ) + { + return EQUIVALENT_ELLIPSOID_RADIUS; + } + else if( s == "BinaryFlatness" ) + { + return BINARY_FLATNESS; + } + // can't recognize the name + return Superclass::GetAttributeFromName( s ); + } + + static std::string GetNameFromAttribute( const AttributeType & a ) + { + switch( a ) + { + case SIZE: + return "Size"; + break; + case PHYSICAL_SIZE: + return "PhysicalSize"; + break; + case REGION_ELONGATION: + return "RegionElongation"; + break; + case SIZE_REGION_RATIO: + return "SizeRegionRatio"; + break; + case CENTROID: + return "Centroid"; + case REGION: + return "Region"; + break; + case SIZE_ON_BORDER: + return "SizeOnBorder"; + break; + case PHYSICAL_SIZE_ON_BORDER: + return "PhysicalSizeOnBorder"; + break; + case FERET_DIAMETER: + return "FeretDiameter"; + break; + case BINARY_PRINCIPAL_MOMENTS: + return "BinaryPrincipalMoments"; + break; + case BINARY_PRINCIPAL_AXES: + return "BinaryPrincipalAxes"; + break; + case BINARY_ELONGATION: + return "BinaryElongation"; + break; + case PERIMETER: + return "Perimeter"; + break; + case ROUNDNESS: + return "Roundness"; + break; + case EQUIVALENT_RADIUS: + return "EquivalentRadius"; + break; + case EQUIVALENT_PERIMETER: + return "EquivalentPerimeter"; + break; + case EQUIVALENT_ELLIPSOID_RADIUS: + return "EquivalentEllipsoidSize"; + break; + case BINARY_FLATNESS: + return "BinaryFlatness"; + break; + } + // can't recognize the name + return Superclass::GetNameFromAttribute( a ); + } + + typedef ImageRegion< VImageDimension > RegionType; + + typedef Point<double, VImageDimension> CentroidType; + + typedef Matrix< double, VImageDimension, VImageDimension > MatrixType; + + typedef Vector< double, VImageDimension > VectorType; + + const RegionType & GetRegion() const + { + return m_Region; + } + + void SetRegion( const RegionType & v ) + { + m_Region = v; + } + + const double & GetPhysicalSize() const + { + return m_PhysicalSize; + } + + void SetPhysicalSize( const double & v ) + { + m_PhysicalSize = v; + } + + const unsigned long & GetSize() const + { + return m_Size; + } + + void SetSize( const unsigned long & v ) + { + m_Size = v; + } + + const CentroidType & GetCentroid() const + { + return m_Centroid; + } + + void SetCentroid( const CentroidType & centroid ) + { + m_Centroid = centroid; + } + + const double & GetRegionElongation() const + { + return m_RegionElongation; + } + + void SetRegionElongation( const double & v ) + { + m_RegionElongation = v; + } + + const double & GetSizeRegionRatio() const + { + return m_SizeRegionRatio; + } + + void SetSizeRegionRatio( const double & v ) + { + m_SizeRegionRatio = v; + } + + const unsigned long & GetSizeOnBorder() const + { + return m_SizeOnBorder; + } + + void SetSizeOnBorder( const unsigned long & v ) + { + m_SizeOnBorder = v; + } + + const double & GetPhysicalSizeOnBorder() const + { + return m_PhysicalSizeOnBorder; + } + + void SetPhysicalSizeOnBorder( const double & v ) + { + m_PhysicalSizeOnBorder = v; + } + + const double & GetFeretDiameter() const + { + return m_FeretDiameter; + } + + void SetFeretDiameter( const double & v ) + { + m_FeretDiameter = v; + } + + const VectorType & GetBinaryPrincipalMoments() const + { + return m_BinaryPrincipalMoments; + } + + void SetBinaryPrincipalMoments( const VectorType & v ) + { + m_BinaryPrincipalMoments = v; + } + + const MatrixType & GetBinaryPrincipalAxes() const + { + return m_BinaryPrincipalAxes; + } + + void SetBinaryPrincipalAxes( const MatrixType & v ) + { + m_BinaryPrincipalAxes = v; + } + + const double & GetBinaryElongation() const + { + return m_BinaryElongation; + } + + void SetBinaryElongation( const double & v ) + { + m_BinaryElongation = v; + } + + const double & GetPerimeter() const + { + return m_Perimeter; + } + + void SetPerimeter( const double & v ) + { + m_Perimeter = v; + } + + const double & GetRoundness() const + { + return m_Roundness; + } + + void SetRoundness( const double & v ) + { + m_Roundness = v; + } + + const double & GetEquivalentRadius() const + { + return m_EquivalentRadius; + } + + void SetEquivalentRadius( const double & v ) + { + m_EquivalentRadius = v; + } + + const double & GetEquivalentPerimeter() const + { + return m_EquivalentPerimeter; + } + + void SetEquivalentPerimeter( const double & v ) + { + m_EquivalentPerimeter = v; + } + + const VectorType & GetEquivalentEllipsoidSize() const + { + return m_EquivalentEllipsoidSize; + } + + void SetEquivalentEllipsoidSize( const VectorType & v ) + { + m_EquivalentEllipsoidSize = v; + } + + const double & GetBinaryFlatness() const + { + return m_BinaryFlatness; + } + + void SetBinaryFlatness( const double & v ) + { + m_BinaryFlatness = v; + } + + + // some helper methods - not really required, but really useful! + + /** Affine transform for mapping to and from principal axis */ + typedef AffineTransform<double,VImageDimension> AffineTransformType; + typedef typename AffineTransformType::Pointer AffineTransformPointer; + + /** Get the affine transform from principal axes to physical axes + * This method returns an affine transform which transforms from + * the principal axes coordinate system to physical coordinates. */ + AffineTransformPointer GetBinaryPrincipalAxesToPhysicalAxesTransform() const + { + typename AffineTransformType::MatrixType matrix; + typename AffineTransformType::OffsetType offset; + for (unsigned int i = 0; i < VImageDimension; i++) + { + offset[i] = m_Centroid[i]; + for (unsigned int j = 0; j < VImageDimension; j++) + { + matrix[j][i] = m_BinaryPrincipalAxes[i][j]; // Note the transposition + } + } + + AffineTransformPointer result = AffineTransformType::New(); + + result->SetMatrix(matrix); + result->SetOffset(offset); + + return result; + } + + /** Get the affine transform from physical axes to principal axes + * This method returns an affine transform which transforms from + * the physical coordinate system to the principal axes coordinate + * system. */ + AffineTransformPointer GetPhysicalAxesToBinaryPrincipalAxesTransform(void) const + { + typename AffineTransformType::MatrixType matrix; + typename AffineTransformType::OffsetType offset; + for (unsigned int i = 0; i < VImageDimension; i++) + { + offset[i] = m_Centroid[i]; + for (unsigned int j = 0; j < VImageDimension; j++) + { + matrix[j][i] = m_BinaryPrincipalAxes[i][j]; // Note the transposition + } + } + + AffineTransformPointer result = AffineTransformType::New(); + result->SetMatrix(matrix); + result->SetOffset(offset); + + AffineTransformPointer inverse = AffineTransformType::New(); + result->GetInverse(inverse); + + return inverse; + } + + + virtual void CopyAttributesFrom( const LabelObjectType * lo ) + { + Superclass::CopyAttributesFrom( lo ); + + // copy the data of the current type if possible + const Self * src = dynamic_cast<const Self *>( lo ); + if( src == NULL ) + { + return; + } + m_Region = src->m_Region; + m_Size = src->m_Size; + m_PhysicalSize = src->m_PhysicalSize; + m_Centroid = src->m_Centroid; + m_RegionElongation = src->m_RegionElongation; + m_SizeRegionRatio = src->m_SizeRegionRatio; + m_SizeOnBorder = src->m_SizeOnBorder; + m_PhysicalSizeOnBorder = src->m_PhysicalSizeOnBorder; + m_FeretDiameter = src->m_FeretDiameter; + m_BinaryPrincipalMoments = src->m_BinaryPrincipalMoments; + m_BinaryPrincipalAxes = src->m_BinaryPrincipalAxes; + m_BinaryElongation = src->m_BinaryElongation; + m_Perimeter = src->m_Perimeter; + m_Roundness = src->m_Roundness; + m_EquivalentRadius = src->m_EquivalentRadius; + m_EquivalentPerimeter = src->m_EquivalentPerimeter; + m_EquivalentEllipsoidSize = src->m_EquivalentEllipsoidSize; + m_BinaryFlatness = src->m_BinaryFlatness; + } + +protected: + ShapeLabelObject() + { + m_Size = 0; + m_PhysicalSize = 0; + m_Centroid.Fill(0); + m_RegionElongation = 0; + m_SizeRegionRatio = 0; + m_SizeOnBorder = false; + m_PhysicalSizeOnBorder = 0; + m_FeretDiameter = false; + m_BinaryPrincipalMoments.Fill(0); + m_BinaryPrincipalAxes.Fill(0); + m_BinaryElongation = 0; + m_Perimeter = 0; + m_Roundness = 0; + m_EquivalentRadius = 0; + m_EquivalentPerimeter = 0; + m_EquivalentEllipsoidSize.Fill(0); + m_BinaryFlatness = 0; + } + + void PrintSelf(std::ostream& os, Indent indent) const + { + Superclass::PrintSelf( os, indent ); + + os << indent << "Centroid: " << m_Centroid << std::endl; + os << indent << "Region: "; + m_Region.Print( os, indent ); + os << indent << "PhysicalSize: " << m_PhysicalSize << std::endl; + os << indent << "Size: " << m_Size << std::endl; + os << indent << "RegionElongation: " << m_RegionElongation << std::endl; + os << indent << "SizeRegionRatio: " << m_SizeRegionRatio << std::endl; + os << indent << "SizeOnBorder: " << m_SizeOnBorder << std::endl; + os << indent << "PhysicalSizeOnBorder: " << m_PhysicalSizeOnBorder << std::endl; + os << indent << "FeretDiameter: " << m_FeretDiameter << std::endl; + os << indent << "BinaryPrincipalMoments: " << m_BinaryPrincipalMoments << std::endl; + os << indent << "BinaryPrincipalAxes: " << std::endl << m_BinaryPrincipalAxes; + os << indent << "BinaryElongation: " << m_BinaryElongation << std::endl; + os << indent << "Perimeter: " << m_Perimeter << std::endl; + os << indent << "Roundness: " << m_Roundness << std::endl; + os << indent << "EquivalentRadius: " << m_EquivalentRadius << std::endl; + os << indent << "EquivalentPerimeter: " << m_EquivalentPerimeter << std::endl; + os << indent << "EquivalentEllipsoidSize: " << m_EquivalentEllipsoidSize << std::endl; + os << indent << "BinaryFlatness: " << m_BinaryElongation << std::endl; + } + +private: + ShapeLabelObject(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + RegionType m_Region; + unsigned long m_Size; + double m_PhysicalSize; + CentroidType m_Centroid; + double m_RegionElongation; + double m_SizeRegionRatio; + unsigned long m_SizeOnBorder; + double m_PhysicalSizeOnBorder; + double m_FeretDiameter; + VectorType m_BinaryPrincipalMoments; + MatrixType m_BinaryPrincipalAxes; + double m_BinaryElongation; + double m_Perimeter; + double m_Roundness; + double m_EquivalentRadius; + double m_EquivalentPerimeter; + VectorType m_EquivalentEllipsoidSize; + double m_BinaryFlatness; + +}; + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkShapeLabelObjectAccessors.h b/Utilities/ITK/Code/Review/itkShapeLabelObjectAccessors.h new file mode 100644 index 0000000000000000000000000000000000000000..c5b94fbecaca4c686eaaba2fd1ea3778b4f6837d --- /dev/null +++ b/Utilities/ITK/Code/Review/itkShapeLabelObjectAccessors.h @@ -0,0 +1,266 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkShapeLabelObjectAccessors.h,v $ + Language: C++ + Date: $Date: 2009-08-09 11:26:48 $ + Version: $Revision: 1.5 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkShapeLabelObjectAccessors_h +#define __itkShapeLabelObjectAccessors_h +#include "itkLabelObjectAccessors.h" + + +namespace itk +{ + +namespace Functor +{ + +template< class TLabelObject > +class ITK_EXPORT SizeLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef unsigned long AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetSize(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT RegionLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef typename LabelObjectType::RegionType AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetRegion(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT PhysicalSizeLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetPhysicalSize(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT RegionElongationLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetRegionElongation(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT SizeRegionRatioLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetSizeRegionRatio(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT SizeOnBorderLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef unsigned long AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetSizeOnBorder(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT PhysicalSizeOnBorderLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetPhysicalSizeOnBorder(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT CentroidLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef typename LabelObjectType::CentroidType AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetCentroid(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT FeretDiameterLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetFeretDiameter(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT BinaryPrincipalMomentsLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef typename LabelObjectType::VectorType AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetBinaryPrincipalMoments(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT BinaryPrincipalAxesLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef typename LabelObjectType::MatrixType AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetBinaryPrincipalAxes(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT BinaryElongationLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetBinaryElongation(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT PerimeterLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetPerimeter(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT RoundnessLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetRoundness(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT EquivalentRadiusLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetEquivalentRadius(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT EquivalentPerimeterLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetEquivalentPerimeter(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT EquivalentEllipsoidSizeLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef typename LabelObjectType::VectorType AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetEquivalentEllipsoidSize(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT BinaryFlatnessLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetBinaryFlatness(); + } +}; + +} + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkShapeOpeningLabelMapFilter.h b/Utilities/ITK/Code/Review/itkShapeOpeningLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..a08046a2bb8bc9dd7397d4834f97406cbbf3a14d --- /dev/null +++ b/Utilities/ITK/Code/Review/itkShapeOpeningLabelMapFilter.h @@ -0,0 +1,176 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkShapeOpeningLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-05 15:52:35 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkShapeOpeningLabelMapFilter_h +#define __itkShapeOpeningLabelMapFilter_h + +#include "itkInPlaceLabelMapFilter.h" +#include "itkLabelObjectAccessors.h" +#include "itkShapeLabelObjectAccessors.h" +#include "itkProgressReporter.h" + +namespace itk { +/** \class ShapeOpeningLabelMapFilter + * \brief Remove objects according to the value of their shape attribute. + * + * ShapeOpeningLabelMapFilter removes objects in a label collection image + * with an attribute value smaller or greater than a threshold called Lambda. + * The attributes are those of the ShapeLabelObject. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * \sa ShapeLabelObject, BinaryShapeOpeningImageFilter, LabelStatisticsOpeningImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TImage> +class ITK_EXPORT ShapeOpeningLabelMapFilter : + public InPlaceLabelMapFilter<TImage> +{ +public: + /** Standard class typedefs. */ + typedef ShapeOpeningLabelMapFilter Self; + typedef InPlaceLabelMapFilter<TImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TImage ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::LabelObjectType LabelObjectType; + + typedef typename LabelObjectType::AttributeType AttributeType; + + /** ImageDimension constants */ + itkStaticConstMacro(ImageDimension, unsigned int, TImage::ImageDimension); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(ShapeOpeningLabelMapFilter, InPlaceLabelMapFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ +/* itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>));*/ + /** End concept checking */ +#endif + + /** + * Set/Get the threshold used to keep or remove the objects. + */ + itkGetConstMacro(Lambda, double); + itkSetMacro(Lambda, double); + + /** + * Set/Get the ordering of the objects. By default, objects with + * an attribute value smaller than Lamba are removed. Turning ReverseOrdering + * to true makes this filter remove objects with an attribute value greater + * than Lambda instead. + */ + itkGetConstMacro( ReverseOrdering, bool ); + itkSetMacro( ReverseOrdering, bool ); + itkBooleanMacro( ReverseOrdering ); + + /** + * Set/Get the attribute to use to select the object to remove. + * The default is "Size". + */ + itkGetConstMacro( Attribute, AttributeType ); + itkSetMacro( Attribute, AttributeType ); + void SetAttribute( const std::string & s ) + { + this->SetAttribute( LabelObjectType::GetAttributeFromName( s ) ); + } + + +protected: + ShapeOpeningLabelMapFilter(); + ~ShapeOpeningLabelMapFilter() {}; + + void GenerateData(); + + template <class TAttributeAccessor> + void TemplatedGenerateData( const TAttributeAccessor & accessor ) + { + // Allocate the output + this->AllocateOutputs(); + + ImageType * output = this->GetOutput(); + ImageType * output2 = this->GetOutput( 1 ); + assert( this->GetNumberOfOutputs() == 2 ); + assert( output2 != NULL ); + + // set the background value for the second output - this is not done in the superclasses + output2->SetBackgroundValue( output->GetBackgroundValue() ); + + const typename ImageType::LabelObjectContainerType & labelObjectContainer = output->GetLabelObjectContainer(); + + ProgressReporter progress( this, 0, labelObjectContainer.size() ); + + typename ImageType::LabelObjectContainerType::const_iterator it = labelObjectContainer.begin(); + while( it != labelObjectContainer.end() ) + { + typename LabelObjectType::LabelType label = it->first; + LabelObjectType * labelObject = it->second; + + if( ( !m_ReverseOrdering && accessor( labelObject ) < m_Lambda ) + || ( m_ReverseOrdering && accessor( labelObject ) > m_Lambda ) ) + { + // must increment the iterator before removing the object to avoid invalidating the iterator + it++; + output2->AddLabelObject( labelObject ); + output->RemoveLabel( label ); + } + else + { + it++; + } + + progress.CompletedPixel(); + } + } + + void PrintSelf(std::ostream& os, Indent indent) const; + + double m_Lambda; + bool m_ReverseOrdering; + AttributeType m_Attribute; + +private: + ShapeOpeningLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkShapeOpeningLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkShapeOpeningLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkShapeOpeningLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..c1a7533cfa5a8cdd5eb41f33bb05a3ffcfc1c8a9 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkShapeOpeningLabelMapFilter.txx @@ -0,0 +1,163 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkShapeOpeningLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-04 21:32:07 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkShapeOpeningLabelMapFilter_txx +#define __itkShapeOpeningLabelMapFilter_txx + +#include "itkShapeOpeningLabelMapFilter.h" + + +namespace itk { + +template <class TImage> +ShapeOpeningLabelMapFilter<TImage> +::ShapeOpeningLabelMapFilter() +{ + m_Lambda = NumericTraits< double >::Zero; + m_ReverseOrdering = false; + m_Attribute = LabelObjectType::SIZE; + + // create the output image for the removed objects + this->SetNumberOfRequiredOutputs(2); + this->SetNthOutput( 1, static_cast<TImage*>( this->MakeOutput(1).GetPointer() ) ); +} + + +template <class TImage> +void +ShapeOpeningLabelMapFilter<TImage> +::GenerateData() +{ + switch( m_Attribute ) + { + case LabelObjectType::LABEL: + { + typedef typename Functor::LabelLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::SIZE: + { + typedef typename Functor::SizeLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::PHYSICAL_SIZE: + { + typedef typename Functor::PhysicalSizeLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::SIZE_REGION_RATIO: + { + typedef typename Functor::SizeRegionRatioLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::REGION_ELONGATION: + { + typedef typename Functor::RegionElongationLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::SIZE_ON_BORDER: + { + typedef typename Functor::SizeOnBorderLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::PHYSICAL_SIZE_ON_BORDER: + { + typedef typename Functor::PhysicalSizeOnBorderLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::FERET_DIAMETER: + { + typedef typename Functor::FeretDiameterLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::BINARY_ELONGATION: + { + typedef typename Functor::BinaryElongationLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::PERIMETER: + { + typedef typename Functor::PerimeterLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::ROUNDNESS: + { + typedef typename Functor::RoundnessLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::EQUIVALENT_RADIUS: + { + typedef typename Functor::EquivalentRadiusLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::EQUIVALENT_PERIMETER: + { + typedef typename Functor::EquivalentPerimeterLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::BINARY_FLATNESS: + { + typedef typename Functor::BinaryFlatnessLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + default: + itkExceptionMacro(<< "Unknown attribute type"); + break; + } +} + +template <class TImage> +void +ShapeOpeningLabelMapFilter<TImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "ReverseOrdering: " << m_ReverseOrdering << std::endl; + os << indent << "Lambda: " << m_Lambda << std::endl; + os << indent << "Attribute: " << LabelObjectType::GetNameFromAttribute( m_Attribute ) << " (" << m_Attribute << ")" << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkShapeRelabelImageFilter.h b/Utilities/ITK/Code/Review/itkShapeRelabelImageFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..fcfc54ad37b64d7eb231dd535fc93222b90e63ca --- /dev/null +++ b/Utilities/ITK/Code/Review/itkShapeRelabelImageFilter.h @@ -0,0 +1,164 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkShapeRelabelImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-08 01:21:23 $ + Version: $Revision: 1.4 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkShapeRelabelImageFilter_h +#define __itkShapeRelabelImageFilter_h + +#include "itkImageToImageFilter.h" +#include "itkShapeLabelObject.h" +#include "itkLabelMap.h" +#include "itkLabelImageToLabelMapFilter.h" +#include "itkShapeLabelMapFilter.h" +#include "itkShapeRelabelLabelMapFilter.h" +#include "itkLabelMapToLabelImageFilter.h" + + +namespace itk { + +/** \class ShapeRelabelImageFilter + * \brief relabel objects according to their shape attributes + * + * ShapeRelabelImageFilter relabel a labeled image according to the shape attributes of + * the objects. The label produced are always consecutives. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \sa ShapeLabelObject, RelabelComponentImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TInputImage> +class ITK_EXPORT ShapeRelabelImageFilter : + public ImageToImageFilter<TInputImage, TInputImage> +{ +public: + /** Standard class typedefs. */ + typedef ShapeRelabelImageFilter Self; + typedef ImageToImageFilter<TInputImage, TInputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef TInputImage OutputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::ConstPointer OutputImageConstPointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(ImageDimension, unsigned int, + TInputImage::ImageDimension); + + typedef ShapeLabelObject<InputImagePixelType, itkGetStaticConstMacro(ImageDimension)> LabelObjectType; + typedef LabelMap< LabelObjectType > LabelMapType; + typedef LabelImageToLabelMapFilter< InputImageType, LabelMapType > LabelizerType; + typedef Image< typename OutputImageType::PixelType, itkGetStaticConstMacro(OutputImageDimension)> + ShapeLabelFilterOutput; + typedef ShapeLabelMapFilter< LabelMapType, ShapeLabelFilterOutput > LabelObjectValuatorType; + typedef typename LabelObjectType::AttributeType AttributeType; + typedef ShapeRelabelLabelMapFilter< LabelMapType > RelabelType; + typedef LabelMapToLabelImageFilter< LabelMapType, OutputImageType > BinarizerType; + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(ShapeRelabelImageFilter, + ImageToImageFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>)); + /** End concept checking */ +#endif + + /** + * Set/Get the value used as "background" in the output image. + * Defaults to NumericTraits<PixelType>::NonpositiveMin(). + */ + itkSetMacro(BackgroundValue, OutputImagePixelType); + itkGetConstMacro(BackgroundValue, OutputImagePixelType); + + /** + * Set/Get the order of labeling of the objects. By default, the objects with + * the highest attribute values are labeled first. Set ReverseOrdering to true + * make the one with the smallest attributes be labeled first. + */ + itkGetConstMacro( ReverseOrdering, bool ); + itkSetMacro( ReverseOrdering, bool ); + itkBooleanMacro( ReverseOrdering ); + + /** + * Set/Get the attribute to use. Default is "Size". + */ + itkGetConstMacro( Attribute, AttributeType ); + itkSetMacro( Attribute, AttributeType ); + void SetAttribute( const std::string & s ) + { + this->SetAttribute( LabelObjectType::GetAttributeFromName( s ) ); + } + + +protected: + ShapeRelabelImageFilter(); + ~ShapeRelabelImageFilter() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + + /** ShapeRelabelImageFilter needs the entire input be + * available. Thus, it needs to provide an implementation of + * GenerateInputRequestedRegion(). */ + void GenerateInputRequestedRegion(); + + /** ShapeRelabelImageFilter will produce the entire output. */ + void EnlargeOutputRequestedRegion(DataObject *itkNotUsed(output)); + + /** Single-threaded version of GenerateData. This filter delegates + * to GrayscaleGeodesicErodeImageFilter. */ + void GenerateData(); + +private: + ShapeRelabelImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + OutputImagePixelType m_BackgroundValue; + bool m_ReverseOrdering; + AttributeType m_Attribute; +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkShapeRelabelImageFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkShapeRelabelImageFilter.txx b/Utilities/ITK/Code/Review/itkShapeRelabelImageFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..dcf713a7b22227ea3bb9fd300d8bbbf430172185 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkShapeRelabelImageFilter.txx @@ -0,0 +1,125 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkShapeRelabelImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-07 11:37:48 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkShapeRelabelImageFilter_txx +#define __itkShapeRelabelImageFilter_txx + +#include "itkShapeRelabelImageFilter.h" +#include "itkProgressAccumulator.h" + + +namespace itk { + +template<class TInputImage> +ShapeRelabelImageFilter<TInputImage> +::ShapeRelabelImageFilter() +{ + m_BackgroundValue = NumericTraits<OutputImagePixelType>::NonpositiveMin(); + m_ReverseOrdering = false; + m_Attribute = LabelObjectType::SIZE; +} + +template<class TInputImage> +void +ShapeRelabelImageFilter<TInputImage> +::GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // We need all the input. + InputImagePointer input = const_cast<InputImageType *>(this->GetInput()); + if( input ) + { + input->SetRequestedRegion( input->GetLargestPossibleRegion() ); + } +} + + +template<class TInputImage> +void +ShapeRelabelImageFilter<TInputImage> +::EnlargeOutputRequestedRegion(DataObject *) +{ + this->GetOutput() + ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); +} + + +template<class TInputImage> +void +ShapeRelabelImageFilter<TInputImage> +::GenerateData() +{ + // Create a process accumulator for tracking the progress of this minipipeline + ProgressAccumulator::Pointer progress = ProgressAccumulator::New(); + progress->SetMiniPipelineFilter(this); + + // Allocate the output + this->AllocateOutputs(); + + typename LabelizerType::Pointer labelizer = LabelizerType::New(); + labelizer->SetInput( this->GetInput() ); + labelizer->SetBackgroundValue( m_BackgroundValue ); + labelizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(labelizer, .3f); + + typename LabelObjectValuatorType::Pointer valuator = LabelObjectValuatorType::New(); + valuator->SetInput( labelizer->GetOutput() ); + valuator->SetLabelImage( this->GetInput() ); + valuator->SetNumberOfThreads( this->GetNumberOfThreads() ); + if( m_Attribute == LabelObjectType::PERIMETER || m_Attribute == LabelObjectType::ROUNDNESS ) + { + valuator->SetComputePerimeter( true ); + } + if( m_Attribute == LabelObjectType::FERET_DIAMETER ) + { + valuator->SetComputeFeretDiameter( true ); + } + progress->RegisterInternalFilter(valuator, .3f); + + typename RelabelType::Pointer opening = RelabelType::New(); + opening->SetInput( valuator->GetOutput() ); + opening->SetReverseOrdering( m_ReverseOrdering ); + opening->SetAttribute( m_Attribute ); + opening->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(opening, .2f); + + typename BinarizerType::Pointer binarizer = BinarizerType::New(); + binarizer->SetInput( opening->GetOutput() ); + binarizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(binarizer, .2f); + + binarizer->GraftOutput( this->GetOutput() ); + binarizer->Update(); + this->GraftOutput( binarizer->GetOutput() ); +} + + +template<class TInputImage> +void +ShapeRelabelImageFilter<TInputImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "ReverseOrdering: " << m_ReverseOrdering << std::endl; + os << indent << "BackgroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_BackgroundValue) << std::endl; + os << indent << "Attribute: " << LabelObjectType::GetNameFromAttribute(m_Attribute) << " (" << m_Attribute << ")" << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkShapeRelabelLabelMapFilter.h b/Utilities/ITK/Code/Review/itkShapeRelabelLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..93843cbf6e752505437391485ec58aa3c448faa2 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkShapeRelabelLabelMapFilter.h @@ -0,0 +1,188 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkShapeRelabelLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-09 17:53:01 $ + Version: $Revision: 1.7 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkShapeRelabelLabelMapFilter_h +#define __itkShapeRelabelLabelMapFilter_h + +#include "itkInPlaceLabelMapFilter.h" +#include "itkLabelObject.h" +#include "itkLabelObjectAccessors.h" +#include "itkShapeLabelObjectAccessors.h" + +namespace itk { +/** \class ShapeRelabelLabelMapFilter + * \brief Relabels objects according to their shape attributes. + * + * The ShapeRelabelImageFilter relabels a label collection image according to the shape attributes of + * the objects. The label produced are always consecutives. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * \sa ShapeLabelObject, RelabelComponentImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TImage > +class ITK_EXPORT ShapeRelabelLabelMapFilter : + public InPlaceLabelMapFilter<TImage> +{ +public: + /** Standard class typedefs. */ + typedef ShapeRelabelLabelMapFilter Self; + typedef InPlaceLabelMapFilter<TImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TImage ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::LabelObjectType LabelObjectType; + + typedef typename LabelObjectType::AttributeType AttributeType; + + /** ImageDimension constants */ + itkStaticConstMacro( ImageDimension, unsigned int, TImage::ImageDimension ); + + /** Standard New method. */ + itkNewMacro( Self ); + + /** Runtime information support. */ + itkTypeMacro( ShapeRelabelLabelMapFilter, InPlaceLabelMapFilter ); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ +/* itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>));*/ + /** End concept checking */ +#endif + + /** + * Set/Get the order of labeling of the objects. By default, the objects with + * the highest attribute values are labeled first. Setting ReverseOrdering to true + * causes the object with the smallest attributes to be labeled first. + */ + itkSetMacro( ReverseOrdering, bool ); + itkGetConstReferenceMacro( ReverseOrdering, bool ); + itkBooleanMacro( ReverseOrdering ); + + /** + * Set/Get the attribute to use. + * Default is "Size". + */ + itkGetConstMacro( Attribute, AttributeType ); + itkSetMacro( Attribute, AttributeType ); + void SetAttribute( const std::string & s ) + { + this->SetAttribute( LabelObjectType::GetAttributeFromName( s ) ); + } + + +protected: + ShapeRelabelLabelMapFilter(); + ~ShapeRelabelLabelMapFilter() {}; + + void GenerateData(); + + typedef typename Superclass::LabelObjectContainerType LabelObjectContainerType; + + template <class TAttributeAccessor> + void TemplatedGenerateData( const TAttributeAccessor & ) + { + // Allocate the output + this->AllocateOutputs(); + + ImageType * output = this->GetOutput(); + + const LabelObjectContainerType & labelObjectContainer = output->GetLabelObjectContainer(); + typedef typename LabelObjectType::Pointer LabelObjectPointer; + typedef std::vector< LabelObjectPointer > VectorType; + + ProgressReporter progress( this, 0, 2 * labelObjectContainer.size() ); + + // Get the label objects in a vector, so they can be sorted + VectorType labelObjects; + labelObjects.reserve( labelObjectContainer.size() ); + for( typename LabelObjectContainerType::const_iterator it = labelObjectContainer.begin(); + it != labelObjectContainer.end(); + it++ ) + { + labelObjects.push_back( it->second ); + progress.CompletedPixel(); + } + + // Instantiate the comparator and sort the vector + if( m_ReverseOrdering ) + { + std::sort( labelObjects.begin(), labelObjects.end(), + Functor::LabelObjectReverseComparator< LabelObjectType, TAttributeAccessor >() ); + } + else + { + std::sort( labelObjects.begin(), labelObjects.end(), + Functor::LabelObjectComparator< LabelObjectType, TAttributeAccessor >() ); + } + // progress.CompletedPixel(); + + // and put back the objects in the map + output->ClearLabels(); + unsigned int label = 0; + typename VectorType::const_iterator it2 = labelObjects.begin(); + while( it2 != labelObjects.end() ) + { + // Avoid the background label if it is used + if( label == output->GetBackgroundValue() ) + { + label++; + } + ( *it2 )->SetLabel( label ); + output->AddLabelObject( *it2 ); + + // Go to the next label + label++; + progress.CompletedPixel(); + + it2++; + } + } + + void PrintSelf(std::ostream& os, Indent indent) const; + + bool m_ReverseOrdering; + AttributeType m_Attribute; + +private: + ShapeRelabelLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkShapeRelabelLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkShapeRelabelLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkShapeRelabelLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..fd7b925df66671589d8d0b1ca8743addd33a8047 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkShapeRelabelLabelMapFilter.txx @@ -0,0 +1,157 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkShapeRelabelLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-04 21:34:24 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkShapeRelabelLabelMapFilter_txx +#define __itkShapeRelabelLabelMapFilter_txx + +#include "itkShapeRelabelLabelMapFilter.h" + +namespace itk { + +template <class TImage> +ShapeRelabelLabelMapFilter<TImage> +::ShapeRelabelLabelMapFilter() +{ + m_ReverseOrdering = false; + m_Attribute = LabelObjectType::SIZE; +} + + +template <class TImage> +void +ShapeRelabelLabelMapFilter<TImage> +::GenerateData() +{ + switch( m_Attribute ) + { + case LabelObjectType::LABEL: + { + typedef typename Functor::LabelLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::SIZE: + { + typedef typename Functor::SizeLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::PHYSICAL_SIZE: + { + typedef typename Functor::PhysicalSizeLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::SIZE_REGION_RATIO: + { + typedef typename Functor::SizeRegionRatioLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::REGION_ELONGATION: + { + typedef typename Functor::RegionElongationLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::SIZE_ON_BORDER: + { + typedef typename Functor::SizeOnBorderLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::PHYSICAL_SIZE_ON_BORDER: + { + typedef typename Functor::PhysicalSizeOnBorderLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::FERET_DIAMETER: + { + typedef typename Functor::FeretDiameterLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::BINARY_ELONGATION: + { + typedef typename Functor::BinaryElongationLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::PERIMETER: + { + typedef typename Functor::PerimeterLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::ROUNDNESS: + { + typedef typename Functor::RoundnessLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::EQUIVALENT_RADIUS: + { + typedef typename Functor::EquivalentRadiusLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::EQUIVALENT_PERIMETER: + { + typedef typename Functor::EquivalentPerimeterLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::BINARY_FLATNESS: + { + typedef typename Functor::BinaryFlatnessLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + default: + itkExceptionMacro(<< "Unknown attribute type"); + break; + } +} + + +template <class TImage> +void +ShapeRelabelLabelMapFilter<TImage> +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "ReverseOrdering: " << m_ReverseOrdering << std::endl; + os << indent << "Attribute: " << LabelObjectType::GetNameFromAttribute(m_Attribute) << " (" << m_Attribute << ")" << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkShapeUniqueLabelMapFilter.h b/Utilities/ITK/Code/Review/itkShapeUniqueLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..09afd9880abcb13142e219217b54edcc7daf338b --- /dev/null +++ b/Utilities/ITK/Code/Review/itkShapeUniqueLabelMapFilter.h @@ -0,0 +1,358 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkShapeUniqueLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-11 14:24:44 $ + Version: $Revision: 1.6 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkShapeUniqueLabelMapFilter_h +#define __itkShapeUniqueLabelMapFilter_h + +#include "itkInPlaceLabelMapFilter.h" +#include "itkShapeLabelObjectAccessors.h" +#include <queue> + +namespace itk { +/** \class ShapeUniqueLabelMapFilter + * \brief Remove some pixels in the label object according to the value of their shape attribute to ensure that a pixel is not in to objects + * + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \sa ShapeLabelObject, BinaryShapeOpeningImageFilter, LabelStatisticsOpeningImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TImage> +class ITK_EXPORT ShapeUniqueLabelMapFilter : + public InPlaceLabelMapFilter<TImage> +{ +public: + /** Standard class typedefs. */ + typedef ShapeUniqueLabelMapFilter Self; + typedef InPlaceLabelMapFilter<TImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TImage ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::LabelObjectType LabelObjectType; + typedef typename LabelObjectType::LineType LineType; + + typedef typename LabelObjectType::AttributeType AttributeType; + + /** ImageDimension constants */ + itkStaticConstMacro(ImageDimension, unsigned int, + TImage::ImageDimension); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(ShapeUniqueLabelMapFilter, + InPlaceLabelMapFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ +/* itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>));*/ + /** End concept checking */ +#endif + + /** + * Set/Get the ordering of the objects. By default, the objects with + * an attribute value smaller than Lamba are removed. Turning ReverseOrdering + * to true make this filter remove the object with an attribute value greater + * than Lambda instead. + */ + itkGetConstMacro( ReverseOrdering, bool ); + itkSetMacro( ReverseOrdering, bool ); + itkBooleanMacro( ReverseOrdering ); + + /** + * Set/Get the attribute to use to select the object to remove. The default + * is "Size". + */ + itkGetConstMacro( Attribute, AttributeType ); + itkSetMacro( Attribute, AttributeType ); + void SetAttribute( const std::string & s ) + { + this->SetAttribute( LabelObjectType::GetAttributeFromName( s ) ); + } + + +protected: + ShapeUniqueLabelMapFilter(); + ~ShapeUniqueLabelMapFilter() {}; + + void GenerateData(); + + template <class TAttributeAccessor> + void TemplatedGenerateData( const TAttributeAccessor & accessor ) + { + // Allocate the output + this->AllocateOutputs(); + + // the priority queue to store all the lines of all the objects sorted + typedef typename std::priority_queue< LineOfLabelObject, std::vector<LineOfLabelObject>, LineOfLabelObjectComparator > PriorityQueueType; + PriorityQueueType pq; + + ProgressReporter progress( this, 0, 1 ); + // TODO: really report the progress + + typedef typename ImageType::LabelObjectContainerType LabelObjectsType; + + const LabelObjectsType & labelObjects = this->GetLabelMap()->GetLabelObjectContainer(); + for( typename LabelObjectsType::const_iterator it2 = labelObjects.begin(); + it2 != labelObjects.end(); + it2++ ) + { + LabelObjectType * lo = it2->second; + + // may reduce the number of lines to proceed + lo->Optimize(); + + typename LabelObjectType::LineContainerType::const_iterator lit; + typename LabelObjectType::LineContainerType & lineContainer = lo->GetLineContainer(); + + for( lit = lineContainer.begin(); lit != lineContainer.end(); lit++ ) + { + pq.push( LineOfLabelObject( *lit, lo ) ); + } + + // clear the lines to readd them later + lineContainer.clear(); + + // go to the next label + // progress.CompletedPixel(); + } + + if( pq.empty() ) + { + // nothing to do + return; + } + + typedef typename std::deque<LineOfLabelObject> LinesType; + LinesType lines; + + lines.push_back( pq.top() ); + LineOfLabelObject prev = lines.back(); + IndexType prevIdx = prev.line.GetIndex(); + pq.pop(); + + while( !pq.empty() ) + { + LineOfLabelObject l = pq.top(); + IndexType idx = l.line.GetIndex(); + pq.pop(); + + bool newMainLine = false; + // don't check dim 0! + for( int i=1; i<ImageDimension; i++ ) + { + if( idx[i] != prevIdx[i] ) + { + newMainLine = true; + } + } + + if( newMainLine ) + { + // just push the line + lines.push_back( l ); + } + else + { + unsigned long prevLength = prev.line.GetLength(); + unsigned long length = l.line.GetLength(); + + if( prevIdx[0] + (long)prevLength >= idx[0] ) + { + // the lines are overlapping. We need to choose which line to keep. + // the label, the only "attribute" to be guarenteed to be unique, is used to choose + // which line to keep. This is necessary to avoid the case where a part of a label is over + // a second label, and below in another part of the image. + bool keepCurrent; + typename TAttributeAccessor::AttributeValueType prevAttr = accessor( prev.labelObject ); + typename TAttributeAccessor::AttributeValueType attr = accessor( l.labelObject ); + // this may be changed to a single boolean expression, but may become quite difficult to read + if( attr == prevAttr ) + { + if( l.labelObject->GetLabel() > prev.labelObject->GetLabel() ) + { + keepCurrent = !m_ReverseOrdering; + } + else + { + keepCurrent = m_ReverseOrdering; + } + } + else + { + if( attr > prevAttr ) + { + keepCurrent = !m_ReverseOrdering; + } + else + { + keepCurrent = m_ReverseOrdering; + } + } + + if( keepCurrent ) + { + // keep the current one. We must truncate the previous one to remove the + // overlap, and take care of the end of the previous line if it extends + // after the current one. + if( prevIdx[0] + prevLength > idx[0] + length ) + { + // the previous line is longer than the current one. Lets take its tail and + // add it to the priority queue + IndexType newIdx = idx; + newIdx[0] = idx[0] + length; + unsigned long newLength = prevIdx[0] + prevLength - newIdx[0]; + pq.push( LineOfLabelObject( LineType( newIdx, newLength ), prev.labelObject ) ); + } + // truncate the previous line to let some place for the current one + prevLength = idx[0] - prevIdx[0]; + if( prevLength != 0 ) + { + lines.back().line.SetLength( idx[0] - prevIdx[0] ); + } + else + { + // length is 0 - no need to keep that line + lines.pop_back(); + } + // and push the current one + lines.push_back( l ); + } + else + { + // keep the previous one. If the previous line fully overlap the current one, + // the current one is fully discarded. + if( prevIdx[0] + prevLength > idx[0] + length ) + { + // discarding the current line - just do nothing + } + else + { + IndexType newIdx = idx; + newIdx[0] = prevIdx[0] + prevLength; + unsigned long newLength = idx[0] + length - newIdx[0]; + l.line.SetIndex( newIdx ); + l.line.SetLength( newLength ); + lines.push_back( l ); + } + + } + } + else + { + // no overlap - things are just fine already + lines.push_back( l ); + } + } + + // store the current line as the previous one, and go to the next one. + prev = lines.back(); + prevIdx = prev.line.GetIndex(); + } + + // put the lines in their object + for( unsigned int i=0; i<lines.size(); i++ ) + { + LineOfLabelObject & l = lines[i]; + l.labelObject->AddLine( l.line ); + } + + // remove objects without lines + typename LabelObjectsType::const_iterator it = labelObjects.begin(); + while( it != labelObjects.end() ) + { + typename LabelObjectType::LabelType label = it->first; + LabelObjectType * labelObject = it->second; + + if( labelObject->Empty() ) + { + // must increment the iterator before removing the object to avoid invalidating the iterator + it++; + this->GetLabelMap()->RemoveLabel( label ); + } + else + { + it++; + } + + } + } + + void PrintSelf(std::ostream& os, Indent indent) const; + + AttributeType m_Attribute; + +private: + ShapeUniqueLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + bool m_ReverseOrdering; + struct LineOfLabelObject + { + typedef typename LabelObjectType::LineType LineType; + LineOfLabelObject( const LineType _line, LabelObjectType * _lo ) + { + this->line = _line; + this->labelObject = _lo; + } + LineType line; + LabelObjectType * labelObject; + }; + + class LineOfLabelObjectComparator + { + public: + bool operator()( const LineOfLabelObject & lla, const LineOfLabelObject & llb ) + { + for( int i=ImageDimension-1; i>=0; i-- ) + { + if( lla.line.GetIndex()[i] > llb.line.GetIndex()[i] ) + { + return true; + } + else if( lla.line.GetIndex()[i] < llb.line.GetIndex()[i] ) + { + return false; + } + } + return false; + } + }; + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkShapeUniqueLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkShapeUniqueLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkShapeUniqueLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..a02559be71d75bf3a1341bb006a255dad0006143 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkShapeUniqueLabelMapFilter.txx @@ -0,0 +1,158 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkShapeUniqueLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-07 13:40:54 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkShapeUniqueLabelMapFilter_txx +#define __itkShapeUniqueLabelMapFilter_txx + +#include "itkShapeUniqueLabelMapFilter.h" + +namespace itk { + +template <class TImage> +ShapeUniqueLabelMapFilter<TImage> +::ShapeUniqueLabelMapFilter() +{ + m_ReverseOrdering = false; + m_Attribute = LabelObjectType::SIZE; +} + + +template <class TImage> +void +ShapeUniqueLabelMapFilter<TImage> +::GenerateData() +{ + switch( m_Attribute ) + { + case LabelObjectType::LABEL: + { + typedef typename Functor::LabelLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::SIZE: + { + typedef typename Functor::SizeLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::PHYSICAL_SIZE: + { + typedef typename Functor::PhysicalSizeLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::SIZE_REGION_RATIO: + { + typedef typename Functor::SizeRegionRatioLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::REGION_ELONGATION: + { + typedef typename Functor::RegionElongationLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::SIZE_ON_BORDER: + { + typedef typename Functor::SizeOnBorderLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::PHYSICAL_SIZE_ON_BORDER: + { + typedef typename Functor::PhysicalSizeOnBorderLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::FERET_DIAMETER: + { + typedef typename Functor::FeretDiameterLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::BINARY_ELONGATION: + { + typedef typename Functor::BinaryElongationLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::PERIMETER: + { + typedef typename Functor::PerimeterLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::ROUNDNESS: + { + typedef typename Functor::RoundnessLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::EQUIVALENT_RADIUS: + { + typedef typename Functor::EquivalentRadiusLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::EQUIVALENT_PERIMETER: + { + typedef typename Functor::EquivalentPerimeterLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + case LabelObjectType::BINARY_FLATNESS: + { + typedef typename Functor::BinaryFlatnessLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData( accessor ); + break; + } + default: + itkExceptionMacro(<< "Unknown attribute type"); + break; + } + +} + + +template <class TImage> +void +ShapeUniqueLabelMapFilter<TImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "ReverseOrdering: " << m_ReverseOrdering << std::endl; + os << indent << "Attribute: " << LabelObjectType::GetNameFromAttribute(m_Attribute) << " (" << m_Attribute << ")" << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkShiftScaleLabelMapFilter.h b/Utilities/ITK/Code/Review/itkShiftScaleLabelMapFilter.h new file mode 100755 index 0000000000000000000000000000000000000000..907f571aae0bff190ffd670c2d88f96e9b7311d5 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkShiftScaleLabelMapFilter.h @@ -0,0 +1,113 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkShiftScaleLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-04 20:25:11 $ + Version: $Revision: 1.4 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkShiftScaleLabelMapFilter_h +#define __itkShiftScaleLabelMapFilter_h + +#include "itkInPlaceLabelMapFilter.h" + +namespace itk { +/** \class ShiftScaleLabelMapFilter + * \brief Shifts and scales a label map filter, giving the option to change the background value. + * + * This filter takes as input a label map and shift, scale and background values + * to produce, as output, a rescaled and shifted label map with, when applicable, a + * new background. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * \sa ShapeLabelObject, RelabelComponentImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TImage > +class ITK_EXPORT ShiftScaleLabelMapFilter : + public InPlaceLabelMapFilter<TImage> +{ +public: + /** Standard class typedefs. */ + typedef ShiftScaleLabelMapFilter Self; + typedef InPlaceLabelMapFilter<TImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TImage ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::LabelObjectType LabelObjectType; + typedef typename Superclass::LabelObjectContainerType LabelObjectContainerType; + + /** ImageDimension constants */ + itkStaticConstMacro(ImageDimension, unsigned int, TImage::ImageDimension); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(ShiftScaleLabelMapFilter, InPlaceLabelMapFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ +/* itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>));*/ + /** End concept checking */ +#endif + + itkSetMacro( Shift, double ); + itkGetConstReferenceMacro( Shift, double ); + + itkSetMacro( Scale, double ); + itkGetConstReferenceMacro( Scale, double ); + + itkSetMacro( ChangeBackgroundValue, bool ); + itkGetConstMacro( ChangeBackgroundValue, bool ); + itkBooleanMacro( ChangeBackgroundValue ); + +protected: + ShiftScaleLabelMapFilter(); + ~ShiftScaleLabelMapFilter() {}; + + void GenerateData(); + + void PrintSelf(std::ostream& os, Indent indent) const; + + double m_Shift; + double m_Scale; + bool m_ChangeBackgroundValue; + +private: + ShiftScaleLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkShiftScaleLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkShiftScaleLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkShiftScaleLabelMapFilter.txx new file mode 100755 index 0000000000000000000000000000000000000000..67f2e36e72780ca04f73870592a632cf67502fb7 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkShiftScaleLabelMapFilter.txx @@ -0,0 +1,89 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkShiftScaleLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-07-25 14:51:19 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkShiftScaleLabelMapFilter_txx +#define __itkShiftScaleLabelMapFilter_txx + +#include "itkShiftScaleLabelMapFilter.h" +#include "itkProgressReporter.h" + + +namespace itk { + +template <class TImage> +ShiftScaleLabelMapFilter<TImage> +::ShiftScaleLabelMapFilter() +{ + m_Shift = 0.0; + m_Scale = 1.0; + m_ChangeBackgroundValue = false; +} + + +template <class TImage> +void +ShiftScaleLabelMapFilter<TImage> +::GenerateData() +{ + // Allocate the output + this->AllocateOutputs(); + + ImageType * output = this->GetOutput(); + + // get the label objects + LabelObjectContainerType labelObjects = output->GetLabelObjectContainer(); + + ProgressReporter progress( this, 0, labelObjects.size() ); + + // change the background, if requested + if( m_ChangeBackgroundValue ) + { + PixelType label = static_cast<PixelType>( m_Scale * output->GetBackgroundValue() + m_Shift ); + output->SetBackgroundValue( label ); + } + + // and put back the objects in the map + output->ClearLabels(); + typename LabelObjectContainerType::iterator it = labelObjects.begin(); + while( it != labelObjects.end() ) + { + LabelObjectType * lo = it->second; + PixelType label = static_cast<PixelType>( m_Scale * lo->GetLabel() + m_Shift ); + lo->SetLabel( label ); + output->AddLabelObject( lo ); + + // go to the next label + progress.CompletedPixel(); + it++; + } + +} + + +template <class TImage> +void +ShiftScaleLabelMapFilter<TImage> +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "Shift: " << m_Shift << std::endl; + os << indent << "Scale: " << m_Scale << std::endl; + os << indent << "ChangeBackgroundValue: " << m_ChangeBackgroundValue << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkSinRegularizedHeavisideStepFunction.h b/Utilities/ITK/Code/Review/itkSinRegularizedHeavisideStepFunction.h index 3976d60aa8f8b50a4eef76e758d08bdb3f5193b3..57b47d02ccbc1155a3d123ee2d3d22aa4c330afd 100644 --- a/Utilities/ITK/Code/Review/itkSinRegularizedHeavisideStepFunction.h +++ b/Utilities/ITK/Code/Review/itkSinRegularizedHeavisideStepFunction.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSinRegularizedHeavisideStepFunction.h,v $ Language: C++ - Date: $Date: 2009-05-09 21:35:53 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-06-08 04:17:06 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -70,13 +70,13 @@ public: /** Evaluate at the specified input position */ virtual OutputType Evaluate( const InputType& input ) const { - if( input > this->GetEpsilon() ) + if( input >= this->GetEpsilon() ) { return 1.0; } else { - if( input < -this->GetEpsilon() ) + if( input <= -this->GetEpsilon() ) { return 0.0; } @@ -92,7 +92,7 @@ public: /** Evaluate the derivative at the specified input position */ virtual OutputType EvaluateDerivative( const InputType& input ) const { - if( vnl_math_abs( input ) > this->GetEpsilon() ) + if( vnl_math_abs( input ) >= this->GetEpsilon() ) { return 0.0; } diff --git a/Utilities/ITK/Code/Review/itkSliceBySliceImageFilter.h b/Utilities/ITK/Code/Review/itkSliceBySliceImageFilter.h index ad8aad5a6484dd57f98d1666bf9ff35d2263e4a0..0492ad2dda8fcec8f2303721bf24aec5a4c9ed6d 100644 --- a/Utilities/ITK/Code/Review/itkSliceBySliceImageFilter.h +++ b/Utilities/ITK/Code/Review/itkSliceBySliceImageFilter.h @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSliceBySliceImageFilter.h,v $ Language: C++ - Date: $Date: 2009-04-23 03:43:42 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-06-20 08:06:34 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -74,7 +74,7 @@ template<class TInputImage, class TInputFilter=ImageToImageFilter< Image< ITK_TYPENAME TInputImage::PixelType, ::itk::GetImageDimension<TInputImage >::ImageDimension - 1 >, Image< ITK_TYPENAME TOutputImage::PixelType, ::itk::GetImageDimension<TOutputImage>::ImageDimension - 1 > >, - class TOutputFilter=TInputFilter, + class TOutputFilter=ITK_TYPENAME TInputFilter::Superclass, class TInternalInputImage=ITK_TYPENAME TInputFilter::InputImageType, class TInternalOutputImage=ITK_TYPENAME TOutputFilter::OutputImageType > class ITK_EXPORT SliceBySliceImageFilter : diff --git a/Utilities/ITK/Code/Review/itkStatisticsKeepNObjectsLabelMapFilter.h b/Utilities/ITK/Code/Review/itkStatisticsKeepNObjectsLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..772ac5ccfd6ff3fe051371757160d7c098ba5b9f --- /dev/null +++ b/Utilities/ITK/Code/Review/itkStatisticsKeepNObjectsLabelMapFilter.h @@ -0,0 +1,102 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStatisticsKeepNObjectsLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-07 09:55:14 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkStatisticsKeepNObjectsLabelMapFilter_h +#define __itkStatisticsKeepNObjectsLabelMapFilter_h + +#include "itkShapeKeepNObjectsLabelMapFilter.h" +#include "itkStatisticsLabelObject.h" +#include "itkStatisticsLabelObjectAccessors.h" + +namespace itk { +/** \class StatisticsKeepNObjectsLabelMapFilter + * \brief keep N objects according to their statistics attributes + * + * StatisticsKeepNObjectsLabelMapFilter keep the N objects in a label collection image + * with the highest (or lowest) attribute value. The attributes are the ones + * of the StatisticsLabelObject. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \sa StatisticsLabelObject, BinaryStatisticsKeepNObjectsImageFilter, LabelShapeKeepNObjectsImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TImage> +class ITK_EXPORT StatisticsKeepNObjectsLabelMapFilter : + public ShapeKeepNObjectsLabelMapFilter<TImage> +{ +public: + /** Standard class typedefs. */ + typedef StatisticsKeepNObjectsLabelMapFilter Self; + typedef ShapeKeepNObjectsLabelMapFilter<TImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TImage ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::LabelObjectType LabelObjectType; + + typedef typename LabelObjectType::AttributeType AttributeType; + + /** ImageDimension constants */ + itkStaticConstMacro(ImageDimension, unsigned int, + TImage::ImageDimension); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(StatisticsKeepNObjectsLabelMapFilter, + ShapeKeepNObjectsLabelMapFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ +/* itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>));*/ + /** End concept checking */ +#endif +protected: + StatisticsKeepNObjectsLabelMapFilter(); + ~StatisticsKeepNObjectsLabelMapFilter() {}; + + void GenerateData(); + +private: + StatisticsKeepNObjectsLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkStatisticsKeepNObjectsLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkStatisticsKeepNObjectsLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkStatisticsKeepNObjectsLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..a02aabf71f8a812d65bae8d8f9ccbffaeab3ae70 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkStatisticsKeepNObjectsLabelMapFilter.txx @@ -0,0 +1,128 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStatisticsKeepNObjectsLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-07 09:16:54 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkStatisticsKeepNObjectsLabelMapFilter_txx +#define __itkStatisticsKeepNObjectsLabelMapFilter_txx + +#include "itkStatisticsKeepNObjectsLabelMapFilter.h" +#include "itkProgressReporter.h" + + +namespace itk { + +template <class TImage> +StatisticsKeepNObjectsLabelMapFilter<TImage> +::StatisticsKeepNObjectsLabelMapFilter() +{ + this->m_Attribute = LabelObjectType::MEAN; + // create the output image for the removed objects + this->SetNumberOfRequiredOutputs(2); + this->SetNthOutput(1, static_cast<TImage*>(this->MakeOutput(1).GetPointer())); +} + + +template <class TImage> +void +StatisticsKeepNObjectsLabelMapFilter<TImage> +::GenerateData() +{ + switch( this->m_Attribute ) + { + case LabelObjectType::MINIMUM: + { + typedef typename Functor::MinimumLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::MAXIMUM: + { + typedef typename Functor::MaximumLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::MEAN: + { + typedef typename Functor::MeanLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::SUM: + { + typedef typename Functor::SumLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::SIGMA: + { + typedef typename Functor::SigmaLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::VARIANCE: + { + typedef typename Functor::VarianceLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::MEDIAN: + { + typedef typename Functor::MedianLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::KURTOSIS: + { + typedef typename Functor::KurtosisLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::SKEWNESS: + { + typedef typename Functor::SkewnessLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::ELONGATION: + { + typedef typename Functor::ElongationLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::FLATNESS: + { + typedef typename Functor::FlatnessLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + default: + Superclass::GenerateData(); + break; + } +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkStatisticsLabelMapFilter.h b/Utilities/ITK/Code/Review/itkStatisticsLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..c9cd85daf01e8e3cba0cc08e59b4175b441075ab --- /dev/null +++ b/Utilities/ITK/Code/Review/itkStatisticsLabelMapFilter.h @@ -0,0 +1,157 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStatisticsLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-08 01:21:23 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkStatisticsLabelMapFilter_h +#define __itkStatisticsLabelMapFilter_h + +#include "itkShapeLabelMapFilter.h" + +namespace itk { +/** \class StatisticsLabelMapFilter + * \brief The valuator class for the ShapeLabelObject + * + * StatisticsCollectionImageFilter can be used to set the attributes values + * of the StatisticsLabelObject in a LabelMap. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TImage, class TFeatureImage> +class ITK_EXPORT StatisticsLabelMapFilter : + public ShapeLabelMapFilter<TImage, Image< typename TImage::PixelType, ::itk::GetImageDimension<TImage>::ImageDimension> > +{ +public: + /** Standard class typedefs. */ + typedef StatisticsLabelMapFilter Self; + typedef ShapeLabelMapFilter<TImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TImage ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::PointType PointType; + typedef typename ImageType::LabelObjectType LabelObjectType; + typedef typename LabelObjectType::MatrixType MatrixType; + typedef typename LabelObjectType::VectorType VectorType; + + typedef TFeatureImage FeatureImageType; + typedef typename FeatureImageType::Pointer FeatureImagePointer; + typedef typename FeatureImageType::ConstPointer FeatureImageConstPointer; + typedef typename FeatureImageType::PixelType FeatureImagePixelType; + + /** ImageDimension constants */ + itkStaticConstMacro(ImageDimension, unsigned int, + TImage::ImageDimension); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(StatisticsLabelMapFilter, + ShapeLabelMapFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ +/* itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>));*/ + /** End concept checking */ +#endif + + /** Set the feature image */ + void SetFeatureImage(const TFeatureImage *input) + { + // Process object is not const-correct so the const casting is required. + this->SetNthInput( 1, const_cast<TFeatureImage *>(input) ); + } + + /** Get the feature image */ + FeatureImageType * GetFeatureImage() + { + return static_cast<FeatureImageType*>(const_cast<DataObject *>(this->ProcessObject::GetInput(1))); + } + + /** Set the input image */ + void SetInput1(TImage *input) + { + this->SetInput( input ); + } + + /** Set the feature image */ + void SetInput2(const TFeatureImage *input) + { + this->SetFeatureImage( input ); + } + + /** + * Set/Get whether the histogram should be attached to the label object or not. + * This option defaults to `true`, but because the histogram may take a lot of memory + * compared to the other attributes, this option is useful to reduce the memory usage + * when the histogram is not required. + */ + itkSetMacro(ComputeHistogram, bool); + itkGetConstReferenceMacro(ComputeHistogram, bool); + itkBooleanMacro(ComputeHistogram); + + /** + * Set/Get the number of bins in the histogram. Note that the histogram is used + * to compute the median value, and that this option may have an effect on the + * value of the median. + */ + itkSetMacro(NumberOfBins, unsigned int); + itkGetConstReferenceMacro(NumberOfBins, unsigned int); + + +protected: + StatisticsLabelMapFilter(); + ~StatisticsLabelMapFilter() {}; + + virtual void ThreadedProcessLabelObject( LabelObjectType * labelObject ); + + virtual void BeforeThreadedGenerateData(); + + void PrintSelf(std::ostream& os, Indent indent) const; + +private: + StatisticsLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + FeatureImagePixelType m_Minimum; + FeatureImagePixelType m_Maximum; + unsigned int m_NumberOfBins; + bool m_ComputeHistogram; + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkStatisticsLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkStatisticsLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkStatisticsLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..32d4b87a964afc7ec42854e95cc0251a60db1026 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkStatisticsLabelMapFilter.txx @@ -0,0 +1,321 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStatisticsLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-09 16:51:34 $ + Version: $Revision: 1.4 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkStatisticsLabelMapFilter_txx +#define __itkStatisticsLabelMapFilter_txx + +#include "itkStatisticsLabelMapFilter.h" +#include "itkMinimumMaximumImageCalculator.h" +#include "itkProgressReporter.h" +#include "vnl/algo/vnl_real_eigensystem.h" +#include "vnl/algo/vnl_symmetric_eigensystem.h" + + +namespace itk { + +template <class TImage, class TFeatureImage> +StatisticsLabelMapFilter<TImage, TFeatureImage> +::StatisticsLabelMapFilter() +{ + m_NumberOfBins = 128; + m_ComputeHistogram = true; + this->SetNumberOfRequiredInputs(2); +} + + +template <class TImage, class TFeatureImage> +void +StatisticsLabelMapFilter<TImage, TFeatureImage> +::BeforeThreadedGenerateData() +{ + Superclass::BeforeThreadedGenerateData(); + + // get the min and max of the feature image, to use those value as the bounds of our + // histograms + typedef MinimumMaximumImageCalculator< FeatureImageType > MinMaxCalculatorType; + typename MinMaxCalculatorType::Pointer minMax = MinMaxCalculatorType::New(); + minMax->SetImage( this->GetFeatureImage() ); + minMax->Compute(); + + m_Minimum = minMax->GetMinimum(); + m_Maximum = minMax->GetMaximum(); + +} + + +template <class TImage, class TFeatureImage> +void +StatisticsLabelMapFilter<TImage, TFeatureImage> +::ThreadedProcessLabelObject( LabelObjectType * labelObject ) +{ + Superclass::ThreadedProcessLabelObject( labelObject ); + + ImageType * output = this->GetOutput(); + const FeatureImageType * featureImage = this->GetFeatureImage(); + + typedef typename LabelObjectType::HistogramType HistogramType; + + typename HistogramType::SizeType histogramSize; +#ifdef ITK_USE_REVIEW_STATISTICS + histogramSize.SetSize(1); +#endif + histogramSize.Fill( m_NumberOfBins ); + + typename HistogramType::MeasurementVectorType featureImageMin; +#ifdef ITK_USE_REVIEW_STATISTICS + featureImageMin.SetSize(1); +#endif + featureImageMin.Fill( m_Minimum ); + + typename HistogramType::MeasurementVectorType featureImageMax; +#ifdef ITK_USE_REVIEW_STATISTICS + featureImageMax.SetSize(1); +#endif + featureImageMax.Fill( m_Maximum ); + + typename HistogramType::Pointer histogram = HistogramType::New(); +#ifdef ITK_USE_REVIEW_STATISTICS + histogram->SetMeasurementVectorSize(1); +#endif + histogram->SetClipBinsAtEnds( false ); + histogram->Initialize( histogramSize, featureImageMin, featureImageMax ); + + typename LabelObjectType::LineContainerType::const_iterator lit; + typename LabelObjectType::LineContainerType & lineContainer = labelObject->GetLineContainer(); + + FeatureImagePixelType min = NumericTraits< FeatureImagePixelType >::max(); + FeatureImagePixelType max = NumericTraits< FeatureImagePixelType >::NonpositiveMin(); + double sum = 0; + double sum2 = 0; + double sum3 = 0; + double sum4 = 0; + IndexType minIdx; + minIdx.Fill( 0 ); + IndexType maxIdx; + maxIdx.Fill( 0 ); + PointType centerOfGravity; + centerOfGravity.Fill( 0 ); + MatrixType centralMoments; + centralMoments.Fill( 0 ); + MatrixType principalAxes; + principalAxes.Fill( 0 ); + VectorType principalMoments; + principalMoments.Fill( 0 ); + + // iterate over all the lines + for( lit = lineContainer.begin(); lit != lineContainer.end(); lit++ ) + { + const IndexType & firstIdx = lit->GetIndex(); + unsigned long length = lit->GetLength(); + + typename HistogramType::MeasurementVectorType mv; +#ifdef ITK_USE_REVIEW_STATISTICS + mv.SetSize(1); +#endif + long endIdx0 = firstIdx[0] + length; + for( IndexType idx = firstIdx; idx[0]<endIdx0; idx[0]++) + { + const FeatureImagePixelType & v = featureImage->GetPixel( idx ); + mv[0] = v; + histogram->IncreaseFrequency( mv, 1 ); + + // update min and max + if( v <= min ) + { + min = v; + minIdx = idx; + } + if( v >= max ) + { + max = v; + maxIdx = idx; + } + + //increase the sums + sum += v; + sum2 += vcl_pow( (double)v, 2 ); + sum3 += vcl_pow( (double)v, 3 ); + sum4 += vcl_pow( (double)v, 4 ); + + // moments + PointType physicalPosition; + output->TransformIndexToPhysicalPoint(idx, physicalPosition); + for(unsigned int i=0; i<ImageDimension; i++) + { + centerOfGravity[i] += physicalPosition[i] * v; + centralMoments[i][i] += v * physicalPosition[i] * physicalPosition[i]; + for(unsigned int j=i+1; j<ImageDimension; j++) + { + double weight = v * physicalPosition[i] * physicalPosition[j]; + centralMoments[i][j] += weight; + centralMoments[j][i] += weight; + } + } + + } + } + + // final computations +#ifdef ITK_USE_REVIEW_STATISTICS + const typename HistogramType::AbsoluteFrequencyType & totalFreq = histogram->GetTotalFrequency(); +#else + const typename HistogramType::FrequencyType & totalFreq = histogram->GetTotalFrequency(); +#endif + double mean = sum / totalFreq; + double variance = ( sum2 - ( vcl_pow( sum, 2 ) / totalFreq ) ) / ( totalFreq - 1 ); + double sigma = vcl_sqrt( variance ); + double mean2 = mean * mean; + double skewness = ( ( sum3 - 3.0 * mean * sum2) / totalFreq + 2.0 * mean * mean2 ) / ( variance * sigma ); + double kurtosis = ( ( sum4 - 4.0 * mean * sum3 + 6.0 * mean2 * sum2) / totalFreq - 3.0 * mean2 * mean2 ) / ( variance * variance ) - 3.0; + + // the median + double median = 0; + double count = 0; // will not be fully set, so do not use later ! + for( unsigned long i=0; + i<histogram->Size(); + i++) + { + count += histogram->GetFrequency( i ); + + if( count >= ( totalFreq / 2 ) ) + { + median = histogram->GetMeasurementVector( i )[0]; + break; + } + } + + double elongation = 0; + double flatness = 0; + if( sum != 0 ) + { + // Normalize using the total mass + for(unsigned int i=0; i<ImageDimension; i++) + { + centerOfGravity[i] /= sum; + for(unsigned int j=0; j<ImageDimension; j++) + { + centralMoments[i][j] /= sum; + } + } + + // Center the second order moments + for(unsigned int i=0; i<ImageDimension; i++) + { + for(unsigned int j=0; j<ImageDimension; j++) + { + centralMoments[i][j] -= centerOfGravity[i] * centerOfGravity[j]; + } + } + + // the normalized second order central moment of a pixel + for(unsigned int i=0; i<ImageDimension; i++) + { + centralMoments[i][i] += output->GetSpacing()[i] * output->GetSpacing()[i] / 12.0; + } + + // Compute principal moments and axes + vnl_symmetric_eigensystem<double> eigen( centralMoments.GetVnlMatrix() ); + vnl_diag_matrix<double> pm = eigen.D; + for(unsigned int i=0; i<ImageDimension; i++) + { + // principalMoments[i] = 4 * vcl_sqrt( pm(i,i) ); + principalMoments[i] = pm(i,i); + } + principalAxes = eigen.V.transpose(); + + // Add a final reflection if needed for a proper rotation, + // by multiplying the last row by the determinant + vnl_real_eigensystem eigenrot( principalAxes.GetVnlMatrix() ); + vnl_diag_matrix< vcl_complex<double> > eigenval = eigenrot.D; + vcl_complex<double> det( 1.0, 0.0 ); + + for(unsigned int i=0; i<ImageDimension; i++) + { + det *= eigenval( i, i ); + } + + for(unsigned int i=0; i<ImageDimension; i++) + { + principalAxes[ ImageDimension-1 ][i] *= std::real( det ); + } + + if( ImageDimension < 2 ) + { + elongation = 1; + flatness = 1; + } + else if( principalMoments[0] != 0 ) + { + // elongation = principalMoments[ImageDimension-1] / principalMoments[0]; + elongation = vcl_sqrt(principalMoments[ImageDimension-1] / principalMoments[ImageDimension-2]); + flatness = vcl_sqrt(principalMoments[1] / principalMoments[0]); + } + } + else + { + // can't compute anything in that case - just set everything to a default value + // Normalize using the total mass + for(unsigned int i=0; i<ImageDimension; i++) + { + centerOfGravity[i] = 0; + principalMoments[i] = 0; + for(unsigned int j=0; j<ImageDimension; j++) + { + principalAxes[i][j] = 0; + } + } + } + + // finally put the values in the label object + labelObject->SetMinimum( (double)min ); + labelObject->SetMaximum( (double)max ); + labelObject->SetSum( sum ); + labelObject->SetMean( mean ); + labelObject->SetMedian( median ); + labelObject->SetVariance( variance ); + labelObject->SetSigma( sigma ); + labelObject->SetMinimumIndex( minIdx ); + labelObject->SetMaximumIndex( maxIdx ); + labelObject->SetCenterOfGravity( centerOfGravity ); + labelObject->SetPrincipalAxes( principalAxes ); + labelObject->SetFlatness( flatness ); + labelObject->SetPrincipalMoments( principalMoments ); + // labelObject->SetCentralMoments( centralMoments ); + labelObject->SetSkewness( skewness ); + labelObject->SetKurtosis( kurtosis ); + labelObject->SetElongation( elongation ); + if( m_ComputeHistogram ) + { + labelObject->SetHistogram( histogram ); + } + +} + + +template <class TImage, class TFeatureImage> +void +StatisticsLabelMapFilter<TImage, TFeatureImage> +::PrintSelf(std::ostream& os, Indent indent) const +{ + Superclass::PrintSelf(os,indent); + + os << indent << "ComputeHistogram: " << m_ComputeHistogram << std::endl; + os << indent << "NumberOfBins: " << m_NumberOfBins << std::endl; +} + + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkStatisticsLabelObject.h b/Utilities/ITK/Code/Review/itkStatisticsLabelObject.h new file mode 100644 index 0000000000000000000000000000000000000000..c5b5c8d9ee1398c2d351865ca4aa714fd3da07d4 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkStatisticsLabelObject.h @@ -0,0 +1,599 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStatisticsLabelObject.h,v $ + Language: C++ + Date: $Date: 2009-08-08 01:21:23 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkStatisticsLabelObject_h +#define __itkStatisticsLabelObject_h + +#include "itkShapeLabelObject.h" +#include "itkHistogram.h" + +namespace itk +{ + +/** \class StatisticsLabelObject + * \brief A Label object to store the common attributes related to the statistics of the object + * + * StatisticsLabelObject stores the common attributes related to the statistics of the object + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \ingroup DataRepresentation + */ +template < class TLabel, unsigned int VImageDimension > +class ITK_EXPORT StatisticsLabelObject : public ShapeLabelObject< TLabel, VImageDimension > +{ +public: + /** Standard class typedefs */ + typedef StatisticsLabelObject Self; + typedef ShapeLabelObject< TLabel, VImageDimension > Superclass; + typedef typename Superclass::LabelObjectType LabelObjectType; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + typedef WeakPointer<const Self> ConstWeakPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(StatisticsLabelObject, LabelObject); + + typedef LabelMap< Self > LabelMapType; + + itkStaticConstMacro(ImageDimension, unsigned int, VImageDimension); + + typedef typename Superclass::IndexType IndexType; + + typedef Point< double, itkGetStaticConstMacro(ImageDimension) > PointType; + + typedef TLabel LabelType; + + typedef typename Superclass::LineType LineType; + + typedef typename Superclass::LengthType LengthType; + + typedef typename Superclass::LineContainerType LineContainerType; + + typedef Matrix< double, itkGetStaticConstMacro(ImageDimension), itkGetStaticConstMacro(ImageDimension) > MatrixType; + + typedef Vector< double, itkGetStaticConstMacro(ImageDimension) > VectorType; + + typedef Statistics::Histogram< double > HistogramType; + + typedef typename Superclass::AttributeType AttributeType; + itkStaticConstMacro(MINIMUM, AttributeType, 200); + itkStaticConstMacro(MAXIMUM, AttributeType, 201); + itkStaticConstMacro(MEAN, AttributeType, 202); + itkStaticConstMacro(SUM, AttributeType, 203); + itkStaticConstMacro(SIGMA, AttributeType, 204); + itkStaticConstMacro(VARIANCE, AttributeType, 205); + itkStaticConstMacro(MEDIAN, AttributeType, 206); + itkStaticConstMacro(MAXIMUM_INDEX, AttributeType, 207); + itkStaticConstMacro(MINIMUM_INDEX, AttributeType, 208); + itkStaticConstMacro(CENTER_OF_GRAVITY, AttributeType, 209); +// itkStaticConstMacro(CENTRAL_MOMENTS, AttributeType, 210); + itkStaticConstMacro(PRINCIPAL_MOMENTS, AttributeType, 211); + itkStaticConstMacro(PRINCIPAL_AXES, AttributeType, 212); + itkStaticConstMacro(KURTOSIS, AttributeType, 213); + itkStaticConstMacro(SKEWNESS, AttributeType, 214); + itkStaticConstMacro(ELONGATION, AttributeType, 215); + itkStaticConstMacro(HISTOGRAM, AttributeType, 216); + itkStaticConstMacro(FLATNESS, AttributeType, 217); + + static AttributeType GetAttributeFromName( const std::string & s ) + { + if( s == "Minimum" ) + { + return MINIMUM; + } + else if( s == "Maximum" ) + { + return MAXIMUM; + } + else if( s == "Mean" ) + { + return MEAN; + } + else if( s == "Sum" ) + { + return SUM; + } + else if( s == "Sigma" ) + { + return SIGMA; + } + else if( s == "Variance" ) + { + return VARIANCE; + } + else if( s == "Median" ) + { + return MEDIAN; + } + else if( s == "MaximumIndex" ) + { + return MAXIMUM_INDEX; + } + else if( s == "MinimumIndex" ) + { + return MINIMUM_INDEX; + } + else if( s == "CenterOfGravity" ) + { + return CENTER_OF_GRAVITY; + } + /* + else if( s == "CentralMoments" ) + { + return CENTRAL_MOMENTS; + } + */ + else if( s == "PrincipalMoments" ) + { + return PRINCIPAL_MOMENTS; + } + else if( s == "PrincipalAxes" ) + { + return PRINCIPAL_AXES; + } + else if( s == "Kurtosis" ) + { + return KURTOSIS; + } + else if( s == "Skewness" ) + { + return SKEWNESS; + } + else if( s == "Elongation" ) + { + return ELONGATION; + } + else if( s == "Histogram" ) + { + return HISTOGRAM; + } + else if( s == "Flatness" ) + { + return FLATNESS; + } + // can't recognize the name + return Superclass::GetAttributeFromName( s ); + } + + static std::string GetNameFromAttribute( const AttributeType & a ) + { + switch( a ) + { + case MINIMUM: + return "Minimum"; + break; + case MAXIMUM: + return "Maximum"; + break; + case MEAN: + return "Mean"; + break; + case SUM: + return "Sum"; + break; + case SIGMA: + return "Sigma"; + break; + case VARIANCE: + return "Variance"; + break; + case MEDIAN: + return "Median"; + break; + case MAXIMUM_INDEX: + return "MaximumIndex"; + break; + case MINIMUM_INDEX: + return "MinimumIndex"; + break; + case CENTER_OF_GRAVITY: + return "CenterOfGravity"; + break; +/* case CENTRAL_MOMENTS: + return "CentralMoments"; + break;*/ + case PRINCIPAL_MOMENTS: + return "PrincipalMoments"; + break; + case PRINCIPAL_AXES: + return "PrincipalAxes"; + break; + case KURTOSIS: + return "Kurtosis"; + break; + case SKEWNESS: + return "Skewness"; + break; + case ELONGATION: + return "Elongation"; + break; + case HISTOGRAM: + return "Histogram"; + break; + case FLATNESS: + return "Flatness"; + break; + } + // can't recognize the name + return Superclass::GetNameFromAttribute( a ); + } + + typedef ImageRegion< itkGetStaticConstMacro(ImageDimension) > RegionType; + + typedef typename Superclass::CentroidType CentroidType; + + + virtual void CopyAttributesFrom( const LabelObjectType * lo ) + { + Superclass::CopyAttributesFrom( lo ); + + // copy the data of the current type if possible + const Self * src = dynamic_cast<const Self *>( lo ); + if( src == NULL ) + { + return; + } + m_Minimum = src->m_Minimum; + m_Maximum = src->m_Maximum; + m_Mean = src->m_Mean; + m_Sum = src->m_Sum; + m_Sigma = src->m_Sigma; + m_Variance = src->m_Variance; + m_Median = src->m_Median; + m_MaximumIndex = src->m_MaximumIndex; + m_MinimumIndex = src->m_MinimumIndex; + m_CenterOfGravity = src->m_CenterOfGravity; + // m_CentralMoments = src->m_CentralMoments; + m_PrincipalMoments = src->m_PrincipalMoments; + m_PrincipalAxes = src->m_PrincipalAxes; + m_Kurtosis = src->m_Kurtosis; + m_Skewness = src->m_Skewness; + m_Elongation = src->m_Elongation; + m_Histogram = src->m_Histogram; + m_Flatness = src->m_Flatness; + } + + const double & GetMinimum() const + { + return m_Minimum; + } + + void SetMinimum( const double & v ) + { + m_Minimum = v; + } + + const double & GetMaximum() const + { + return m_Maximum; + } + + void SetMaximum( const double & v ) + { + m_Maximum = v; + } + + const double & GetMean() const + { + return m_Mean; + } + + void SetMean( const double & v ) + { + m_Mean = v; + } + + const double & GetSum() const + { + return m_Sum; + } + + void SetSum( const double & v ) + { + m_Sum = v; + } + + const double & GetSigma() const + { + return m_Sigma; + } + + void SetSigma( const double & v ) + { + m_Sigma = v; + } + + const double & GetVariance() const + { + return m_Variance; + } + + void SetVariance( const double & v ) + { + m_Variance = v; + } + + const double & GetMedian() const + { + return m_Median; + } + + void SetMedian( const double & v ) + { + m_Median = v; + } + + const IndexType & GetMaximumIndex() const + { + return m_MaximumIndex; + } + + void SetMaximumIndex( const IndexType & v ) + { + m_MaximumIndex = v; + } + + const IndexType & GetMinimumIndex() const + { + return m_MinimumIndex; + } + + void SetMinimumIndex( const IndexType & v ) + { + m_MinimumIndex = v; + } + + const PointType & GetCenterOfGravity() const + { + return m_CenterOfGravity; + } + + void SetCenterOfGravity( const PointType & v ) + { + m_CenterOfGravity = v; + } + + /* + const MatrixType & GetCentralMoments() const + { + return m_CentralMoments; + } + + void SetCentralMoments( const MatrixType & v ) + { + m_CentralMoments = v; + }*/ + + const VectorType & GetPrincipalMoments() const + { + return m_PrincipalMoments; + } + + void SetPrincipalMoments( const VectorType & v ) + { + m_PrincipalMoments = v; + } + + const MatrixType & GetPrincipalAxes() const + { + return m_PrincipalAxes; + } + + void SetPrincipalAxes( const MatrixType & v ) + { + m_PrincipalAxes = v; + } + + const double & GetSkewness() const + { + return m_Skewness; + } + + void SetSkewness( const double & v ) + { + m_Skewness = v; + } + + const double & GetKurtosis() const + { + return m_Kurtosis; + } + + void SetKurtosis( const double & v ) + { + m_Kurtosis = v; + } + + const double & GetElongation() const + { + return m_Elongation; + } + + void SetElongation( const double & v ) + { + m_Elongation = v; + } + + const HistogramType * GetHistogram() const + { + return m_Histogram; + } + + void SetHistogram( const HistogramType * v ) + { + m_Histogram = v; + } + + const double & GetFlatness() const + { + return m_Flatness; + } + + void SetFlatness( const double & v ) + { + m_Flatness = v; + } + + + // some helper methods - not really required, but really useful! + /** Affine transform for mapping to and from principal axis */ + typedef AffineTransform<double,itkGetStaticConstMacro(ImageDimension)> AffineTransformType; + typedef typename AffineTransformType::Pointer AffineTransformPointer; + + /** Get the affine transform from principal axes to physical axes + * This method returns an affine transform which transforms from + * the principal axes coordinate system to physical coordinates. */ + AffineTransformPointer GetPrincipalAxesToPhysicalAxesTransform() const + { + typename AffineTransformType::MatrixType matrix; + typename AffineTransformType::OffsetType offset; + for (unsigned int i = 0; i < ImageDimension; i++) + { + offset[i] = m_CenterOfGravity[i]; + for (unsigned int j = 0; j < ImageDimension; j++) + { + matrix[j][i] = m_PrincipalAxes[i][j]; // Note the transposition + } + } + + AffineTransformPointer result = AffineTransformType::New(); + + result->SetMatrix(matrix); + result->SetOffset(offset); + + return result; + } + + /** Get the affine transform from physical axes to principal axes + * This method returns an affine transform which transforms from + * the physical coordinate system to the principal axes coordinate + * system. */ + AffineTransformPointer GetPhysicalAxesToPrincipalAxesTransform(void) const + { + typename AffineTransformType::MatrixType matrix; + typename AffineTransformType::OffsetType offset; + for (unsigned int i = 0; i < ImageDimension; i++) + { + offset[i] = m_CenterOfGravity[i]; + for (unsigned int j = 0; j < ImageDimension; j++) + { + matrix[j][i] = m_PrincipalAxes[i][j]; // Note the transposition + } + } + + AffineTransformPointer result = AffineTransformType::New(); + result->SetMatrix(matrix); + result->SetOffset(offset); + + AffineTransformPointer inverse = AffineTransformType::New(); + result->GetInverse(inverse); + + return inverse; + } + + +protected: + StatisticsLabelObject() + { + m_Minimum = 0; + m_Maximum = 0; + m_Mean = 0; + m_Sum = 0; + m_Sigma = 0; + m_Variance = 0; + m_Median = 0; + m_MaximumIndex.Fill(0); + m_MinimumIndex.Fill(0); + m_CenterOfGravity.Fill(0); + // m_CentralMoments.Fill(0); + m_PrincipalMoments.Fill(0); + m_PrincipalAxes.Fill(0); + m_Kurtosis = 0; + m_Skewness = 0; + m_Elongation = 0; + m_Histogram = NULL; + m_Flatness = 0; + } + + + void PrintSelf(std::ostream& os, Indent indent) const + { + Superclass::PrintSelf( os, indent ); + + os << indent << "Minimum: " << m_Minimum << std::endl; + os << indent << "Maximum: " << m_Maximum << std::endl; + os << indent << "Mean: " << m_Mean << std::endl; + os << indent << "Sum: " << m_Sum << std::endl; + os << indent << "Sigma: " << m_Sigma << std::endl; + os << indent << "Variance: " << m_Variance << std::endl; + os << indent << "Median: " << m_Median << std::endl; + os << indent << "MaximumIndex: " << m_MaximumIndex << std::endl; + os << indent << "MinimumIndex: " << m_MinimumIndex << std::endl; + os << indent << "CenterOfGravity: " << m_CenterOfGravity << std::endl; + // os << indent << "CentralMoments: " << std::endl << m_CentralMoments; + os << indent << "PrincipalMoments: " << m_PrincipalMoments << std::endl; + os << indent << "PrincipalAxes: " << std::endl << m_PrincipalAxes; + os << indent << "Skewness: " << m_Skewness << std::endl; + os << indent << "Kurtosis: " << m_Kurtosis << std::endl; + os << indent << "Elongation: " << m_Elongation << std::endl; + os << indent << "Histogram: "; + if( m_Histogram.IsNull() ) + { + os << "NULL" << std::endl; + } + else + { + m_Histogram->Print( os, indent ); + } + os << indent << "Flatness: " << m_Flatness << std::endl; + } + +private: + StatisticsLabelObject(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + double m_Minimum; + double m_Maximum; + double m_Mean; + double m_Sum; + double m_Sigma; + double m_Variance; + double m_Median; + IndexType m_MaximumIndex; + IndexType m_MinimumIndex; + PointType m_CenterOfGravity; + // MatrixType m_CentralMoments; + VectorType m_PrincipalMoments; + MatrixType m_PrincipalAxes; + double m_Skewness; + double m_Kurtosis; + double m_Elongation; + typename HistogramType::ConstPointer m_Histogram; + double m_Flatness; + +}; + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkStatisticsLabelObjectAccessors.h b/Utilities/ITK/Code/Review/itkStatisticsLabelObjectAccessors.h new file mode 100644 index 0000000000000000000000000000000000000000..29aa3b30b640d39759f21f66ced5fb3ca483075d --- /dev/null +++ b/Utilities/ITK/Code/Review/itkStatisticsLabelObjectAccessors.h @@ -0,0 +1,269 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStatisticsLabelObjectAccessors.h,v $ + Language: C++ + Date: $Date: 2009-08-09 11:26:48 $ + Version: $Revision: 1.4 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkStatisticsLabelObjectAccessors_h +#define __itkStatisticsLabelObjectAccessors_h +#include "itkShapeLabelObjectAccessors.h" + + +namespace itk +{ + +namespace Functor +{ + +template< class TLabelObject > +class ITK_EXPORT MinimumLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetMinimum(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT MaximumLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetMaximum(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT MeanLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetMean(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT SumLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetSum(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT SigmaLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetSigma(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT VarianceLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetVariance(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT MedianLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetMedian(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT MaximumIndexLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef typename LabelObjectType::IndexType AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetMaximumIndex(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT MinimumIndexLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef typename LabelObjectType::IndexType AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetMinimumIndex(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT CenterOfGravityLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef typename LabelObjectType::PointType AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetCenterOfGravity(); + } +}; + + +/* +template< class TLabelObject > +class ITK_EXPORT CentralMomentsLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef typename LabelObjectType::MatrixType AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetCentralMoments(); + } + }; +*/ + +template< class TLabelObject > +class ITK_EXPORT PrincipalMomentsLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef typename LabelObjectType::VectorType AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetPrincipalMoments(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT PrincipalAxesLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef typename LabelObjectType::MatrixType AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetPrincipalAxes(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT KurtosisLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetKurtosis(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT SkewnessLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetSkewness(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT ElongationLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetElongation(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT HistogramLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef typename LabelObjectType::HistogramType * AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetHistogram(); + } +}; + +template< class TLabelObject > +class ITK_EXPORT FlatnessLabelObjectAccessor +{ +public: + typedef TLabelObject LabelObjectType; + typedef double AttributeValueType; + + inline AttributeValueType operator()( const LabelObjectType * labelObject ) const + { + return labelObject->GetFlatness(); + } +}; + +} + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Code/Review/itkStatisticsOpeningLabelMapFilter.h b/Utilities/ITK/Code/Review/itkStatisticsOpeningLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..f49505d164f77a8ed4917ca30050e3c72e07998c --- /dev/null +++ b/Utilities/ITK/Code/Review/itkStatisticsOpeningLabelMapFilter.h @@ -0,0 +1,103 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStatisticsOpeningLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-07 09:55:14 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkStatisticsOpeningLabelMapFilter_h +#define __itkStatisticsOpeningLabelMapFilter_h + +#include "itkShapeOpeningLabelMapFilter.h" +#include "itkStatisticsLabelObject.h" +#include "itkStatisticsLabelObjectAccessors.h" + +namespace itk { +/** \class StatisticsOpeningLabelMapFilter + * \brief remove the objects according to the value of their statistics attribute + * + * StatisticsOpeningLabelMapFilter removes the objects in a lavbel collection image + * with an attribute value smaller or greater than a threshold called Lambda. + * The attributes are the ones of the StatisticsLabelObject. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \sa StatisticsLabelObject, BinaryStatisticsOpeningImageFilter, LabelShapeOpeningImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TImage> +class ITK_EXPORT StatisticsOpeningLabelMapFilter : + public ShapeOpeningLabelMapFilter<TImage> +{ +public: + /** Standard class typedefs. */ + typedef StatisticsOpeningLabelMapFilter Self; + typedef ShapeOpeningLabelMapFilter<TImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TImage ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::LabelObjectType LabelObjectType; + + typedef typename LabelObjectType::AttributeType AttributeType; + + /** ImageDimension constants */ + itkStaticConstMacro(ImageDimension, unsigned int, + TImage::ImageDimension); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(StatisticsOpeningLabelMapFilter, + ShapeOpeningLabelMapFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ +/* itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>));*/ + /** End concept checking */ +#endif + + +protected: + StatisticsOpeningLabelMapFilter(); + ~StatisticsOpeningLabelMapFilter() {}; + + void GenerateData(); + +private: + StatisticsOpeningLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkStatisticsOpeningLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkStatisticsOpeningLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkStatisticsOpeningLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..1c0b0c9b22a083ed0f5573d508469a64cdbeef99 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkStatisticsOpeningLabelMapFilter.txx @@ -0,0 +1,128 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStatisticsOpeningLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-07 09:06:55 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkStatisticsOpeningLabelMapFilter_txx +#define __itkStatisticsOpeningLabelMapFilter_txx + +#include "itkStatisticsOpeningLabelMapFilter.h" +#include "itkProgressReporter.h" + + +namespace itk { + +template <class TImage> +StatisticsOpeningLabelMapFilter<TImage> +::StatisticsOpeningLabelMapFilter() +{ + this->m_Attribute = LabelObjectType::MEAN; + // create the output image for the removed objects + this->SetNumberOfRequiredOutputs(2); + this->SetNthOutput(1, static_cast<TImage*>(this->MakeOutput(1).GetPointer())); +} + + +template <class TImage> +void +StatisticsOpeningLabelMapFilter<TImage> +::GenerateData() +{ + switch( this->m_Attribute ) + { + case LabelObjectType::MINIMUM: + { + typedef typename Functor::MinimumLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::MAXIMUM: + { + typedef typename Functor::MaximumLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::MEAN: + { + typedef typename Functor::MeanLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::SUM: + { + typedef typename Functor::SumLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::SIGMA: + { + typedef typename Functor::SigmaLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::VARIANCE: + { + typedef typename Functor::VarianceLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::MEDIAN: + { + typedef typename Functor::MedianLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::KURTOSIS: + { + typedef typename Functor::KurtosisLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::SKEWNESS: + { + typedef typename Functor::SkewnessLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::ELONGATION: + { + typedef typename Functor::ElongationLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::FLATNESS: + { + typedef typename Functor::FlatnessLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + default: + Superclass::GenerateData(); + break; + } +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkStatisticsRelabelImageFilter.h b/Utilities/ITK/Code/Review/itkStatisticsRelabelImageFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..ba5394cb657bf79fea9908e3630f8da0f42808e6 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkStatisticsRelabelImageFilter.h @@ -0,0 +1,192 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStatisticsRelabelImageFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-11 14:24:44 $ + Version: $Revision: 1.3 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkStatisticsRelabelImageFilter_h +#define __itkStatisticsRelabelImageFilter_h + +#include "itkImageToImageFilter.h" +#include "itkStatisticsLabelObject.h" +#include "itkLabelMap.h" +#include "itkLabelImageToLabelMapFilter.h" +#include "itkStatisticsLabelMapFilter.h" +#include "itkStatisticsRelabelLabelMapFilter.h" +#include "itkLabelMapToLabelImageFilter.h" + + +namespace itk { + +/** \class StatisticsRelabelImageFilter + * \brief relabel objects according to their shape attributes + * + * StatisticsRelabelImageFilter relabel a labeled image according to the statistics attributes of + * the objects. The label produced are always consecutives. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \sa StatisticsLabelObject, RelabelComponentImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TInputImage, class TFeatureImage> +class ITK_EXPORT StatisticsRelabelImageFilter : + public ImageToImageFilter<TInputImage, TInputImage> +{ +public: + /** Standard class typedefs. */ + typedef StatisticsRelabelImageFilter Self; + typedef ImageToImageFilter<TInputImage, TInputImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef TInputImage OutputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + typedef typename OutputImageType::Pointer OutputImagePointer; + typedef typename OutputImageType::ConstPointer OutputImageConstPointer; + typedef typename OutputImageType::RegionType OutputImageRegionType; + typedef typename OutputImageType::PixelType OutputImagePixelType; + + typedef TFeatureImage FeatureImageType; + typedef typename FeatureImageType::Pointer FeatureImagePointer; + typedef typename FeatureImageType::ConstPointer FeatureImageConstPointer; + typedef typename FeatureImageType::PixelType FeatureImagePixelType; + + /** ImageDimension constants */ + itkStaticConstMacro(InputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(OutputImageDimension, unsigned int, + TInputImage::ImageDimension); + itkStaticConstMacro(ImageDimension, unsigned int, + TInputImage::ImageDimension); + + typedef StatisticsLabelObject<InputImagePixelType, itkGetStaticConstMacro(ImageDimension)> LabelObjectType; + typedef LabelMap< LabelObjectType > LabelMapType; + typedef LabelImageToLabelMapFilter< InputImageType, LabelMapType > LabelizerType; + typedef StatisticsLabelMapFilter< LabelMapType, TFeatureImage > LabelObjectValuatorType; + typedef typename LabelObjectType::AttributeType AttributeType; + typedef StatisticsRelabelLabelMapFilter< LabelMapType > RelabelType; + typedef LabelMapToLabelImageFilter< LabelMapType, OutputImageType > BinarizerType; + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(StatisticsRelabelImageFilter, + ImageToImageFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>)); + /** End concept checking */ +#endif + + /** + * Set/Get the value used as "background" in the output image. + * Defaults to NumericTraits<PixelType>::NonpositiveMin(). + */ + itkSetMacro(BackgroundValue, OutputImagePixelType); + itkGetConstMacro(BackgroundValue, OutputImagePixelType); + + /** + * Set/Get the order of labeling of the objects. By default, the objects with + * the highest attribute values are labeled first. Set ReverseOrdering to true + * make the one with the smallest attributes be labeled first. + */ + itkGetConstMacro( ReverseOrdering, bool ); + itkSetMacro( ReverseOrdering, bool ); + itkBooleanMacro( ReverseOrdering ); + + /** + * Set/Get the attribute to use. Default is "Mean". + */ + itkGetConstMacro( Attribute, AttributeType ); + itkSetMacro( Attribute, AttributeType ); + void SetAttribute( const std::string & s ) + { + this->SetAttribute( LabelObjectType::GetAttributeFromName( s ) ); + } + + + /** Set the feature image */ + void SetFeatureImage(TFeatureImage *input) + { + // Process object is not const-correct so the const casting is required. + this->SetNthInput( 1, const_cast<TFeatureImage *>(input) ); + } + + /** Get the feature image */ + FeatureImageType * GetFeatureImage() + { + return static_cast<FeatureImageType*>(const_cast<DataObject *>(this->ProcessObject::GetInput(1))); + } + + /** Set the input image */ + void SetInput1(InputImageType *input) + { + this->SetInput( input ); + } + + /** Set the feature image */ + void SetInput2(FeatureImageType *input) + { + this->SetFeatureImage( input ); + } + +protected: + StatisticsRelabelImageFilter(); + ~StatisticsRelabelImageFilter() {}; + void PrintSelf(std::ostream& os, Indent indent) const; + + /** StatisticsRelabelImageFilter needs the entire input be + * available. Thus, it needs to provide an implementation of + * GenerateInputRequestedRegion(). */ + void GenerateInputRequestedRegion(); + + /** StatisticsRelabelImageFilter will produce the entire output. */ + void EnlargeOutputRequestedRegion(DataObject *itkNotUsed(output)); + + /** Single-threaded version of GenerateData. This filter delegates + * to GrayscaleGeodesicErodeImageFilter. */ + void GenerateData(); + +private: + StatisticsRelabelImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + OutputImagePixelType m_BackgroundValue; + bool m_ReverseOrdering; + AttributeType m_Attribute; +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkStatisticsRelabelImageFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkStatisticsRelabelImageFilter.txx b/Utilities/ITK/Code/Review/itkStatisticsRelabelImageFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..d52f965f610d4f1e8000ba11df1458ce60b2c534 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkStatisticsRelabelImageFilter.txx @@ -0,0 +1,128 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStatisticsRelabelImageFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-07 12:33:02 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkStatisticsRelabelImageFilter_txx +#define __itkStatisticsRelabelImageFilter_txx + +#include "itkStatisticsRelabelImageFilter.h" +#include "itkProgressAccumulator.h" + + +namespace itk { + +template<class TInputImage, class TFeatureImage> +StatisticsRelabelImageFilter<TInputImage, TFeatureImage> +::StatisticsRelabelImageFilter() +{ + m_BackgroundValue = NumericTraits<OutputImagePixelType>::NonpositiveMin(); + m_ReverseOrdering = false; + m_Attribute = LabelObjectType::MEAN; + this->SetNumberOfRequiredInputs(2); +} + +template<class TInputImage, class TFeatureImage> +void +StatisticsRelabelImageFilter<TInputImage, TFeatureImage> +::GenerateInputRequestedRegion() +{ + // call the superclass' implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // We need all the input. + InputImagePointer input = const_cast<InputImageType *>(this->GetInput()); + if( input ) + { + input->SetRequestedRegion( input->GetLargestPossibleRegion() ); + } +} + + +template<class TInputImage, class TFeatureImage> +void +StatisticsRelabelImageFilter<TInputImage, TFeatureImage> +::EnlargeOutputRequestedRegion(DataObject *) +{ + this->GetOutput() + ->SetRequestedRegion( this->GetOutput()->GetLargestPossibleRegion() ); +} + + +template<class TInputImage, class TFeatureImage> +void +StatisticsRelabelImageFilter<TInputImage, TFeatureImage> +::GenerateData() +{ + // Create a process accumulator for tracking the progress of this minipipeline + ProgressAccumulator::Pointer progress = ProgressAccumulator::New(); + progress->SetMiniPipelineFilter(this); + + // Allocate the output + this->AllocateOutputs(); + + typename LabelizerType::Pointer labelizer = LabelizerType::New(); + labelizer->SetInput( this->GetInput() ); + labelizer->SetBackgroundValue( m_BackgroundValue ); + labelizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(labelizer, .3f); + + typename LabelObjectValuatorType::Pointer valuator = LabelObjectValuatorType::New(); + valuator->SetInput( labelizer->GetOutput() ); + valuator->SetFeatureImage( this->GetFeatureImage() ); + valuator->SetLabelImage( this->GetInput() ); + valuator->SetNumberOfThreads( this->GetNumberOfThreads() ); + valuator->SetComputeHistogram( false ); + if( m_Attribute == LabelObjectType::PERIMETER || m_Attribute == LabelObjectType::ROUNDNESS ) + { + valuator->SetComputePerimeter( true ); + } + if( m_Attribute == LabelObjectType::FERET_DIAMETER ) + { + valuator->SetComputeFeretDiameter( true ); + } + progress->RegisterInternalFilter(valuator, .3f); + + typename RelabelType::Pointer opening = RelabelType::New(); + opening->SetInput( valuator->GetOutput() ); + opening->SetReverseOrdering( m_ReverseOrdering ); + opening->SetAttribute( m_Attribute ); + opening->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(opening, .2f); + + typename BinarizerType::Pointer binarizer = BinarizerType::New(); + binarizer->SetInput( opening->GetOutput() ); + binarizer->SetNumberOfThreads( this->GetNumberOfThreads() ); + progress->RegisterInternalFilter(binarizer, .2f); + + binarizer->GraftOutput( this->GetOutput() ); + binarizer->Update(); + this->GraftOutput( binarizer->GetOutput() ); +} + + +template<class TInputImage, class TFeatureImage> +void +StatisticsRelabelImageFilter<TInputImage, TFeatureImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "ReverseOrdering: " << m_ReverseOrdering << std::endl; + os << indent << "BackgroundValue: " << static_cast<typename NumericTraits<OutputImagePixelType>::PrintType>(m_BackgroundValue) << std::endl; + os << indent << "Attribute: " << LabelObjectType::GetNameFromAttribute(m_Attribute) << " (" << m_Attribute << ")" << std::endl; +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkStatisticsRelabelLabelMapFilter.h b/Utilities/ITK/Code/Review/itkStatisticsRelabelLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..faf02c41f1ec159e6d4c36f1c0852a16fa0356f7 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkStatisticsRelabelLabelMapFilter.h @@ -0,0 +1,103 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStatisticsRelabelLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-07 09:55:14 $ + Version: $Revision: 1.2 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkStatisticsRelabelLabelMapFilter_h +#define __itkStatisticsRelabelLabelMapFilter_h + +#include "itkShapeRelabelLabelMapFilter.h" +#include "itkStatisticsLabelObject.h" +#include "itkStatisticsLabelObjectAccessors.h" + +namespace itk { +/** \class StatisticsRelabelLabelMapFilter + * \brief relabel objects according to their shape attributes + * + * StatisticsRelabelLabelMapFilter relabel a label collection image according to the statistics attributes of + * the objects. The label produced are always consecutives. + * + * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France. + * + * This implementation was taken from the Insight Journal paper: + * + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \sa StatisticsLabelObject, RelabelComponentImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TImage > +class ITK_EXPORT StatisticsRelabelLabelMapFilter : + public ShapeRelabelLabelMapFilter<TImage> +{ +public: + /** Standard class typedefs. */ + typedef StatisticsRelabelLabelMapFilter Self; + typedef ShapeRelabelLabelMapFilter<TImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TImage ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::LabelObjectType LabelObjectType; + + typedef typename LabelObjectType::AttributeType AttributeType; + + /** ImageDimension constants */ + itkStaticConstMacro(ImageDimension, unsigned int, + TImage::ImageDimension); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(StatisticsRelabelLabelMapFilter, + ShapeRelabelLabelMapFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ +/* itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>));*/ + /** End concept checking */ +#endif + + +protected: + StatisticsRelabelLabelMapFilter(); + ~StatisticsRelabelLabelMapFilter() {}; + + void GenerateData(); + +private: + StatisticsRelabelLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkStatisticsRelabelLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkStatisticsRelabelLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkStatisticsRelabelLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..4302507117759ec7c0e709f8d91f7957571618cd --- /dev/null +++ b/Utilities/ITK/Code/Review/itkStatisticsRelabelLabelMapFilter.txx @@ -0,0 +1,125 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStatisticsRelabelLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-07 09:30:38 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkStatisticsRelabelLabelMapFilter_txx +#define __itkStatisticsRelabelLabelMapFilter_txx + +#include "itkStatisticsRelabelLabelMapFilter.h" +#include "itkProgressReporter.h" + + +namespace itk { + +template <class TImage> +StatisticsRelabelLabelMapFilter<TImage> +::StatisticsRelabelLabelMapFilter() +{ + this->m_Attribute = LabelObjectType::MEAN; +} + + +template <class TImage> +void +StatisticsRelabelLabelMapFilter<TImage> +::GenerateData() +{ + switch( this->m_Attribute ) + { + case LabelObjectType::MINIMUM: + { + typedef typename Functor::MinimumLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::MAXIMUM: + { + typedef typename Functor::MaximumLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::MEAN: + { + typedef typename Functor::MeanLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::SUM: + { + typedef typename Functor::SumLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::SIGMA: + { + typedef typename Functor::SigmaLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::VARIANCE: + { + typedef typename Functor::VarianceLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::MEDIAN: + { + typedef typename Functor::MedianLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::KURTOSIS: + { + typedef typename Functor::KurtosisLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::SKEWNESS: + { + typedef typename Functor::SkewnessLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::ELONGATION: + { + typedef typename Functor::ElongationLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::FLATNESS: + { + typedef typename Functor::FlatnessLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + default: + Superclass::GenerateData(); + break; + } +} + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkStatisticsUniqueLabelMapFilter.h b/Utilities/ITK/Code/Review/itkStatisticsUniqueLabelMapFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..7b1464d4064369e923e6cd04f57e4f6962f9ca03 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkStatisticsUniqueLabelMapFilter.h @@ -0,0 +1,97 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStatisticsUniqueLabelMapFilter.h,v $ + Language: C++ + Date: $Date: 2009-08-07 13:57:19 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkStatisticsUniqueLabelMapFilter_h +#define __itkStatisticsUniqueLabelMapFilter_h + +#include "itkShapeUniqueLabelMapFilter.h" +#include "itkStatisticsLabelObject.h" + +namespace itk { +/** \class StatisticsUniqueLabelMapFilter + * \brief Remove some pixels in the label object according to the value of their statistics attribute to ensure that a pixel is not in to objects + * + * + * This implementation was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/584 or + * http://www.insight-journal.org/browse/publication/176 + * + * \sa ShapeLabelObject, BinaryShapeOpeningImageFilter, LabelStatisticsOpeningImageFilter + * \ingroup ImageEnhancement MathematicalMorphologyImageFilters + */ +template<class TImage> +class ITK_EXPORT StatisticsUniqueLabelMapFilter : + public ShapeUniqueLabelMapFilter<TImage> +{ +public: + /** Standard class typedefs. */ + typedef StatisticsUniqueLabelMapFilter Self; + typedef ShapeUniqueLabelMapFilter<TImage> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Some convenient typedefs. */ + typedef TImage ImageType; + typedef typename ImageType::Pointer ImagePointer; + typedef typename ImageType::ConstPointer ImageConstPointer; + typedef typename ImageType::PixelType PixelType; + typedef typename ImageType::IndexType IndexType; + typedef typename ImageType::LabelObjectType LabelObjectType; + + typedef typename LabelObjectType::AttributeType AttributeType; + + /** ImageDimension constants */ + itkStaticConstMacro(ImageDimension, unsigned int, + TImage::ImageDimension); + + /** Standard New method. */ + itkNewMacro(Self); + + /** Runtime information support. */ + itkTypeMacro(StatisticsUniqueLabelMapFilter, + ShapeUniqueLabelMapFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ +/* itkConceptMacro(InputEqualityComparableCheck, + (Concept::EqualityComparable<InputImagePixelType>)); + itkConceptMacro(IntConvertibleToInputCheck, + (Concept::Convertible<int, InputImagePixelType>)); + itkConceptMacro(InputOStreamWritableCheck, + (Concept::OStreamWritable<InputImagePixelType>));*/ + /** End concept checking */ +#endif + + +protected: + StatisticsUniqueLabelMapFilter(); + ~StatisticsUniqueLabelMapFilter() {}; + + void GenerateData(); + +private: + StatisticsUniqueLabelMapFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + +}; // end of class + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkStatisticsUniqueLabelMapFilter.txx" +#endif + +#endif diff --git a/Utilities/ITK/Code/Review/itkStatisticsUniqueLabelMapFilter.txx b/Utilities/ITK/Code/Review/itkStatisticsUniqueLabelMapFilter.txx new file mode 100644 index 0000000000000000000000000000000000000000..4444192783596a985d94b5b3233d5ba5cb730a36 --- /dev/null +++ b/Utilities/ITK/Code/Review/itkStatisticsUniqueLabelMapFilter.txx @@ -0,0 +1,125 @@ +/*========================================================================= + + Program: Insight Segmentation & Registration Toolkit + Module: $RCSfile: itkStatisticsUniqueLabelMapFilter.txx,v $ + Language: C++ + Date: $Date: 2009-08-07 13:57:20 $ + Version: $Revision: 1.1 $ + + Copyright (c) Insight Software Consortium. All rights reserved. + See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +#ifndef __itkStatisticsUniqueLabelMapFilter_txx +#define __itkStatisticsUniqueLabelMapFilter_txx + +#include "itkStatisticsUniqueLabelMapFilter.h" + + +namespace itk { + +template <class TImage> +StatisticsUniqueLabelMapFilter<TImage> +::StatisticsUniqueLabelMapFilter() +{ + this->m_Attribute = LabelObjectType::MEAN; +} + + +template <class TImage> +void +StatisticsUniqueLabelMapFilter<TImage> +::GenerateData() +{ + switch( this->m_Attribute ) + { + case LabelObjectType::MINIMUM: + { + typedef typename Functor::MinimumLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::MAXIMUM: + { + typedef typename Functor::MaximumLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::MEAN: + { + typedef typename Functor::MeanLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::SUM: + { + typedef typename Functor::SumLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::SIGMA: + { + typedef typename Functor::SigmaLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::VARIANCE: + { + typedef typename Functor::VarianceLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::MEDIAN: + { + typedef typename Functor::MedianLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::KURTOSIS: + { + typedef typename Functor::KurtosisLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::SKEWNESS: + { + typedef typename Functor::SkewnessLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::ELONGATION: + { + typedef typename Functor::ElongationLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + case LabelObjectType::FLATNESS: + { + typedef typename Functor::FlatnessLabelObjectAccessor< LabelObjectType > AccessorType; + AccessorType accessor; + this->TemplatedGenerateData(accessor); + break; + } + default: + Superclass::GenerateData(); + break; + } +} + + +}// end namespace itk +#endif diff --git a/Utilities/ITK/Code/Review/itkTransformFileWriterWithFactory.cxx b/Utilities/ITK/Code/Review/itkTransformFileWriterWithFactory.cxx index c5f2867dfd0404335abdcc4d206aec0011aa400b..a795118a9435de376456c9bf5d0ee45ec2e6d100 100644 --- a/Utilities/ITK/Code/Review/itkTransformFileWriterWithFactory.cxx +++ b/Utilities/ITK/Code/Review/itkTransformFileWriterWithFactory.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkTransformFileWriterWithFactory.cxx,v $ Language: C++ - Date: $Date: 2008-04-05 15:21:56 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-07-02 17:19:26 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -41,14 +41,14 @@ TransformFileWriter /** Set the writer to append to the specified file */ void TransformFileWriter::SetAppendOn( ) { - this->m_AppendMode = true; + this->SetAppendMode(true); } /** Set the writer to overwrite the specified file - This is the * default mode. */ void TransformFileWriter::SetAppendOff( ) { - this->m_AppendMode = false; + this->SetAppendMode(false); } /** Set the writer mode (append/overwrite). */ @@ -91,6 +91,7 @@ void TransformFileWriter itkExceptionMacro( "Can't Create IO object for file " << m_FileName); } + transformIO->SetAppendMode(this->m_AppendMode); transformIO->SetFileName(m_FileName); transformIO->SetTransformList(this->m_TransformList); transformIO->Write(); diff --git a/Utilities/ITK/Code/Review/itkVTKPolyDataReader.txx b/Utilities/ITK/Code/Review/itkVTKPolyDataReader.txx index 508f1ac5fef0f4394d0429335e4ce5cbce2c6fb6..5ab9d1b19befc11ae719db5e0b2d4c260ad2dfc0 100644 --- a/Utilities/ITK/Code/Review/itkVTKPolyDataReader.txx +++ b/Utilities/ITK/Code/Review/itkVTKPolyDataReader.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVTKPolyDataReader.txx,v $ Language: C++ - Date: $Date: 2009-04-06 18:29:00 $ - Version: $Revision: 1.13 $ + Date: $Date: 2009-06-02 12:48:35 $ + Version: $Revision: 1.16 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -53,7 +53,6 @@ VTKPolyDataReader<TOutputMesh> if( m_FileName == "" ) { itkExceptionMacro("No input FileName"); - return; } // @@ -65,7 +64,6 @@ VTKPolyDataReader<TOutputMesh> { itkExceptionMacro("Unable to open file\n" "inputFilename= " << m_FileName ); - return; } std::string line; @@ -91,7 +89,6 @@ VTKPolyDataReader<TOutputMesh> { itkExceptionMacro("ERROR: Failed to read numberOfPoints\n" " pointLine= " << pointLine ); - return; } itkDebugMacro("numberOfPoints= " << numberOfPoints ); @@ -100,7 +97,6 @@ VTKPolyDataReader<TOutputMesh> { itkExceptionMacro("numberOfPoints < 1" << " numberOfPoints= " << numberOfPoints ); - return; } outputMesh->GetPoints()->Reserve( numberOfPoints ); @@ -140,7 +136,6 @@ VTKPolyDataReader<TOutputMesh> { itkExceptionMacro("ERROR: Failed to read numberOfPolygons from subline2" "\npolygonLine= " << polygonLine ); - return; } itkDebugMacro("numberOfPolygons " << numberOfPolygons ); @@ -150,7 +145,6 @@ VTKPolyDataReader<TOutputMesh> { itkExceptionMacro("ERROR: numberOfPolygons < 1\nnumberOfPolygons= " << numberOfPolygons ); - return; } if( numberOfIndices < numberOfPolygons ) @@ -158,7 +152,6 @@ VTKPolyDataReader<TOutputMesh> itkExceptionMacro("ERROR: numberOfIndices < numberOfPolygons\n" << "numberOfIndices= " << numberOfIndices << "\n" << "numberOfPolygons= " << numberOfPolygons ); - return; } // @@ -174,7 +167,6 @@ VTKPolyDataReader<TOutputMesh> { itkExceptionMacro("Failed to read " << numberOfPolygons << " polygons before the end of file"); - return; } std::getline( inputFile, line ); @@ -182,13 +174,15 @@ VTKPolyDataReader<TOutputMesh> if( line.find("DATA") != std::string::npos ) { itkExceptionMacro("Read keyword DATA"); - return; } - if( sscanf( line.c_str(), "%ld %ld %ld %ld", &numberOfCellPoints, - &ids[0], &ids[1], &ids[2] ) != 4 ) + int got; + if( (got = sscanf( line.c_str(), "%ld %ld %ld %ld", &numberOfCellPoints, + &ids[0], &ids[1], &ids[2] )) != 4 ) { - break; + itkExceptionMacro("Error parsing POLYGON cell. Expected 4 items but got " + << got << std::endl + << "Line is: " << line); } if( numberOfCellPoints != 3 ) @@ -196,7 +190,6 @@ VTKPolyDataReader<TOutputMesh> itkExceptionMacro("ERROR: numberOfCellPoints != 3\n" << "numberOfCellPoints= " << numberOfCellPoints << "itkVTKPolyDataReader can only read triangles"); - return; } if( static_cast<long>(ids[0]) < 0 || @@ -205,7 +198,6 @@ VTKPolyDataReader<TOutputMesh> { itkExceptionMacro("ERROR: Incorrect point ids\n" "ids=" << ids[0] << " " << ids[1] << " " << ids[2]); - return; } if( static_cast<long>(ids[0]) >= numberOfPoints || @@ -214,7 +206,6 @@ VTKPolyDataReader<TOutputMesh> { itkExceptionMacro("ERROR: Incorrect point ids\n" << "ids=" << ids[0] << " " << ids[1] << " " << ids[2]); - return; } CellAutoPointer cell; @@ -228,6 +219,59 @@ VTKPolyDataReader<TOutputMesh> outputMesh->SetCell( i, cell ); } + bool foundPointData = false; + + while( !inputFile.eof() ) + { + std::getline( inputFile, line ); + + if( line.find("POINT_DATA") != std::string::npos ) + { + foundPointData = true; + break; + } + } + + if( foundPointData ) + { + typedef typename OutputMeshType::PointDataContainer PointDataContainer; + + outputMesh->SetPointData( PointDataContainer::New() ); + outputMesh->GetPointData()->Reserve( numberOfPoints ); + + itkDebugMacro("POINT_DATA line" << line ); + + // Skip two lines + if (!inputFile.eof()) + { + std::getline( inputFile, line ); + } + else + { + itkExceptionMacro("Unexpected end-of-file while trying to read POINT_DATA."); + } + if (!inputFile.eof()) + { + std::getline( inputFile, line ); + } + else + { + itkExceptionMacro("Unexpected end-of-file while trying to read POINT_DATA."); + } + + double pointData; + + for( int pid=0; pid < numberOfPoints; pid++ ) + { + if (inputFile.eof()) + { + itkExceptionMacro("Unexpected end-of-file while trying to read POINT_DATA." << "Failed while trying to reading point data for id: " << pid); + } + inputFile >> pointData; + outputMesh->SetPointData( pid, pointData ); + } + } + inputFile.close(); } diff --git a/Utilities/ITK/Code/Review/itkVanHerkGilWermanErodeDilateImageFilter.txx b/Utilities/ITK/Code/Review/itkVanHerkGilWermanErodeDilateImageFilter.txx index 3a2157b0153d6eb1744b6f8db4b66af78a9b3f46..5d4a3c3cb10afe2a309c4bb575c096fd2df28a7e 100644 --- a/Utilities/ITK/Code/Review/itkVanHerkGilWermanErodeDilateImageFilter.txx +++ b/Utilities/ITK/Code/Review/itkVanHerkGilWermanErodeDilateImageFilter.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkVanHerkGilWermanErodeDilateImageFilter.txx,v $ Language: C++ - Date: $Date: 2008-10-20 16:32:08 $ - Version: $Revision: 1.5 $ + Date: $Date: 2009-06-03 12:48:05 $ + Version: $Revision: 1.6 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -106,7 +106,7 @@ VanHerkGilWermanErodeDilateImageFilter<TImage, TKernel, TFunction1> for (unsigned i = 0; i < decomposition.size(); i++) { typename KernelType::LType ThisLine = decomposition[i]; - typename BresType::OffsetArray TheseOffsets = BresLine.buildLine(ThisLine, bufflength); + typename BresType::OffsetArray TheseOffsets = BresLine.BuildLine(ThisLine, bufflength); unsigned int SELength = GetLinePixels<KernelLType>(ThisLine); // want lines to be odd if (!(SELength%2)) diff --git a/Utilities/ITK/DartConfig.cmake b/Utilities/ITK/DartConfig.cmake index 32e220f4a77efc96903cd3c88b0d980af1ed45ea..643e14e327a7e18861b4a49e50f75614481a77df 100644 --- a/Utilities/ITK/DartConfig.cmake +++ b/Utilities/ITK/DartConfig.cmake @@ -1,4 +1,4 @@ -set(CTEST_PROJECT_NAME "Insight") +set(CTEST_PROJECT_NAME "ITK") set(CTEST_NIGHTLY_START_TIME "21:00:00 EDT") set(CTEST_DROP_METHOD "http") diff --git a/Utilities/ITK/Utilities/MetaIO/.svnrev b/Utilities/ITK/Utilities/MetaIO/.svnrev index 84efa7e06a44889fdf6b29b7ddd360dfd91c8ce8..e2a83a8ce3c7e2098c21145f578ff91b7541c16a 100644 --- a/Utilities/ITK/Utilities/MetaIO/.svnrev +++ b/Utilities/ITK/Utilities/MetaIO/.svnrev @@ -1 +1 @@ -801 \ No newline at end of file +855 \ No newline at end of file diff --git a/Utilities/ITK/Utilities/MetaIO/CMakeLists.txt b/Utilities/ITK/Utilities/MetaIO/CMakeLists.txt index 37761f7fa8690d39a993216b83ca6acef0f4d8dc..065cac2ca8b06e5e237a10d9f5294ce5f29351a8 100644 --- a/Utilities/ITK/Utilities/MetaIO/CMakeLists.txt +++ b/Utilities/ITK/Utilities/MetaIO/CMakeLists.txt @@ -54,6 +54,12 @@ ADD_LIBRARY(${METAIO_NAMESPACE} INCLUDE_REGULAR_EXPRESSION("^.*$") +# Need nsl to resolve gethostbyname on SunOS-5.8 +# and socket also +IF(CMAKE_SYSTEM MATCHES "SunOS.*") + TARGET_LINK_LIBRARIES(${METAIO_NAMESPACE} socket nsl) +ENDIF(CMAKE_SYSTEM MATCHES "SunOS.*") + IF(METAIO_FOR_VTK) IF(BUILD_SHARED_LIBS) ADD_DEFINITIONS(-Dvtkmetaio_BUILD_SHARED_LIBS) diff --git a/Utilities/ITK/Utilities/MetaIO/localMetaConfiguration.h b/Utilities/ITK/Utilities/MetaIO/localMetaConfiguration.h index bafd869f958576666a91fca49b0c87ed25182201..1b6074a78fe11cc74f8483203df811d637bf0a47 100644 --- a/Utilities/ITK/Utilities/MetaIO/localMetaConfiguration.h +++ b/Utilities/ITK/Utilities/MetaIO/localMetaConfiguration.h @@ -23,7 +23,6 @@ #define METAIO_NAMESPACE ITKMetaIO #include "itk_zlib.h" - #include "itksys/SystemTools.hxx" #define METAIO_STL std #define METAIO_STREAM std @@ -41,7 +40,6 @@ #include "vtkConfigure.h" #include "vtk_zlib.h" - #include "vtksys/SystemTools.hxx" #ifdef VTK_NO_STD_NAMESPACE #define METAIO_STL diff --git a/Utilities/ITK/Utilities/MetaIO/metaArray.cxx b/Utilities/ITK/Utilities/MetaIO/metaArray.cxx index d3e9fc8d06f859c150931a23ae786affd74d7896..53267996125f8b927291e84c143929f1bed0f4b2 100644 --- a/Utilities/ITK/Utilities/MetaIO/metaArray.cxx +++ b/Utilities/ITK/Utilities/MetaIO/metaArray.cxx @@ -3,8 +3,8 @@ Program: MetaIO Module: $RCSfile: metaArray.cxx,v $ Language: C++ - Date: $Date: 2008-04-09 01:44:28 $ - Version: $Revision: 1.9 $ + Date: $Date: 2009-06-21 21:54:05 $ + Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -18,6 +18,7 @@ #ifdef _MSC_VER #pragma warning(disable:4702) +#pragma warning(disable:4996) #endif #include <stdio.h> diff --git a/Utilities/ITK/Utilities/MetaIO/metaCommand.cxx b/Utilities/ITK/Utilities/MetaIO/metaCommand.cxx index b249bf38844e250bef95095a4b3c68f9d0169fe1..e08eab463d23c98472de969567b59758cf8028b9 100644 --- a/Utilities/ITK/Utilities/MetaIO/metaCommand.cxx +++ b/Utilities/ITK/Utilities/MetaIO/metaCommand.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: metaCommand.cxx,v $ Language: C++ - Date: $Date: 2008-12-30 21:26:22 $ - Version: $Revision: 1.55 $ + Date: $Date: 2009-06-22 20:14:04 $ + Version: $Revision: 1.56 $ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -133,7 +133,8 @@ SetOption(METAIO_STL::string name, << " You should use the SetOptionLongTag(optionName,longTagName)" << " if you want to use a longer tag. The longtag will be" << " refered as --LongTag and the short tag as -ShortTag." - << " Replace -" << shortTag << " by --" << shortTag + << " Replace -" << shortTag.c_str() + << " by --" << shortTag.c_str() << METAIO_STREAM::endl; } @@ -179,7 +180,8 @@ SetOption(METAIO_STL::string name, << " You should use the SetOptionLongTag(optionName,longTagName)" << " if you want to use a longer tag. The longtag will be " << " refered as --LongTag and the short tag as -ShortTag " - << " Replace -" << shortTag << " by --" << shortTag + << " Replace -" << shortTag.c_str() + << " by --" << shortTag.c_str() << METAIO_STREAM::endl; } @@ -903,7 +905,8 @@ void MetaCommand::WriteXMLOptionToCout(METAIO_STL::string optionName, optionType = this->TypeToString((*itField).type).c_str(); } - METAIO_STREAM::cout << "<" << optionType << ">" << METAIO_STREAM::endl; + METAIO_STREAM::cout << "<" << optionType.c_str() + << ">" << METAIO_STREAM::endl; METAIO_STREAM::cout << "<name>" << (*it).name.c_str() << "</name>" @@ -965,7 +968,8 @@ void MetaCommand::WriteXMLOptionToCout(METAIO_STL::string optionName, } // Write out the closing tag - METAIO_STREAM::cout << "</" << optionType << ">" << METAIO_STREAM::endl; + METAIO_STREAM::cout << "</" << optionType.c_str() + << ">" << METAIO_STREAM::endl; } /** List the current options in Slicer's xml format (www.slicer.org) */ @@ -1001,15 +1005,18 @@ void MetaCommand::ListOptionsSlicerXML() { METAIO_STREAM::cout << " <parameters>" << METAIO_STREAM::endl; } - METAIO_STREAM::cout << " <label>" << (*itGroup).name << "</label>" << METAIO_STREAM::endl; + METAIO_STREAM::cout << " <label>" << (*itGroup).name.c_str() + << "</label>" << METAIO_STREAM::endl; if((*itGroup).description.size() == 0) { - METAIO_STREAM::cout << " <description>" << (*itGroup).name << "</description>" << METAIO_STREAM::endl; + METAIO_STREAM::cout << " <description>" << (*itGroup).name.c_str() + << "</description>" << METAIO_STREAM::endl; } else { - METAIO_STREAM::cout << " <description>" << (*itGroup).description << "</description>" << METAIO_STREAM::endl; + METAIO_STREAM::cout << " <description>" << (*itGroup).description.c_str() + << "</description>" << METAIO_STREAM::endl; } METAIO_STL::vector<METAIO_STL::string>::const_iterator itOption = (*itGroup).options.begin(); @@ -2294,7 +2301,8 @@ bool MetaCommand::SetParameterGroup(METAIO_STL::string optionName, if(!optionExists) { - METAIO_STREAM::cout << "The option " << optionName << " doesn't exist" << METAIO_STREAM::endl; + METAIO_STREAM::cout << "The option " << optionName.c_str() + << " doesn't exist" << METAIO_STREAM::endl; return false; } diff --git a/Utilities/ITK/Utilities/MetaIO/metaForm.cxx b/Utilities/ITK/Utilities/MetaIO/metaForm.cxx index 0b85099a7eff3f20b5cd72798f27f7c226bc7e21..1017e313c7293668aa19dbb00fbca9906a63d92c 100644 --- a/Utilities/ITK/Utilities/MetaIO/metaForm.cxx +++ b/Utilities/ITK/Utilities/MetaIO/metaForm.cxx @@ -3,8 +3,8 @@ Program: MetaIO Module: $RCSfile: metaForm.cxx,v $ Language: C++ - Date: $Date: 2008-04-09 01:44:28 $ - Version: $Revision: 1.8 $ + Date: $Date: 2009-06-21 21:54:04 $ + Version: $Revision: 1.9 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -14,6 +14,11 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ +#ifdef _MSC_VER +#pragma warning(disable:4702) +#pragma warning(disable:4996) +#endif + #include "metaForm.h" #include <stdlib.h> diff --git a/Utilities/ITK/Utilities/MetaIO/metaImage.cxx b/Utilities/ITK/Utilities/MetaIO/metaImage.cxx index c99c318db4d4fd392f2681cee3e516a820445c64..098ae60194122b993ab695ee2efe0319c6bdb98b 100644 --- a/Utilities/ITK/Utilities/MetaIO/metaImage.cxx +++ b/Utilities/ITK/Utilities/MetaIO/metaImage.cxx @@ -3,8 +3,8 @@ Program: MetaIO Module: $RCSfile: metaImage.cxx,v $ Language: C++ - Date: $Date: 2009-03-06 03:24:05 $ - Version: $Revision: 1.115 $ + Date: $Date: 2009-07-20 15:34:20 $ + Version: $Revision: 1.119 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -697,8 +697,12 @@ ElementNumberOfChannels(int _elementNumberOfChannels) // // void MetaImage:: -ElementByteOrderSwap(void) +ElementByteOrderSwap(METAIO_STL::streamsize _quantity) { + + // use the user provided value if provided or the internal ivar + METAIO_STL::streamsize quantity = _quantity ? _quantity : m_Quantity; + if(META_DEBUG) { METAIO_STREAM::cout << "MetaImage: ElementByteOrderSwap" @@ -718,7 +722,7 @@ ElementByteOrderSwap(void) case 2: { int i; - for(i=0; i<m_Quantity*m_ElementNumberOfChannels; i++) + for(i=0; i<quantity*m_ElementNumberOfChannels; i++) { ((MET_USHORT_TYPE *)m_ElementData)[i] = MET_ByteOrderSwapShort(((MET_USHORT_TYPE *)m_ElementData)[i]); @@ -728,7 +732,7 @@ ElementByteOrderSwap(void) case 4: { int i; - for(i=0; i<m_Quantity*m_ElementNumberOfChannels; i++) + for(i=0; i<quantity*m_ElementNumberOfChannels; i++) { ((MET_UINT_TYPE *)m_ElementData)[i] = MET_ByteOrderSwapLong(((MET_UINT_TYPE *)m_ElementData)[i]); @@ -739,7 +743,7 @@ ElementByteOrderSwap(void) { int i; char* data = (char*)m_ElementData; - for(i=0; i<m_Quantity*m_ElementNumberOfChannels; i++) + for(i=0; i<quantity*m_ElementNumberOfChannels; i++) { MET_ByteOrderSwap8(data); data += 8; @@ -751,11 +755,11 @@ ElementByteOrderSwap(void) } bool MetaImage:: -ElementByteOrderFix(void) +ElementByteOrderFix(METAIO_STL::streamsize _quantity) { if(m_BinaryDataByteOrderMSB != MET_SystemByteOrderMSB()) { - ElementByteOrderSwap(); + ElementByteOrderSwap(_quantity); return true; } return true; @@ -1257,8 +1261,9 @@ ReadStream(int _nDims, } for(i=0; i<nWrds; i++) { - delete [] wrds[i++]; + delete [] wrds[i]; } + delete [] wrds; if ( (fileImageDim == 0) || (fileImageDim > m_NDims) ) { // if optional file dimension size is not give or is larger than @@ -1377,6 +1382,11 @@ ReadStream(int _nDims, readStreamTemp->close(); } delete readStreamTemp; + for(i=0; i<nWrds; i++) + { + delete [] wrds[i]; + } + delete [] wrds; } else { @@ -2789,8 +2799,9 @@ bool MetaImage::ReadROIStream(int * _indexMin, int * _indexMax, } for(i=0; i<nWrds; i++) { - delete [] wrds[i++]; + delete [] wrds[i]; } + delete [] wrds; if ( (fileImageDim == 0) || (fileImageDim > m_NDims) ) { // if optional file dimension size is not give or is larger than @@ -2961,8 +2972,9 @@ bool MetaImage::ReadROIStream(int * _indexMin, int * _indexMax, for(i=0; i<nWrds; i++) { - delete [] wrds[i++]; + delete [] wrds[i]; } + delete [] wrds; delete readStreamTemp; } diff --git a/Utilities/ITK/Utilities/MetaIO/metaImage.h b/Utilities/ITK/Utilities/MetaIO/metaImage.h index f3ce2beb1406e71894030de9080d9447a22683dd..e32963b319b5894c564f574ca07ae80f81d74747 100644 --- a/Utilities/ITK/Utilities/MetaIO/metaImage.h +++ b/Utilities/ITK/Utilities/MetaIO/metaImage.h @@ -3,8 +3,8 @@ Program: MetaIO Module: $RCSfile: metaImage.h,v $ Language: C++ - Date: $Date: 2009-02-15 23:54:08 $ - Version: $Revision: 1.32 $ + Date: $Date: 2009-07-07 20:04:04 $ + Version: $Revision: 1.33 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -177,8 +177,12 @@ class METAIO_EXPORT MetaImage : public MetaObject // ElemByteOrderSwap(), ElemByteOrderFix() // The following functions are available only after // ReadImageData() or if _read_and_close=TRUE when read - void ElementByteOrderSwap(void); - bool ElementByteOrderFix(void); + // + // if streaming is used, then the size of buffer in total number + // of elements, should be passed as an argument, otherwise the + // internal value Quantity() will be used + void ElementByteOrderSwap( METAIO_STL::streamsize _quantity = 0); + bool ElementByteOrderFix( METAIO_STL::streamsize _quantity = 0); // Min(...) Max(...) // The default max returned is the largest allowed by diff --git a/Utilities/ITK/Utilities/MetaIO/metaImageUtils.cxx b/Utilities/ITK/Utilities/MetaIO/metaImageUtils.cxx index 1936ffcd19b9759da0bd179bb644a7b880b82258..35c45f807c55355bc03e3d30cd73d9d6e6c2f3d1 100644 --- a/Utilities/ITK/Utilities/MetaIO/metaImageUtils.cxx +++ b/Utilities/ITK/Utilities/MetaIO/metaImageUtils.cxx @@ -3,8 +3,8 @@ Program: MetaIO Module: $RCSfile: metaImageUtils.cxx,v $ Language: C++ - Date: $Date: 2008-04-09 01:44:28 $ - Version: $Revision: 1.12 $ + Date: $Date: 2009-06-21 21:54:05 $ + Version: $Revision: 1.13 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -16,6 +16,12 @@ =========================================================================*/ #include <stdio.h> +#ifdef _MSC_VER +#pragma warning(disable:4702) +#pragma warning(disable:4996) +#endif + + #include "metaImageTypes.h" #include <string.h> diff --git a/Utilities/ITK/Utilities/MetaIO/metaOutput.cxx b/Utilities/ITK/Utilities/MetaIO/metaOutput.cxx index 50e8f4f77a35140cc0ab1ae88b625e6d36c941ed..53219c05b6dd4c3e10691f039bf069959dd4b8d0 100644 --- a/Utilities/ITK/Utilities/MetaIO/metaOutput.cxx +++ b/Utilities/ITK/Utilities/MetaIO/metaOutput.cxx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: metaOutput.cxx,v $ Language: C++ - Date: $Date: 2008-04-24 19:13:40 $ - Version: $Revision: 1.21 $ + Date: $Date: 2009-06-21 21:54:04 $ + Version: $Revision: 1.22 $ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -16,6 +16,7 @@ =========================================================================*/ #ifdef _MSC_VER #pragma warning(disable:4702) +#pragma warning(disable:4996) #endif #include "metaOutput.h" @@ -33,6 +34,7 @@ #endif #include <string.h> +#include <time.h> #include <typeinfo> @@ -40,6 +42,18 @@ namespace METAIO_NAMESPACE { #endif + +/** Stolen from kwsys */ +METAIO_STL::string GetCurrentDateTime(const char* format) +{ + char buf[1024]; + time_t t; + time(&t); + strftime(buf, sizeof(buf), format, localtime(&t)); + return METAIO_STL::string(buf); +} + + /****/ MetaOutputStream:: MetaOutputStream() @@ -394,9 +408,9 @@ METAIO_STL::string MetaOutput::GenerateXML(const char* filename) buffer += " version=\""+m_CurrentVersion+"\">\n"; buffer += "<Creation date=\"" - + METAIO_KWSYS::SystemTools::GetCurrentDateTime("%Y%m%d") + "\""; + + GetCurrentDateTime("%Y%m%d") + "\""; buffer += " time=\"" - + METAIO_KWSYS::SystemTools::GetCurrentDateTime("%H%M%S") + "\""; + + GetCurrentDateTime("%H%M%S") + "\""; buffer += " hostname=\""+this->GetHostname() +"\""; buffer += " hostIP=\""+this->GetHostip() +"\""; buffer += " user=\"" + this->GetUsername() + "\"/>\n"; diff --git a/Utilities/ITK/Utilities/MetaIO/metaUtils.cxx b/Utilities/ITK/Utilities/MetaIO/metaUtils.cxx index a80611342f0815d8e3f654a1d416ff647bda1bf0..53d5fd33dbc3c09d076df11464ca39948a62e616 100644 --- a/Utilities/ITK/Utilities/MetaIO/metaUtils.cxx +++ b/Utilities/ITK/Utilities/MetaIO/metaUtils.cxx @@ -3,8 +3,8 @@ Program: MetaIO Module: $RCSfile: metaUtils.cxx,v $ Language: C++ - Date: $Date: 2008-11-06 15:55:28 $ - Version: $Revision: 1.56 $ + Date: $Date: 2009-07-08 15:54:08 $ + Version: $Revision: 1.58 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -16,6 +16,7 @@ =========================================================================*/ #ifdef _MSC_VER #pragma warning(disable:4702) +#pragma warning(disable:4996) #endif #include "metaUtils.h" @@ -713,7 +714,10 @@ unsigned char * MET_PerformCompression(const unsigned char * source, // when the output is bigger than the input (true for small images) if(j+count>=buffer_size) { - compressedData = (unsigned char *)realloc( compressedData, j+count+1 ); + unsigned char* compressedDataTemp = new unsigned char[j+count+1]; + memcpy(compressedDataTemp,compressedData,buffer_size); + delete [] compressedData; + compressedData = compressedDataTemp; } memcpy((char*)compressedData+j, (char *)output_buffer, count); @@ -727,7 +731,10 @@ unsigned char * MET_PerformCompression(const unsigned char * source, { if(j+count>=buffer_size) { - compressedData = (unsigned char *)realloc( compressedData, j+count+1 ); + unsigned char* compressedDataTemp = new unsigned char[j+count+1]; + memcpy(compressedDataTemp,compressedData,buffer_size); + delete [] compressedData; + compressedData = compressedDataTemp; } memcpy((char*)compressedData+j, (char*)output_buffer, count); } diff --git a/Utilities/ITK/Utilities/MetaIO/metaUtils.h b/Utilities/ITK/Utilities/MetaIO/metaUtils.h index 8b52c4fd2553c12b4ba984c28b2b7daa73dc223b..e3ac8f3f57f7d89613641ec36020998c68861b43 100644 --- a/Utilities/ITK/Utilities/MetaIO/metaUtils.h +++ b/Utilities/ITK/Utilities/MetaIO/metaUtils.h @@ -3,8 +3,8 @@ Program: MetaIO Module: $RCSfile: metaUtils.h,v $ Language: C++ - Date: $Date: 2008-11-12 20:14:51 $ - Version: $Revision: 1.43 $ + Date: $Date: 2009-06-21 21:54:05 $ + Version: $Revision: 1.44 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -48,6 +48,7 @@ #pragma warning( disable:4284 ) #pragma warning( disable:4702 ) #pragma warning( disable:4786 ) +#pragma warning( disable:4996 ) #endif #include <vector> diff --git a/Utilities/ITK/Utilities/NrrdIO/read.c b/Utilities/ITK/Utilities/NrrdIO/read.c index 6ab9dc66991cf0b44e0761d118b73af1c41080a3..17a395f950ba3432fcee657231638130511efb20 100644 --- a/Utilities/ITK/Utilities/NrrdIO/read.c +++ b/Utilities/ITK/Utilities/NrrdIO/read.c @@ -397,6 +397,7 @@ nrrdRead (Nrrd *nrrd, FILE *file, NrrdIoState *nio) { void _nrrdSplitName (char **dirP, char **baseP, const char *name) { char *where; + char separator; if (dirP) { *dirP = (char *)airFree(*dirP); @@ -404,7 +405,19 @@ _nrrdSplitName (char **dirP, char **baseP, const char *name) { if (baseP) { *baseP = (char *)airFree(*baseP); } - where = strrchr(name, '/'); + + /* for unix, the separator is '/' */ + separator = '/'; + + /* for windows, the separator might be '\' */ +#ifdef _WIN32 + if (strchr(name, '\\')) { + separator = '\\'; + } +#endif + + where = strrchr(name, separator); + /* we found a valid break if the last directory character is somewhere in the string except the last character */ if (where && airStrlen(where) > 1) { diff --git a/Utilities/ITK/Utilities/NrrdIO/reorder.c b/Utilities/ITK/Utilities/NrrdIO/reorder.c index 5b873720ecc522285b076ba9979c5f383ae9d399..04841d36779d441b6fe845397f36ea53f80c73a4 100644 --- a/Utilities/ITK/Utilities/NrrdIO/reorder.c +++ b/Utilities/ITK/Utilities/NrrdIO/reorder.c @@ -22,6 +22,10 @@ 3. This notice may not be removed or altered from any source distribution. */ +#if defined(__GNUC__) && (__GNUC__ == 4 && __GNUC_MINOR__ >= 3) +#pragma GCC diagnostic ignored "-Warray-bounds" +#endif + #include "NrrdIO.h" #include "privateNrrd.h" diff --git a/Utilities/ITK/Utilities/NrrdIO/subset.c b/Utilities/ITK/Utilities/NrrdIO/subset.c index 5663d20c5a82143e5b52330c1b1e3fdfef83ec0f..722db03aac06651b1031fb2b6c0bbe7a854535b8 100644 --- a/Utilities/ITK/Utilities/NrrdIO/subset.c +++ b/Utilities/ITK/Utilities/NrrdIO/subset.c @@ -22,6 +22,10 @@ 3. This notice may not be removed or altered from any source distribution. */ +#if defined(__GNUC__) && (__GNUC__ == 4 && __GNUC_MINOR__ >= 3) +#pragma GCC diagnostic ignored "-Warray-bounds" +#endif + #include "NrrdIO.h" #include "privateNrrd.h" diff --git a/Utilities/ITK/Utilities/expat/expat.h b/Utilities/ITK/Utilities/expat/expat.h index d4eee5cdd35d7b5f14c4ecb4dccc39eeb51f1cc0..c48e67e1c80117804f942d9e003b2922f518c768 100644 --- a/Utilities/ITK/Utilities/expat/expat.h +++ b/Utilities/ITK/Utilities/expat/expat.h @@ -11,7 +11,7 @@ See the file COPYING for copying permission. #include "expatDllConfig.h" #if defined(_WIN32) && !defined(ITK_EXPAT_STATIC) -# if defined(vtkexpat_EXPORTS) +# if defined(ITKEXPAT_EXPORTS) # define XMLPARSEAPI(type) __declspec( dllexport ) type __cdecl # else # define XMLPARSEAPI(type) __declspec( dllimport ) type __cdecl diff --git a/Utilities/ITK/Utilities/gdcm/src/CMakeLists.txt b/Utilities/ITK/Utilities/gdcm/src/CMakeLists.txt index ca9597c694c36824ded331e7e46b616852f10f47..8ee0af4991a05ebdf16478600244e5b1e14e052a 100644 --- a/Utilities/ITK/Utilities/gdcm/src/CMakeLists.txt +++ b/Utilities/ITK/Utilities/gdcm/src/CMakeLists.txt @@ -69,6 +69,7 @@ TARGET_LINK_LIBRARIES(itkgdcm itkopenjpeg ${UUID_LIBRARIES} ) +SET_TARGET_PROPERTIES(itkgdcm PROPERTIES DEFINE_SYMBOL gdcm_EXPORTS) IF(WIN32) IF(NOT BORLAND) # rpcrt4 -> UuidCreate @@ -100,3 +101,8 @@ IF(CMAKE_COMPILER_IS_GNUCXX) SET_SOURCE_FILES_PROPERTIES(gdcmPixelWriteConvert.cxx PROPERTIES COMPILE_FLAGS -w) SET_SOURCE_FILES_PROPERTIES(gdcmFile.cxx PROPERTIES COMPILE_FLAGS -w) ENDIF(CMAKE_COMPILER_IS_GNUCXX) + +IF(CMAKE_COMPILER_IS_GNUCXX) + SET_SOURCE_FILES_PROPERTIES(gdcmDocument.cxx PROPERTIES COMPILE_FLAGS -fno-strict-aliasing) + SET_SOURCE_FILES_PROPERTIES(gdcmSerieHelper.cxx PROPERTIES COMPILE_FLAGS -Wno-uninitialized) +ENDIF(CMAKE_COMPILER_IS_GNUCXX) diff --git a/Utilities/ITK/Utilities/kwsys/CMakeLists.txt b/Utilities/ITK/Utilities/kwsys/CMakeLists.txt index 40dad9c05d1dff657060e4191e69cc13377e8fbc..9e7b1279437e686f6d4dd569ac44aeb692c9b58d 100644 --- a/Utilities/ITK/Utilities/kwsys/CMakeLists.txt +++ b/Utilities/ITK/Utilities/kwsys/CMakeLists.txt @@ -337,14 +337,19 @@ ENDIF(NOT CMAKE_COMPILER_IS_GNUCXX) #----------------------------------------------------------------------------- # Configure Large File Support. +KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_CSTDIO + "Checking whether header cstdio is available" DIRECT) SET(KWSYS_LFS_AVAILABLE 0) IF(KWSYS_LFS_REQUESTED) # Large File Support is requested. SET(KWSYS_LFS_REQUESTED 1) # Check for large file support. + SET(KWSYS_PLATFORM_CXX_TEST_DEFINES + -DKWSYS_CXX_HAS_CSTDIO=${KWSYS_CXX_HAS_CSTDIO}) KWSYS_PLATFORM_CXX_TEST_RUN(KWSYS_LFS_WORKS "Checking for Large File Support" DIRECT) + SET(KWSYS_PLATFORM_CXX_TEST_DEFINES) IF(KWSYS_LFS_WORKS) SET(KWSYS_LFS_AVAILABLE 1) @@ -442,6 +447,11 @@ ELSE(KWSYS_IOS_USE_ANSI AND NOT WATCOM) KWSYS_PLATFORM_CXX_TEST(KWSYS_STL_STRING_HAVE_ISTREAM "Checking whether stl string has istream operator>>" DIRECT) ENDIF(KWSYS_IOS_USE_ANSI AND NOT WATCOM) +SET(KWSYS_PLATFORM_CXX_TEST_DEFINES + -DKWSYS_IOS_USE_ANSI=${KWSYS_IOS_USE_ANSI} + -DKWSYS_IOS_HAVE_STD=${KWSYS_IOS_HAVE_STD}) +KWSYS_PLATFORM_CXX_TEST(KWSYS_IOS_HAVE_BINARY + "Checking whether ios has binary openmode" DIRECT) SET(KWSYS_PLATFORM_CXX_TEST_DEFINES) KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_NULL_TEMPLATE_ARGS @@ -848,6 +858,12 @@ ENDIF(KWSYS_ENABLE_C AND KWSYS_C_SRCS) # line to configure the namespace in the C and C++ source files. ADD_DEFINITIONS("-DKWSYS_NAMESPACE=${KWSYS_NAMESPACE}") +IF(KWSYS_USE_String) + # Activate code in "String.c". See the comment in the source. + SET_SOURCE_FILES_PROPERTIES(String.c PROPERTIES + COMPILE_FLAGS "-DKWSYS_STRING_C") +ENDIF(KWSYS_USE_String) + #----------------------------------------------------------------------------- # Process execution on windows needs to build a forwarding executable # that works around a Win9x bug. We encode the executable into a C diff --git a/Utilities/ITK/Utilities/kwsys/Configure.h.in b/Utilities/ITK/Utilities/kwsys/Configure.h.in index 9f34eac3aa63a5fb33129c140d71baa4fe5dcb79..847ce3c4350b9829296b3ade429ae30a4f7f284b 100644 --- a/Utilities/ITK/Utilities/kwsys/Configure.h.in +++ b/Utilities/ITK/Utilities/kwsys/Configure.h.in @@ -22,6 +22,13 @@ # define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT #endif +/* Disable some warnings inside kwsys source files. */ +#if defined(KWSYS_NAMESPACE) +# if defined(__BORLANDC__) +# pragma warn -8027 /* function not inlined. */ +# endif +#endif + /* Whether kwsys namespace is "kwsys". */ #define @KWSYS_NAMESPACE@_NAME_IS_KWSYS @KWSYS_NAME_IS_KWSYS@ diff --git a/Utilities/ITK/Utilities/kwsys/Configure.hxx.in b/Utilities/ITK/Utilities/kwsys/Configure.hxx.in index fc77b35a57155d1baf8c1b1b09c60e996bd6fa71..cdf6d93d9db18c1ce6570e194de2673387201180 100644 --- a/Utilities/ITK/Utilities/kwsys/Configure.hxx.in +++ b/Utilities/ITK/Utilities/kwsys/Configure.hxx.in @@ -32,6 +32,9 @@ /* Whether old C++ <strstrea.h> header is to be used. */ #define @KWSYS_NAMESPACE@_IOS_USE_STRSTREA_H @KWSYS_IOS_USE_STRSTREA_H@ +/* Whether C++ streams support the ios::binary openmode. */ +#define @KWSYS_NAMESPACE@_IOS_HAVE_BINARY @KWSYS_IOS_HAVE_BINARY@ + /* Whether STL is in std namespace. */ #define @KWSYS_NAMESPACE@_STL_HAVE_STD @KWSYS_STL_HAVE_STD@ @@ -63,6 +66,13 @@ # define @KWSYS_NAMESPACE@_ios @KWSYS_NAMESPACE@_ios #endif +/* Define the ios::binary openmode macro. */ +#if @KWSYS_NAMESPACE@_IOS_HAVE_BINARY +# define @KWSYS_NAMESPACE@_ios_binary @KWSYS_NAMESPACE@_ios::ios::binary +#else +# define @KWSYS_NAMESPACE@_ios_binary 0 +#endif + /* Whether the cstddef header is available. */ #define @KWSYS_NAMESPACE@_CXX_HAS_CSTDDEF @KWSYS_CXX_HAS_CSTDDEF@ @@ -133,6 +143,7 @@ # define kwsys_stl @KWSYS_NAMESPACE@_stl # define kwsys_ios @KWSYS_NAMESPACE@_ios # define kwsys @KWSYS_NAMESPACE@ +# define kwsys_ios_binary @KWSYS_NAMESPACE@_ios_binary # endif # define KWSYS_NAME_IS_KWSYS @KWSYS_NAMESPACE@_NAME_IS_KWSYS # define KWSYS_STL_HAVE_STD @KWSYS_NAMESPACE@_STL_HAVE_STD @@ -141,6 +152,7 @@ # define KWSYS_IOS_USE_SSTREAM @KWSYS_NAMESPACE@_IOS_USE_SSTREAM # define KWSYS_IOS_USE_STRSTREAM_H @KWSYS_NAMESPACE@_IOS_USE_STRSTREAM_H # define KWSYS_IOS_USE_STRSTREA_H @KWSYS_NAMESPACE@_IOS_USE_STRSTREA_H +# define KWSYS_IOS_HAVE_BINARY @KWSYS_NAMESPACE@_IOS_HAVE_BINARY # define KWSYS_STAT_HAS_ST_MTIM @KWSYS_NAMESPACE@_STAT_HAS_ST_MTIM # define KWSYS_CXX_HAS_CSTDDEF @KWSYS_NAMESPACE@_CXX_HAS_CSTDDEF # define KWSYS_STL_STRING_HAVE_OSTREAM @KWSYS_NAMESPACE@_STL_STRING_HAVE_OSTREAM diff --git a/Utilities/ITK/Utilities/kwsys/Glob.cxx b/Utilities/ITK/Utilities/kwsys/Glob.cxx index 4c17d63549598f320678181454d8227a89ff283b..9feeae352ef96f5382768203ccef1430008991e3 100644 --- a/Utilities/ITK/Utilities/kwsys/Glob.cxx +++ b/Utilities/ITK/Utilities/kwsys/Glob.cxx @@ -84,7 +84,8 @@ kwsys_stl::vector<kwsys_stl::string>& Glob::GetFiles() //---------------------------------------------------------------------------- kwsys_stl::string Glob::PatternToRegex(const kwsys_stl::string& pattern, - bool require_whole_string) + bool require_whole_string, + bool preserve_case) { // Incrementally build the regular expression from the pattern. kwsys_stl::string regex = require_whole_string? "^" : ""; @@ -195,10 +196,13 @@ kwsys_stl::string Glob::PatternToRegex(const kwsys_stl::string& pattern, { // On case-insensitive systems file names are converted to lower // case before matching. - ch = tolower(ch); + if(!preserve_case) + { + ch = tolower(ch); + } } #endif - + (void)preserve_case; // Store the character. regex.append(1, static_cast<char>(ch)); } diff --git a/Utilities/ITK/Utilities/kwsys/Glob.hxx.in b/Utilities/ITK/Utilities/kwsys/Glob.hxx.in index dc4ad58db7500f8f0d2a4c0d755c18020a0872b1..33afcf92dd48fded947357731ec43d0c008e0a16 100644 --- a/Utilities/ITK/Utilities/kwsys/Glob.hxx.in +++ b/Utilities/ITK/Utilities/kwsys/Glob.hxx.in @@ -79,7 +79,8 @@ public: whole strings, but may be disabled to support concatenating expressions more easily (regex1|regex2|etc). */ static kwsys_stl::string PatternToRegex(const kwsys_stl::string& pattern, - bool require_whole_string = true); + bool require_whole_string = true, + bool preserve_case = false); protected: //! Process directory diff --git a/Utilities/ITK/Utilities/kwsys/MD5.c b/Utilities/ITK/Utilities/kwsys/MD5.c index 35a6f1cdb308758e3fc4021929f450b32f892b6f..07314f4fe9ecbf683d6904564a3c163afbc4f47f 100644 --- a/Utilities/ITK/Utilities/kwsys/MD5.c +++ b/Utilities/ITK/Utilities/kwsys/MD5.c @@ -20,6 +20,7 @@ # include "MD5.h.in" #endif +#include <stddef.h> /* size_t */ #include <stdlib.h> /* malloc, free */ #include <string.h> /* memcpy, strlen */ @@ -53,7 +54,7 @@ ghost@aladdin.com */ -/* $Id: MD5.c,v 1.1 2007-03-14 19:12:10 king Exp $ */ +/* $Id: MD5.c,v 1.3 2009-07-08 20:18:19 david.cole Exp $ */ /* Independent implementation of MD5 (RFC 1321). @@ -238,7 +239,8 @@ md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/) # define xbuf X /* (static only) */ # endif for (i = 0; i < 16; ++i, xp += 4) - xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24); + xbuf[i] = (md5_word_t)(xp[0] + (xp[1] << 8) + + (xp[2] << 16) + (xp[3] << 24)); } #endif } @@ -369,25 +371,25 @@ static void md5_init(md5_state_t *pms) } /* Append a string to the message. */ -static void md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes) +static void md5_append(md5_state_t *pms, const md5_byte_t *data, size_t nbytes) { const md5_byte_t *p = data; - int left = nbytes; - int offset = (pms->count[0] >> 3) & 63; + size_t left = nbytes; + size_t offset = (pms->count[0] >> 3) & 63; md5_word_t nbits = (md5_word_t)(nbytes << 3); if (nbytes <= 0) return; /* Update the message length. */ - pms->count[1] += nbytes >> 29; + pms->count[1] += (md5_word_t)(nbytes >> 29); pms->count[0] += nbits; if (pms->count[0] < nbits) pms->count[1]++; /* Process an initial partial block. */ if (offset) { - int copy = (offset + nbytes > 64 ? 64 - offset : nbytes); + size_t copy = (offset + nbytes > 64 ? 64 - offset : nbytes); memcpy(pms->buf + offset, p, copy); if (offset + copy < 64) @@ -474,7 +476,7 @@ void kwsysMD5_Append(kwsysMD5* md5, unsigned char const* data, int length) { length = (int)strlen((char const*)data); } - md5_append(&md5->md5_state, (md5_byte_t const*)data, length); + md5_append(&md5->md5_state, (md5_byte_t const*)data, (size_t)length); } /*--------------------------------------------------------------------------*/ diff --git a/Utilities/ITK/Utilities/kwsys/ProcessUNIX.c b/Utilities/ITK/Utilities/kwsys/ProcessUNIX.c index 938683820ebf86af6030de37848bc44d4554f221..51b209e6e3a1846ac1770c68b7434bf172dd8fdb 100644 --- a/Utilities/ITK/Utilities/kwsys/ProcessUNIX.c +++ b/Utilities/ITK/Utilities/kwsys/ProcessUNIX.c @@ -13,11 +13,13 @@ =========================================================================*/ #include "kwsysPrivate.h" #include KWSYS_HEADER(Process.h) +#include KWSYS_HEADER(System.h) /* Work-around CMake dependency scanning limitation. This must duplicate the above list of headers. */ #if 0 # include "Process.h.in" +# include "System.h.in" #endif /* @@ -67,6 +69,12 @@ do. #undef __BEOS__ #endif +#if defined(__VMS) +# define KWSYSPE_VMS_NONBLOCK , O_NONBLOCK +#else +# define KWSYSPE_VMS_NONBLOCK +#endif + #if defined(KWSYS_C_HAS_PTRDIFF_T) && KWSYS_C_HAS_PTRDIFF_T typedef ptrdiff_t kwsysProcess_ptrdiff_t; #else @@ -100,7 +108,7 @@ static inline void kwsysProcess_usleep(unsigned int msec) * pipes' file handles to be non-blocking and just poll them directly * without select(). */ -#if !defined(__BEOS__) +#if !defined(__BEOS__) && !defined(__VMS) # define KWSYSPE_USE_SELECT 1 #endif @@ -156,7 +164,8 @@ static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout, kwsysProcessTime* timeoutTime); static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime, double* userTimeout, - kwsysProcessTimeNative* timeoutLength); + kwsysProcessTimeNative* timeoutLength, + int zeroIsExpired); static kwsysProcessTime kwsysProcessTimeGetCurrent(void); static double kwsysProcessTimeToDouble(kwsysProcessTime t); static kwsysProcessTime kwsysProcessTimeFromDouble(double d); @@ -169,6 +178,9 @@ static void kwsysProcessRestoreDefaultSignalHandlers(void); static pid_t kwsysProcessFork(kwsysProcess* cp, kwsysProcessCreateInformation* si); static void kwsysProcessKill(pid_t process_id); +#if defined(__VMS) +static int kwsysProcessSetVMSFeature(const char* name, int value); +#endif static int kwsysProcessesAdd(kwsysProcess* cp); static void kwsysProcessesRemove(kwsysProcess* cp); #if KWSYSPE_USE_SIGINFO @@ -177,7 +189,6 @@ static void kwsysProcessesSignalHandler(int signum, siginfo_t* info, #else static void kwsysProcessesSignalHandler(int signum); #endif -static char** kwsysProcessParseVerbatimCommand(const char* command); /*--------------------------------------------------------------------------*/ /* Structure containing data used to implement the child's execution. */ @@ -412,7 +423,7 @@ int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command) /* In order to run the given command line verbatim we need to parse it. */ newCommands[cp->NumberOfCommands] = - kwsysProcessParseVerbatimCommand(*command); + kwsysSystem_Parse_CommandForUnix(*command, 0); if(!newCommands[cp->NumberOfCommands]) { /* Out of memory. */ @@ -719,6 +730,15 @@ void kwsysProcess_Execute(kwsysProcess* cp) return; } +#if defined(__VMS) + /* Make sure pipes behave like streams on VMS. */ + if(!kwsysProcessSetVMSFeature("DECC$STREAM_PIPE", 1)) + { + kwsysProcessCleanup(cp, 1); + return; + } +#endif + /* Save the real working directory of this process and change to the working directory for the child processes. This is needed to make pipe file paths evaluate correctly. */ @@ -758,7 +778,7 @@ void kwsysProcess_Execute(kwsysProcess* cp) { /* Create the pipe. */ int p[2]; - if(pipe(p) < 0) + if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0) { kwsysProcessCleanup(cp, 1); return; @@ -1097,7 +1117,7 @@ static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length, } if(kwsysProcessGetTimeoutLeft(&wd->TimeoutTime, wd->User?wd->UserTimeout:0, - &timeoutLength)) + &timeoutLength, 0)) { /* Timeout has already expired. */ wd->Expired = 1; @@ -1184,11 +1204,24 @@ static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length, else if (n == 0) /* EOF */ { /* We are done reading from this pipe. */ - kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]); - --cp->PipesLeft; +#if defined(__VMS) + if(!cp->CommandsLeft) +#endif + { + kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]); + --cp->PipesLeft; + } } else if (n < 0) /* error */ { +#if defined(__VMS) + if(!cp->CommandsLeft) + { + kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]); + --cp->PipesLeft; + } + else +#endif if((errno != EINTR) && (errno != EAGAIN)) { strncpy(cp->ErrorMessage,strerror(errno), @@ -1210,14 +1243,7 @@ static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length, } if(kwsysProcessGetTimeoutLeft(&wd->TimeoutTime, wd->User?wd->UserTimeout:0, - &timeoutLength)) - { - /* Timeout has already expired. */ - wd->Expired = 1; - return 1; - } - - if((timeoutLength.tv_sec == 0) && (timeoutLength.tv_usec == 0)) + &timeoutLength, 1)) { /* Timeout has already expired. */ wd->Expired = 1; @@ -1571,6 +1597,11 @@ static int kwsysProcessSetNonBlocking(int fd) return flags >= 0; } +/*--------------------------------------------------------------------------*/ +#if defined(__VMS) +int decc$set_child_standard_streams(int fd1, int fd2, int fd3); +#endif + /*--------------------------------------------------------------------------*/ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex, kwsysProcessCreateInformation* si, int* readEnd) @@ -1622,7 +1653,7 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex, { /* Create the pipe. */ int p[2]; - if(pipe(p) < 0) + if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0) { return 0; } @@ -1680,7 +1711,14 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex, } /* Fork off a child process. */ +#if defined(__VMS) + /* VMS needs vfork and execvp to be in the same function because + they use setjmp/longjmp to run the child startup code in the + parent! TODO: OptionDetach. */ + cp->ForkPIDs[prIndex] = vfork(); +#else cp->ForkPIDs[prIndex] = kwsysProcessFork(cp, si); +#endif if(cp->ForkPIDs[prIndex] < 0) { return 0; @@ -1688,6 +1726,10 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex, if(cp->ForkPIDs[prIndex] == 0) { +#if defined(__VMS) + /* Specify standard pipes for child process. */ + decc$set_child_standard_streams(si->StdIn, si->StdOut, si->StdErr); +#else /* Close the read end of the error reporting pipe. */ close(si->ErrorPipe[0]); @@ -1717,14 +1759,21 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex, /* Restore all default signal handlers. */ kwsysProcessRestoreDefaultSignalHandlers(); +#endif /* Execute the real process. If successful, this does not return. */ execvp(cp->Commands[prIndex][0], cp->Commands[prIndex]); + /* TODO: What does VMS do if the child fails to start? */ /* Failure. Report error to parent and terminate. */ kwsysProcessChildErrorExit(si->ErrorPipe[1]); } +#if defined(__VMS) + /* Restore the standard pipes of this process. */ + decc$set_child_standard_streams(0, 1, 2); +#endif + /* A child has been created. */ ++cp->CommandsLeft; @@ -1905,7 +1954,8 @@ static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout, Returns 1 if the time has already arrived, and 0 otherwise. */ static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime, double* userTimeout, - kwsysProcessTimeNative* timeoutLength) + kwsysProcessTimeNative* timeoutLength, + int zeroIsExpired) { if(timeoutTime->tv_sec < 0) { @@ -1925,7 +1975,8 @@ static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime, timeLeft.tv_usec = 0; } - if(timeLeft.tv_sec < 0) + if(timeLeft.tv_sec < 0 || + (timeLeft.tv_sec == 0 && timeLeft.tv_usec == 0 && zeroIsExpired)) { /* Timeout has already expired. */ return 1; @@ -2263,6 +2314,7 @@ static void kwsysProcessExit(void) } /*--------------------------------------------------------------------------*/ +#if !defined(__VMS) static pid_t kwsysProcessFork(kwsysProcess* cp, kwsysProcessCreateInformation* si) { @@ -2270,9 +2322,6 @@ static pid_t kwsysProcessFork(kwsysProcess* cp, if(cp->OptionDetach) { /* Create an intermediate process. */ -#ifdef __VMS -#define fork vfork -#endif pid_t middle_pid = fork(); if(middle_pid < 0) { @@ -2320,6 +2369,7 @@ static pid_t kwsysProcessFork(kwsysProcess* cp, return fork(); } } +#endif /*--------------------------------------------------------------------------*/ /* We try to obtain process information by invoking the ps command. @@ -2440,6 +2490,19 @@ static void kwsysProcessKill(pid_t process_id) } } +/*--------------------------------------------------------------------------*/ +#if defined(__VMS) +int decc$feature_get_index(const char* name); +int decc$feature_set_value(int index, int mode, int value); +static int kwsysProcessSetVMSFeature(const char* name, int value) +{ + int i; + errno = 0; + i = decc$feature_get_index(name); + return i >= 0 && (decc$feature_set_value(i, 1, value) >= 0 || errno == 0); +} +#endif + /*--------------------------------------------------------------------------*/ /* Global set of executing processes for use by the signal handler. This global instance will be zero-initialized by the compiler. */ @@ -2481,7 +2544,7 @@ static int kwsysProcessesAdd(kwsysProcess* cp) { /* Create the pipe. */ int p[2]; - if(pipe(p) < 0) + if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0) { return 0; } @@ -2667,257 +2730,3 @@ static void kwsysProcessesSignalHandler(int signum } #endif } - -/*--------------------------------------------------------------------------*/ -static int kwsysProcessAppendByte(char* local, - char** begin, char** end, - int* size, char c) -{ - /* Allocate space for the character. */ - if((*end - *begin) >= *size) - { - kwsysProcess_ptrdiff_t length = *end - *begin; - char* newBuffer = (char*)malloc((size_t)(*size*2)); - if(!newBuffer) - { - return 0; - } - memcpy(newBuffer, *begin, (size_t)(length)*sizeof(char)); - if(*begin != local) - { - free(*begin); - } - *begin = newBuffer; - *end = *begin + length; - *size *= 2; - } - - /* Store the character. */ - *(*end)++ = c; - return 1; -} - -/*--------------------------------------------------------------------------*/ -static int kwsysProcessAppendArgument(char** local, - char*** begin, char*** end, - int* size, - char* arg_local, - char** arg_begin, char** arg_end, - int* arg_size) -{ - /* Append a null-terminator to the argument string. */ - if(!kwsysProcessAppendByte(arg_local, arg_begin, arg_end, arg_size, '\0')) - { - return 0; - } - - /* Allocate space for the argument pointer. */ - if((*end - *begin) >= *size) - { - kwsysProcess_ptrdiff_t length = *end - *begin; - char** newPointers = (char**)malloc((size_t)(*size)*2*sizeof(char*)); - if(!newPointers) - { - return 0; - } - memcpy(newPointers, *begin, (size_t)(length)*sizeof(char*)); - if(*begin != local) - { - free(*begin); - } - *begin = newPointers; - *end = *begin + length; - *size *= 2; - } - - /* Allocate space for the argument string. */ - **end = (char*)malloc((size_t)(*arg_end - *arg_begin)); - if(!**end) - { - return 0; - } - - /* Store the argument in the command array. */ - memcpy(**end, *arg_begin,(size_t)(*arg_end - *arg_begin)); - ++(*end); - - /* Reset the argument to be empty. */ - *arg_end = *arg_begin; - - return 1; -} - -/*--------------------------------------------------------------------------*/ -#define KWSYSPE_LOCAL_BYTE_COUNT 1024 -#define KWSYSPE_LOCAL_ARGS_COUNT 32 -static char** kwsysProcessParseVerbatimCommand(const char* command) -{ - /* Create a buffer for argument pointers during parsing. */ - char* local_pointers[KWSYSPE_LOCAL_ARGS_COUNT]; - int pointers_size = KWSYSPE_LOCAL_ARGS_COUNT; - char** pointer_begin = local_pointers; - char** pointer_end = pointer_begin; - - /* Create a buffer for argument strings during parsing. */ - char local_buffer[KWSYSPE_LOCAL_BYTE_COUNT]; - int buffer_size = KWSYSPE_LOCAL_BYTE_COUNT; - char* buffer_begin = local_buffer; - char* buffer_end = buffer_begin; - - /* Parse the command string. Try to behave like a UNIX shell. */ - char** newCommand = 0; - const char* c = command; - int in_argument = 0; - int in_escape = 0; - int in_single = 0; - int in_double = 0; - int failed = 0; - for(;*c; ++c) - { - if(in_escape) - { - /* This character is escaped so do no special handling. */ - if(!in_argument) - { - in_argument = 1; - } - if(!kwsysProcessAppendByte(local_buffer, &buffer_begin, - &buffer_end, &buffer_size, *c)) - { - failed = 1; - break; - } - in_escape = 0; - } - else if(*c == '\\' && !in_single) - { - /* The next character should be escaped. */ - in_escape = 1; - } - else if(*c == '\'' && !in_double) - { - /* Enter or exit single-quote state. */ - if(in_single) - { - in_single = 0; - } - else - { - in_single = 1; - if(!in_argument) - { - in_argument = 1; - } - } - } - else if(*c == '"' && !in_single) - { - /* Enter or exit double-quote state. */ - if(in_double) - { - in_double = 0; - } - else - { - in_double = 1; - if(!in_argument) - { - in_argument = 1; - } - } - } - else if(isspace((unsigned char) *c)) - { - if(in_argument) - { - if(in_single || in_double) - { - /* This space belongs to a quoted argument. */ - if(!kwsysProcessAppendByte(local_buffer, &buffer_begin, - &buffer_end, &buffer_size, *c)) - { - failed = 1; - break; - } - } - else - { - /* This argument has been terminated by whitespace. */ - if(!kwsysProcessAppendArgument(local_pointers, &pointer_begin, - &pointer_end, &pointers_size, - local_buffer, &buffer_begin, - &buffer_end, &buffer_size)) - { - failed = 1; - break; - } - in_argument = 0; - } - } - } - else - { - /* This character belong to an argument. */ - if(!in_argument) - { - in_argument = 1; - } - if(!kwsysProcessAppendByte(local_buffer, &buffer_begin, - &buffer_end, &buffer_size, *c)) - { - failed = 1; - break; - } - } - } - - /* Finish the last argument. */ - if(in_argument) - { - if(!kwsysProcessAppendArgument(local_pointers, &pointer_begin, - &pointer_end, &pointers_size, - local_buffer, &buffer_begin, - &buffer_end, &buffer_size)) - { - failed = 1; - } - } - - /* If we still have memory allocate space for the new command - buffer. */ - if(!failed) - { - kwsysProcess_ptrdiff_t n = pointer_end - pointer_begin; - newCommand = (char**)malloc((size_t)(n+1)*sizeof(char*)); - } - - if(newCommand) - { - /* Copy the arguments into the new command buffer. */ - kwsysProcess_ptrdiff_t n = pointer_end - pointer_begin; - memcpy(newCommand, pointer_begin, sizeof(char*)*(size_t)(n)); - newCommand[n] = 0; - } - else - { - /* Free arguments already allocated. */ - while(pointer_end != pointer_begin) - { - free(*(--pointer_end)); - } - } - - /* Free temporary buffers. */ - if(pointer_begin != local_pointers) - { - free(pointer_begin); - } - if(buffer_begin != local_buffer) - { - free(buffer_begin); - } - - /* Return the final command buffer. */ - return newCommand; -} - diff --git a/Utilities/ITK/Utilities/kwsys/ProcessWin32.c b/Utilities/ITK/Utilities/kwsys/ProcessWin32.c index 94de585a1c4e4b0aecb6293e05f641472bd27f10..0ab9b602ed0edc0f474e719b552b716b46e8b346 100644 --- a/Utilities/ITK/Utilities/kwsys/ProcessWin32.c +++ b/Utilities/ITK/Utilities/kwsys/ProcessWin32.c @@ -806,7 +806,7 @@ int kwsysProcess_SetPipeFile(kwsysProcess* cp, int pipe, const char* file) } if(file) { - *pfile = malloc(strlen(file)+1); + *pfile = (char*)malloc(strlen(file)+1); if(!*pfile) { return 0; @@ -1666,7 +1666,7 @@ int kwsysProcessInitialize(kwsysProcess* cp) cp->RealWorkingDirectoryLength = GetCurrentDirectory(0, 0); if(cp->RealWorkingDirectoryLength > 0) { - cp->RealWorkingDirectory = malloc(cp->RealWorkingDirectoryLength); + cp->RealWorkingDirectory = (char*)malloc(cp->RealWorkingDirectoryLength); if(!cp->RealWorkingDirectory) { return 0; @@ -1834,7 +1834,7 @@ int kwsysProcessCreate(kwsysProcess* cp, int index, /* The forwarding executable is given a handle to the error pipe and resume and kill events. */ - realCommand = malloc(strlen(cp->Win9x)+strlen(cp->Commands[index])+100); + realCommand = (char*)malloc(strlen(cp->Win9x)+strlen(cp->Commands[index])+100); if(!realCommand) { return 0; @@ -2672,7 +2672,7 @@ static int kwsysProcess_List__New_NT4(kwsysProcess_List* self) loaded in this program. This does not actually increment the reference count to the module so we do not need to close the handle. */ - HANDLE hNT = GetModuleHandle("ntdll.dll"); + HMODULE hNT = GetModuleHandle("ntdll.dll"); if(hNT) { /* Get pointers to the needed API functions. */ @@ -2776,7 +2776,7 @@ static int kwsysProcess_List__New_Snapshot(kwsysProcess_List* self) loaded in this program. This does not actually increment the reference count to the module so we do not need to close the handle. */ - HANDLE hKernel = GetModuleHandle("kernel32.dll"); + HMODULE hKernel = GetModuleHandle("kernel32.dll"); if(hKernel) { self->P_CreateToolhelp32Snapshot = diff --git a/Utilities/ITK/Utilities/kwsys/RegularExpression.hxx.in b/Utilities/ITK/Utilities/kwsys/RegularExpression.hxx.in index 2aa8a9aeedee67c17300770f3282867ecce3b752..48c00477f765e9a4ae4f22fe64b3cc25e2c3497d 100644 --- a/Utilities/ITK/Utilities/kwsys/RegularExpression.hxx.in +++ b/Utilities/ITK/Utilities/kwsys/RegularExpression.hxx.in @@ -42,6 +42,12 @@ # define kwsys_stl @KWSYS_NAMESPACE@_stl #endif +/* Disable useless Borland warnings. KWSys tries not to force things + on its includers, but there is no choice here. */ +#if defined(__BORLANDC__) +# pragma warn -8027 /* function not inlined. */ +#endif + namespace @KWSYS_NAMESPACE@ { diff --git a/Utilities/ITK/Utilities/kwsys/SharedForward.h.in b/Utilities/ITK/Utilities/kwsys/SharedForward.h.in index 3f864faa49f08b041753e753375087a39b9adf3a..fe85f78ccbd2e3ba1afb0cae11afd77e181becd9 100644 --- a/Utilities/ITK/Utilities/kwsys/SharedForward.h.in +++ b/Utilities/ITK/Utilities/kwsys/SharedForward.h.in @@ -147,6 +147,7 @@ /*--------------------------------------------------------------------------*/ /* Include needed system headers. */ +#include <stddef.h> /* size_t */ #include <limits.h> #include <stdlib.h> #include <string.h> @@ -219,7 +220,7 @@ static const char kwsys_shared_forward_path_slash[2] = {KWSYS_SHARED_FORWARD_PAT #endif /* SUN */ -#if defined(__sparc) +#if defined(__sparc) && !defined(__linux) # define KWSYS_SHARED_FORWARD_LDD "ldd" # define KWSYS_SHARED_FORWARD_LDD_N 1 # include <sys/isa_defs.h> @@ -482,13 +483,14 @@ static void kwsys_shared_forward_strerror(char* message) /*--------------------------------------------------------------------------*/ /* Functions to execute a child process. */ -static void kwsys_shared_forward_execvp(const char* cmd, char* const* argv) +static void kwsys_shared_forward_execvp(const char* cmd, + char const* const* argv) { #ifdef KWSYS_SHARED_FORWARD_ESCAPE_ARGV /* Count the number of arguments. */ int argc = 0; { - char* const* argvc; + char const* const* argvc; for(argvc = argv; *argvc; ++argvc,++argc) {} } @@ -505,7 +507,7 @@ static void kwsys_shared_forward_execvp(const char* cmd, char* const* argv) nargv[argc] = 0; /* Replace the command line to be used. */ - argv = nargv; + argv = (char const* const*)nargv; } #endif @@ -513,10 +515,9 @@ static void kwsys_shared_forward_execvp(const char* cmd, char* const* argv) #if defined(_MSC_VER) _execvp(cmd, argv); #elif defined(__MINGW32__) - /* Avoid incompatible pointer warning with a cast. */ - execvp(cmd, (char const* const*)argv); -#else execvp(cmd, argv); +#else + execvp(cmd, (char* const*)argv); #endif } @@ -550,7 +551,7 @@ static void kwsys_shared_forward_dirname(const char* begin, char* result) else if(last_slash_index == 2 && begin[1] == ':') { /* Only one leading drive letter and slash. */ - strncpy(result, begin, last_slash_index); + strncpy(result, begin, (size_t)last_slash_index); result[last_slash_index] = KWSYS_SHARED_FORWARD_PATH_SLASH; result[last_slash_index+1] = 0; } @@ -558,7 +559,7 @@ static void kwsys_shared_forward_dirname(const char* begin, char* result) else { /* A non-leading slash. */ - strncpy(result, begin, last_slash_index); + strncpy(result, begin, (size_t)last_slash_index); result[last_slash_index] = 0; } } @@ -630,7 +631,7 @@ static int kwsys_shared_forward_self_path(const char* argv0, char* result) if(first < last) { /* Determine the length without trailing slash. */ - int length = (int)(last-first); + size_t length = (size_t)(last-first); if(*(last-1) == '/' || *(last-1) == '\\') { --length; @@ -800,10 +801,10 @@ static int kwsys_shared_forward_get_settings(const char* self_path, /*--------------------------------------------------------------------------*/ /* Function to print why execution of a command line failed. */ -static void kwsys_shared_forward_print_failure(char** argv) +static void kwsys_shared_forward_print_failure(char const* const* argv) { char msg[KWSYS_SHARED_FORWARD_MAXPATH]; - char** arg = argv; + char const* const* arg = argv; kwsys_shared_forward_strerror(msg); fprintf(stderr, "Error running"); for(; *arg; ++arg) @@ -818,8 +819,9 @@ static char kwsys_shared_forward_ldpath[KWSYS_SHARED_FORWARD_MAXPATH*16] = KWSYS /*--------------------------------------------------------------------------*/ /* Main driver function to be called from main. */ -static int @KWSYS_NAMESPACE@_shared_forward_to_real(int argc, char** argv) +static int @KWSYS_NAMESPACE@_shared_forward_to_real(int argc, char** argv_in) { + char const** argv = (char const**)argv_in; /* Get the directory containing this executable. */ char self_path[KWSYS_SHARED_FORWARD_MAXPATH]; if(kwsys_shared_forward_self_path(argv[0], self_path)) @@ -877,7 +879,7 @@ static int @KWSYS_NAMESPACE@_shared_forward_to_real(int argc, char** argv) { # if defined(KWSYS_SHARED_FORWARD_LDD) /* Use the named ldd-like executable and arguments. */ - char* ldd_argv[] = {KWSYS_SHARED_FORWARD_LDD, 0, 0}; + char const* ldd_argv[] = {KWSYS_SHARED_FORWARD_LDD, 0, 0}; ldd_argv[KWSYS_SHARED_FORWARD_LDD_N] = exe; kwsys_shared_forward_execvp(ldd_argv[0], ldd_argv); diff --git a/Utilities/ITK/Utilities/kwsys/String.c b/Utilities/ITK/Utilities/kwsys/String.c index aa9b123e8ed0ea56bef8f22bcf08125ae88aa5a8..c0b2b9f83ce1673c2411a432c429a2d06bca24d4 100644 --- a/Utilities/ITK/Utilities/kwsys/String.c +++ b/Utilities/ITK/Utilities/kwsys/String.c @@ -11,6 +11,14 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ +#ifdef KWSYS_STRING_C +/* +All code in this source file is conditionally compiled to work-around +template definition auto-search on VMS. Other source files in this +directory that use the stl string cause the compiler to load this +source to try to get the definition of the string template. This +condition blocks the compiler from seeing the symbols defined here. +*/ #include "kwsysPrivate.h" #include KWSYS_HEADER(String.h) @@ -78,7 +86,7 @@ int kwsysString_strcasecmp(const char* lhs, const char* rhs) const char* const lower = kwsysString_strcasecmp_tolower; unsigned char const* us1 = (unsigned char const*)lhs; unsigned char const* us2 = (unsigned char const*)rhs; - int result = 0; + int result; while((result = lower[*us1] - lower[*us2++], result == 0) && *us1++) { } @@ -105,3 +113,5 @@ int kwsysString_strncasecmp(const char* lhs, const char* rhs, size_t n) return result; #endif } + +#endif /* KWSYS_STRING_C */ diff --git a/Utilities/ITK/Utilities/kwsys/System.c b/Utilities/ITK/Utilities/kwsys/System.c index 831f3f013c79390e198fd53e142219c38c09ab1c..9277d794b92f2357c0ccdc54d3988e5a67bc006f 100644 --- a/Utilities/ITK/Utilities/kwsys/System.c +++ b/Utilities/ITK/Utilities/kwsys/System.c @@ -20,11 +20,19 @@ # include "System.h.in" #endif +#include <stddef.h> /* ptrdiff_t */ +#include <stdlib.h> /* malloc, free */ #include <string.h> /* strlen */ #include <ctype.h> /* isalpha */ #include <stdio.h> +#if defined(KWSYS_C_HAS_PTRDIFF_T) && KWSYS_C_HAS_PTRDIFF_T +typedef ptrdiff_t kwsysSystem_ptrdiff_t; +#else +typedef int kwsysSystem_ptrdiff_t; +#endif + /* Notes: @@ -579,3 +587,272 @@ int kwsysSystem_Shell_GetArgumentSizeForUnix(const char* in, int flags) { return kwsysSystem_Shell__GetArgumentSize(in, 1, flags); } + +/*--------------------------------------------------------------------------*/ +static int kwsysSystem__AppendByte(char* local, + char** begin, char** end, + int* size, char c) +{ + /* Allocate space for the character. */ + if((*end - *begin) >= *size) + { + kwsysSystem_ptrdiff_t length = *end - *begin; + char* newBuffer = (char*)malloc((size_t)(*size*2)); + if(!newBuffer) + { + return 0; + } + memcpy(newBuffer, *begin, (size_t)(length)*sizeof(char)); + if(*begin != local) + { + free(*begin); + } + *begin = newBuffer; + *end = *begin + length; + *size *= 2; + } + + /* Store the character. */ + *(*end)++ = c; + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int kwsysSystem__AppendArgument(char** local, + char*** begin, char*** end, + int* size, + char* arg_local, + char** arg_begin, char** arg_end, + int* arg_size) +{ + /* Append a null-terminator to the argument string. */ + if(!kwsysSystem__AppendByte(arg_local, arg_begin, arg_end, arg_size, '\0')) + { + return 0; + } + + /* Allocate space for the argument pointer. */ + if((*end - *begin) >= *size) + { + kwsysSystem_ptrdiff_t length = *end - *begin; + char** newPointers = (char**)malloc((size_t)(*size)*2*sizeof(char*)); + if(!newPointers) + { + return 0; + } + memcpy(newPointers, *begin, (size_t)(length)*sizeof(char*)); + if(*begin != local) + { + free(*begin); + } + *begin = newPointers; + *end = *begin + length; + *size *= 2; + } + + /* Allocate space for the argument string. */ + **end = (char*)malloc((size_t)(*arg_end - *arg_begin)); + if(!**end) + { + return 0; + } + + /* Store the argument in the command array. */ + memcpy(**end, *arg_begin,(size_t)(*arg_end - *arg_begin)); + ++(*end); + + /* Reset the argument to be empty. */ + *arg_end = *arg_begin; + + return 1; +} + +/*--------------------------------------------------------------------------*/ +#define KWSYSPE_LOCAL_BYTE_COUNT 1024 +#define KWSYSPE_LOCAL_ARGS_COUNT 32 +static char** kwsysSystem__ParseUnixCommand(const char* command, int flags) +{ + /* Create a buffer for argument pointers during parsing. */ + char* local_pointers[KWSYSPE_LOCAL_ARGS_COUNT]; + int pointers_size = KWSYSPE_LOCAL_ARGS_COUNT; + char** pointer_begin = local_pointers; + char** pointer_end = pointer_begin; + + /* Create a buffer for argument strings during parsing. */ + char local_buffer[KWSYSPE_LOCAL_BYTE_COUNT]; + int buffer_size = KWSYSPE_LOCAL_BYTE_COUNT; + char* buffer_begin = local_buffer; + char* buffer_end = buffer_begin; + + /* Parse the command string. Try to behave like a UNIX shell. */ + char** newCommand = 0; + const char* c = command; + int in_argument = 0; + int in_escape = 0; + int in_single = 0; + int in_double = 0; + int failed = 0; + for(;*c; ++c) + { + if(in_escape) + { + /* This character is escaped so do no special handling. */ + if(!in_argument) + { + in_argument = 1; + } + if(!kwsysSystem__AppendByte(local_buffer, &buffer_begin, + &buffer_end, &buffer_size, *c)) + { + failed = 1; + break; + } + in_escape = 0; + } + else if(*c == '\\') + { + /* The next character should be escaped. */ + in_escape = 1; + } + else if(*c == '\'' && !in_double) + { + /* Enter or exit single-quote state. */ + if(in_single) + { + in_single = 0; + } + else + { + in_single = 1; + if(!in_argument) + { + in_argument = 1; + } + } + } + else if(*c == '"' && !in_single) + { + /* Enter or exit double-quote state. */ + if(in_double) + { + in_double = 0; + } + else + { + in_double = 1; + if(!in_argument) + { + in_argument = 1; + } + } + } + else if(isspace((unsigned char) *c)) + { + if(in_argument) + { + if(in_single || in_double) + { + /* This space belongs to a quoted argument. */ + if(!kwsysSystem__AppendByte(local_buffer, &buffer_begin, + &buffer_end, &buffer_size, *c)) + { + failed = 1; + break; + } + } + else + { + /* This argument has been terminated by whitespace. */ + if(!kwsysSystem__AppendArgument(local_pointers, &pointer_begin, + &pointer_end, &pointers_size, + local_buffer, &buffer_begin, + &buffer_end, &buffer_size)) + { + failed = 1; + break; + } + in_argument = 0; + } + } + } + else + { + /* This character belong to an argument. */ + if(!in_argument) + { + in_argument = 1; + } + if(!kwsysSystem__AppendByte(local_buffer, &buffer_begin, + &buffer_end, &buffer_size, *c)) + { + failed = 1; + break; + } + } + } + + /* Finish the last argument. */ + if(in_argument) + { + if(!kwsysSystem__AppendArgument(local_pointers, &pointer_begin, + &pointer_end, &pointers_size, + local_buffer, &buffer_begin, + &buffer_end, &buffer_size)) + { + failed = 1; + } + } + + /* If we still have memory allocate space for the new command + buffer. */ + if(!failed) + { + kwsysSystem_ptrdiff_t n = pointer_end - pointer_begin; + newCommand = (char**)malloc((size_t)(n+1)*sizeof(char*)); + } + + if(newCommand) + { + /* Copy the arguments into the new command buffer. */ + kwsysSystem_ptrdiff_t n = pointer_end - pointer_begin; + memcpy(newCommand, pointer_begin, sizeof(char*)*(size_t)(n)); + newCommand[n] = 0; + } + else + { + /* Free arguments already allocated. */ + while(pointer_end != pointer_begin) + { + free(*(--pointer_end)); + } + } + + /* Free temporary buffers. */ + if(pointer_begin != local_pointers) + { + free(pointer_begin); + } + if(buffer_begin != local_buffer) + { + free(buffer_begin); + } + + /* The flags argument is currently unused. */ + (void)flags; + + /* Return the final command buffer. */ + return newCommand; +} + +/*--------------------------------------------------------------------------*/ +char** kwsysSystem_Parse_CommandForUnix(const char* command, int flags) +{ + /* Validate the flags. */ + if(flags != 0) + { + return 0; + } + + /* Forward to our internal implementation. */ + return kwsysSystem__ParseUnixCommand(command, flags); +} diff --git a/Utilities/ITK/Utilities/kwsys/System.h.in b/Utilities/ITK/Utilities/kwsys/System.h.in index d890a3c923a7b57c9d4e9d78c6a06c94dbba2aaf..32111797aae4a084d3e432ec846a3fce8bc98ab4 100644 --- a/Utilities/ITK/Utilities/kwsys/System.h.in +++ b/Utilities/ITK/Utilities/kwsys/System.h.in @@ -25,6 +25,7 @@ # define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT #endif #if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS +# define kwsysSystem_Parse_CommandForUnix kwsys_ns(System_Parse_CommandForUnix) # define kwsysSystem_Shell_GetArgumentForWindows kwsys_ns(System_Shell_GetArgumentForWindows) # define kwsysSystem_Shell_GetArgumentForUnix kwsys_ns(System_Shell_GetArgumentForUnix) # define kwsysSystem_Shell_GetArgumentSizeForWindows kwsys_ns(System_Shell_GetArgumentSizeForWindows) @@ -113,6 +114,27 @@ enum kwsysSystem_Shell_Flag_e kwsysSystem_Shell_Flag_AllowMakeVariables = (1<<5) }; +/** + * Parse a unix-style command line string into separate arguments. + * + * On success, returns a pointer to an array of pointers to individual + * argument strings. Each string is null-terminated and the last + * entry in the array is a NULL pointer (just like argv). It is the + * caller's responsibility to free() the strings and the array of + * pointers to them. + * + * On failure, returns NULL. Failure occurs only on invalid flags or + * when memory cannot be allocated; never due to content of the input + * string. Missing close-quotes are treated as if the necessary + * closing quote appears. + * + * By default single- and double-quoted arguments are supported, and + * any character may be escaped by a backslash. The flags argument is + * reserved for future use, and must be zero (or the call will fail). + */ +kwsysEXPORT char** kwsysSystem_Parse_CommandForUnix(const char* command, + int flags); + #if defined(__cplusplus) } /* extern "C" */ #endif @@ -123,6 +145,7 @@ enum kwsysSystem_Shell_Flag_e # undef kwsys_ns # undef kwsysEXPORT # if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS +# undef kwsysSystem_Parse_CommandForUnix # undef kwsysSystem_Shell_GetArgumentForWindows # undef kwsysSystem_Shell_GetArgumentForUnix # undef kwsysSystem_Shell_GetArgumentSizeForWindows diff --git a/Utilities/ITK/Utilities/kwsys/SystemTools.cxx b/Utilities/ITK/Utilities/kwsys/SystemTools.cxx index 0135df63af5a24699e11d3a5257809ae97fd0376..848446abe9ddaf6e45c991122ef2388ee357feb4 100644 --- a/Utilities/ITK/Utilities/kwsys/SystemTools.cxx +++ b/Utilities/ITK/Utilities/kwsys/SystemTools.cxx @@ -402,9 +402,36 @@ bool SystemTools::GetEnv(const char* key, kwsys_stl::string& result) } } +class kwsysDeletingCharVector : public kwsys_stl::vector<char*> +{ +public: + ~kwsysDeletingCharVector(); +}; + +kwsysDeletingCharVector::~kwsysDeletingCharVector() +{ + for(kwsys_stl::vector<char*>::iterator i = this->begin(); + i != this->end(); ++i) + { + delete []*i; + } +} +bool SystemTools::PutEnv(const char* value) +{ + static kwsysDeletingCharVector localEnvironment; + char* envVar = new char[strlen(value)+1]; + strcpy(envVar, value); + int ret = putenv(envVar); + // save the pointer in the static vector so that it can + // be deleted on exit + localEnvironment.push_back(envVar); + return ret == 0; +} + + const char* SystemTools::GetExecutableExtension() { -#if defined(_WIN32) || defined(__CYGWIN__) +#if defined(_WIN32) || defined(__CYGWIN__) || defined(__VMS) return ".exe"; #else return ""; @@ -1456,12 +1483,38 @@ kwsys_stl::string SystemTools::EscapeChars( return n; } +#ifdef __VMS +static void ConvertVMSToUnix(kwsys_stl::string& path) +{ + kwsys_stl::string::size_type rootEnd = path.find(":["); + kwsys_stl::string::size_type pathEnd = path.find("]"); + if(rootEnd != path.npos) + { + kwsys_stl::string root = path.substr(0, rootEnd); + kwsys_stl::string pathPart = path.substr(rootEnd+2, pathEnd - rootEnd-2); + const char* pathCString = pathPart.c_str(); + const char* pos0 = pathCString; + for (kwsys_stl::string::size_type pos = 0; *pos0; ++ pos ) + { + if ( *pos0 == '.' ) + { + pathPart[pos] = '/'; + } + pos0 ++; + } + path = "/"+ root + "/" + pathPart; + } +} +#endif + // convert windows slashes to unix slashes void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path) { const char* pathCString = path.c_str(); bool hasDoubleSlash = false; - +#ifdef __VMS + ConvertVMSToUnix(path); +#else const char* pos0 = pathCString; const char* pos1 = pathCString+1; for (kwsys_stl::string::size_type pos = 0; *pos0; ++ pos ) @@ -1495,7 +1548,7 @@ void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path) { SystemTools::ReplaceString(path, "//", "/"); } - +#endif // remove any trailing slash if(!path.empty()) { @@ -3272,18 +3325,18 @@ SystemTools // The first two components do not add a slash. if(first != last) { - result += *first++; + result.append(*first++); } if(first != last) { - result += *first++; + result.append(*first++); } // All remaining components are always separated with a slash. while(first != last) { - result += "/"; - result += *first++; + result.append("/"); + result.append((*first++)); } // Return the concatenated result. @@ -3910,7 +3963,6 @@ bool SystemTools::GetLineFromStream(kwsys_ios::istream& is, // Append the data read to the line. line.append(buffer); - sizeLimit = sizeLimit - static_cast<long>(length); } // Return the results. @@ -4507,8 +4559,25 @@ SystemToolsManager::~SystemToolsManager() } } +#if defined(__VMS) +// On VMS we configure the run time C library to be more UNIX like. +// http://h71000.www7.hp.com/doc/732final/5763/5763pro_004.html +extern "C" int decc$feature_get_index(char *name); +extern "C" int decc$feature_set_value(int index, int mode, int value); +static int SetVMSFeature(char* name, int value) +{ + int i; + errno = 0; + i = decc$feature_get_index(name); + return i >= 0 && (decc$feature_set_value(i, 1, value) >= 0 || errno == 0); +} +#endif + void SystemTools::ClassInitialize() { +#ifdef __VMS + SetVMSFeature("DECC$FILENAME_UNIX_ONLY", 1); +#endif // Allocate the translation map first. SystemTools::TranslationMap = new SystemToolsTranslationMap; SystemTools::LongPathMap = new SystemToolsTranslationMap; diff --git a/Utilities/ITK/Utilities/kwsys/SystemTools.hxx.in b/Utilities/ITK/Utilities/kwsys/SystemTools.hxx.in index 6527c21fb6fec0a72c7f5a0bf74c1a01e2a5e4cb..d5fc6fe0a5399f93245978f92ece08ebe506874a 100644 --- a/Utilities/ITK/Utilities/kwsys/SystemTools.hxx.in +++ b/Utilities/ITK/Utilities/kwsys/SystemTools.hxx.in @@ -754,6 +754,10 @@ public: static const char* GetEnv(const char* key); static bool GetEnv(const char* key, kwsys_stl::string& result); + /** Put a string into the environment + of the form var=value */ + static bool PutEnv(const char* value); + /** * Get current working directory CWD */ diff --git a/Utilities/ITK/Utilities/kwsys/hashtable.hxx.in b/Utilities/ITK/Utilities/kwsys/hashtable.hxx.in index 42b85dfbc903a806df4d4d19b75ab1d03eba2d76..12e76d26761572544864cc9f0e0cff3bfd41768c 100644 --- a/Utilities/ITK/Utilities/kwsys/hashtable.hxx.in +++ b/Utilities/ITK/Utilities/kwsys/hashtable.hxx.in @@ -36,6 +36,10 @@ * purpose. It is provided "as is" without express or implied warranty. * */ +#ifdef __BORLANDC__ +# pragma warn -8027 /* 'for' not inlined. */ +# pragma warn -8026 /* 'exception' not inlined. */ +#endif #ifndef @KWSYS_NAMESPACE@_hashtable_hxx #define @KWSYS_NAMESPACE@_hashtable_hxx @@ -212,9 +216,9 @@ inline PIn hash_allocate_type(PIn (*)(TSize), // Define the comparison operators in terms of a base type to avoid // needing templated versions. class hash_allocator_base {}; -bool operator==(const hash_allocator_base&, +inline bool operator==(const hash_allocator_base&, const hash_allocator_base&) throw() { return true; } -bool operator!=(const hash_allocator_base&, +inline bool operator!=(const hash_allocator_base&, const hash_allocator_base&) throw() { return false; } // Define the allocator template. diff --git a/Utilities/ITK/Utilities/kwsys/kwsysDateStamp.cmake b/Utilities/ITK/Utilities/kwsys/kwsysDateStamp.cmake index 3d491de89fcfedf71235ecd3de7ff9aad428eef5..8e64e4a5b71c0a5297212c5e5d233a14a8903a56 100644 --- a/Utilities/ITK/Utilities/kwsys/kwsysDateStamp.cmake +++ b/Utilities/ITK/Utilities/kwsys/kwsysDateStamp.cmake @@ -4,7 +4,7 @@ SET(KWSYS_DATE_STAMP_YEAR 2009) # KWSys version date month component. Format is MM. -SET(KWSYS_DATE_STAMP_MONTH 05) +SET(KWSYS_DATE_STAMP_MONTH 09) # KWSys version date day component. Format is DD. -SET(KWSYS_DATE_STAMP_DAY 27) +SET(KWSYS_DATE_STAMP_DAY 14) diff --git a/Utilities/ITK/Utilities/kwsys/kwsysPlatformTestsCXX.cxx b/Utilities/ITK/Utilities/kwsys/kwsysPlatformTestsCXX.cxx index f0a2dfccbcfe84f6d5a9f8a44fbe3578980cc78a..502e2d88b170b36f2acd40e5f09a01e03888036f 100644 --- a/Utilities/ITK/Utilities/kwsys/kwsysPlatformTestsCXX.cxx +++ b/Utilities/ITK/Utilities/kwsys/kwsysPlatformTestsCXX.cxx @@ -91,6 +91,11 @@ bool f(const kwsys_stl::string& s) { return s != ""; } int main() { return 0; } #endif +#ifdef TEST_KWSYS_CXX_HAS_CSTDIO +#include <cstdio> +int main() { return 0; } +#endif + #ifdef TEST_KWSYS_CXX_HAS_CSTDDEF #include <cstddef> void f(size_t) {} @@ -289,6 +294,17 @@ int main() } #endif +#ifdef TEST_KWSYS_IOS_HAVE_BINARY +int test_binary(int, ...) +{ + return 0; +} +int main() +{ + return test_binary(1, kwsys_ios::ios::binary); +} +#endif + #ifdef TEST_KWSYS_IOS_HAS_ISTREAM_LONG_LONG int test_istream(kwsys_ios::istream& is, long long& x) { @@ -331,6 +347,9 @@ int main() #include <sys/types.h> #include <sys/stat.h> #include <assert.h> +#if KWSYS_CXX_HAS_CSTDIO +# include <cstdio> +#endif #include <stdio.h> int main(int, char **argv) diff --git a/Utilities/ITK/Utilities/kwsys/kwsysPrivate.h b/Utilities/ITK/Utilities/kwsys/kwsysPrivate.h index d6b2d47e78a4e201a9d6c8df7996a6f32d9fdd4a..a40a7210d72244510b6d68aa95afe40d04bf5e84 100644 --- a/Utilities/ITK/Utilities/kwsys/kwsysPrivate.h +++ b/Utilities/ITK/Utilities/kwsys/kwsysPrivate.h @@ -39,7 +39,5 @@ #define KWSYS_NAMESPACE_STRING1(x) #x #else -# ifndef __VMS /* Avoid strange false positive on VMS compiler. */ -# error "kwsysPrivate.h included multiple times." -# endif +# error "kwsysPrivate.h included multiple times." #endif diff --git a/Utilities/ITK/Utilities/kwsys/testAutoPtr.cxx b/Utilities/ITK/Utilities/kwsys/testAutoPtr.cxx index 5b2ed2854fb9bad3bc4cede069492e76baf062f7..8351272a3e239eadff28edb6f073bc137cc7bfb9 100644 --- a/Utilities/ITK/Utilities/kwsys/testAutoPtr.cxx +++ b/Utilities/ITK/Utilities/kwsys/testAutoPtr.cxx @@ -11,9 +11,12 @@ PURPOSE. See the above copyright notices for more information. =========================================================================*/ +#ifdef __BORLANDC__ +# pragma warn -8027 /* 'for' not inlined. */ +# pragma warn -8026 /* exception not inlined. */ +#endif #include "kwsysPrivate.h" #include KWSYS_HEADER(auto_ptr.hxx) - // Work-around CMake dependency scanning limitation. This must // duplicate the above list of headers. #if 0 diff --git a/Utilities/ITK/Utilities/kwsys/testIOS.cxx b/Utilities/ITK/Utilities/kwsys/testIOS.cxx index 5b65d20b5a326cd80022dba415a9fefb9137c2d3..2839109278ff1f7b90e2eea6eeb376308c4e9388 100644 --- a/Utilities/ITK/Utilities/kwsys/testIOS.cxx +++ b/Utilities/ITK/Utilities/kwsys/testIOS.cxx @@ -1,6 +1,7 @@ #include "kwsysPrivate.h" #include KWSYS_HEADER(stl/vector) #include KWSYS_HEADER(ios/sstream) +#include KWSYS_HEADER(ios/fstream) #include KWSYS_HEADER(ios/iostream) // Work-around CMake dependency scanning limitation. This must @@ -9,6 +10,7 @@ # include "kwsys_stl_string.hxx.in" # include "kwsys_stl_vector.h.in" # include "kwsys_ios_sstream.h.in" +# include "kwsys_ios_fstream.h.in" # include "kwsys_ios_iostream.h.in" #endif @@ -142,6 +144,13 @@ int testIOS(int, char*[]) return 1; } + // Just try to compile this. + if(x == 12345) + { + kwsys_ios::ifstream fin("/does_not_exist", + kwsys_ios::ios::in | kwsys_ios_binary); + } + kwsys_ios::cout << "IOS tests passed" << kwsys_ios::endl; return 0; } diff --git a/Utilities/ITK/Utilities/netlib/slatec/CMakeLists.txt b/Utilities/ITK/Utilities/netlib/slatec/CMakeLists.txt index 16b62d7d0de26f05336843fefe6508e7031eb605..4961219c6ac0992d423f87a6707a8bbd1b823ea3 100644 --- a/Utilities/ITK/Utilities/netlib/slatec/CMakeLists.txt +++ b/Utilities/ITK/Utilities/netlib/slatec/CMakeLists.txt @@ -23,11 +23,15 @@ ADD_LIBRARY( itkNetlibSlatec ) IF(ITK_USE_SYSTEM_VXL) - TARGET_LINK_LIBRARIES( itkNetlibSlatec netlib ) + TARGET_LINK_LIBRARIES( itkNetlibSlatec v3p_netlib netlib) ELSE(ITK_USE_SYSTEM_VXL) TARGET_LINK_LIBRARIES( itkNetlibSlatec itkv3p_netlib ) ENDIF(ITK_USE_SYSTEM_VXL) +IF(ITK_LIBRARY_PROPERTIES) + SET_TARGET_PROPERTIES(itkNetlibSlatec PROPERTIES ${ITK_LIBRARY_PROPERTIES}) +ENDIF(ITK_LIBRARY_PROPERTIES) + IF(NOT ITK_INSTALL_NO_LIBRARIES) INSTALL(TARGETS itkNetlibSlatec RUNTIME DESTINATION ${ITK_INSTALL_BIN_DIR_CM24} COMPONENT RuntimeLibraries diff --git a/Utilities/ITK/Utilities/nifti/CMakeLists.txt b/Utilities/ITK/Utilities/nifti/CMakeLists.txt index ac5f0e317f5573e16e379d5eab1fcafc8c1cc777..3915e3679afe81cfb711d86d8780e18b3f86136b 100644 --- a/Utilities/ITK/Utilities/nifti/CMakeLists.txt +++ b/Utilities/ITK/Utilities/nifti/CMakeLists.txt @@ -1,6 +1,11 @@ #File Generated by Hans J. Johnson #Please contact hans-johnson@uiowa.edu for making enhancments/corrections PROJECT(NIFTI) +cmake_minimum_required(VERSION 2.6) +if(COMMAND cmake_policy) + cmake_policy(SET CMP0003 NEW) +endif(COMMAND cmake_policy) + # Configure Dart testing support. INCLUDE(${CMAKE_ROOT}/Modules/Dart.cmake) diff --git a/Utilities/ITK/Utilities/nifti/Testing/CMakeLists.txt b/Utilities/ITK/Utilities/nifti/Testing/CMakeLists.txt index ec439b8f74f0127869ca823ef3554d96cdcfd86e..c8774265dc7b33251b642c73eaf197e34e488a38 100644 --- a/Utilities/ITK/Utilities/nifti/Testing/CMakeLists.txt +++ b/Utilities/ITK/Utilities/nifti/Testing/CMakeLists.txt @@ -1,7 +1,8 @@ +PROJECT(NIFTI_TESTS) #File Generated by Hans J. Johnson #Please contact hans-johnson@uiowa.edu for making enhancments/corrections -PROJECT(TESTING) +INCLUDE_DIRECTORIES(${NIFTI_SOURCE_DIR}/niftilib ${NIFTI_SOURCE_DIR}/znzlib ${NIFTI_SOURCE_DIR}/nifticdf) SUBDIRS(niftilib) SUBDIRS(nifti_regress_test) diff --git a/Utilities/ITK/Utilities/nifti/Testing/nifti_regress_test/CMakeLists.txt b/Utilities/ITK/Utilities/nifti/Testing/nifti_regress_test/CMakeLists.txt index 4530b3e7c39dc5caa4e28641706b095b0e10f680..6c2823501249b9d197da3b6e3d1a6bd40c218bda 100644 --- a/Utilities/ITK/Utilities/nifti/Testing/nifti_regress_test/CMakeLists.txt +++ b/Utilities/ITK/Utilities/nifti/Testing/nifti_regress_test/CMakeLists.txt @@ -1,12 +1,11 @@ # Do all regression tests -PROJECT(REGRESSION_TEST) SET(NT ${NIFTI_BINARY_DIR}/utils/nifti_tool ) -SET(DATA ${REGRESSION_TEST_BINARY_DIR}/nifti_regress_data) -SET(TESTS ${REGRESSION_TEST_SOURCE_DIR}/cmake_testscripts) +SET(DATA ${NIFTI_TESTS_BINARY_DIR}/nifti_regress_test/nifti_regress_data) +SET(TESTS ${NIFTI_TESTS_SOURCE_DIR}/nifti_regress_test/cmake_testscripts) ADD_TEST(fetch_data -sh ${TESTS}/fetch_data_test.sh ${REGRESSION_TEST_BINARY_DIR} +sh ${TESTS}/fetch_data_test.sh ${NIFTI_TESTS_BINARY_DIR}/nifti_regress_test ) ADD_TEST(nifti_ver ${NT} -nifti_ver) diff --git a/Utilities/ITK/Utilities/nifti/Testing/niftilib/CMakeLists.txt b/Utilities/ITK/Utilities/nifti/Testing/niftilib/CMakeLists.txt index 6fe87bd48e782436186194b1ab95d9b269fab607..1492f904e99fe4d03fa6783e419b6efc7f446124 100644 --- a/Utilities/ITK/Utilities/nifti/Testing/niftilib/CMakeLists.txt +++ b/Utilities/ITK/Utilities/nifti/Testing/niftilib/CMakeLists.txt @@ -1,8 +1,8 @@ #File Generated by Hans J. Johnson #Please contact hans-johnson@uiowa.edu for making enhancments/corrections -PROJECT(NIFTILIB_TESTS) -INCLUDE_DIRECTORIES(${NIFTILIB_SOURCE_DIR} ${ZNZLIB_SOURCE_DIR} ${NIFTILIB_SOURCE_DIR}/../utils) +INCLUDE_DIRECTORIES(${NIFTI_SOURCE_DIR}/niftilib ${NIFTI_SOURCE_DIR}/znzlib + ${NIFTI_SOURCE_DIR}/nifticdf ${NIFTI_SOURCE_DIR}/utils) ADD_EXECUTABLE(first_test nifti_test.c) TARGET_LINK_LIBRARIES(first_test niftiio ) diff --git a/Utilities/ITK/Utilities/nifti/Updates.txt b/Utilities/ITK/Utilities/nifti/Updates.txt index 27df33edd3b2812713fa080f99718c3f42d430a6..0fb7859b5f3d391e5e83294b01eedee114c613ce 100644 --- a/Utilities/ITK/Utilities/nifti/Updates.txt +++ b/Utilities/ITK/Utilities/nifti/Updates.txt @@ -89,4 +89,10 @@ Updated in version 1.1.0 August 28, 2008 Recent Updates - RR added nifti_NBL_matches_nim() check for write_bricks() + - HJ added casts to suppress compiler warnings + - RR added NIFTI_ECODE_PYPICKLE + - RR added NIFTI_ECODEs 18-28 for the LONI MiND group + - RR added examples/clib_01_read_write.c as a simple library example + - RR allow uppercase extension + - RR added 4 checks of alloc() returns diff --git a/Utilities/ITK/Utilities/nifti/examples/CMakeLists.txt b/Utilities/ITK/Utilities/nifti/examples/CMakeLists.txt index 5b784697a7da1ab452a8db11b4ac8e7779dd7eaf..91d2643facded7c616fe8b85dc8edd2ddbb1dede 100644 --- a/Utilities/ITK/Utilities/nifti/examples/CMakeLists.txt +++ b/Utilities/ITK/Utilities/nifti/examples/CMakeLists.txt @@ -1,8 +1,7 @@ #File Generated by Hans J. Johnson #Please contact hans-johnson@uiowa.edu for making enhancments/corrections -PROJECT(FSLEXAMPLES) -INCLUDE_DIRECTORIES(${NIFTILIB_SOURCE_DIR} ${ZNZLIB_SOURCE_DIR} ${FSLIOLIB_SOURCE_DIR} ) +INCLUDE_DIRECTORIES(${NIFTI_SOURCE_DIR}/niftilib ${NIFTI_SOURCE_DIR}/znzlib ${NIFTI_SOURCE_DIR}/nifticdf) ADD_EXECUTABLE( ${PACKAGE_PREFIX}fsl_api_driver fsl_api_driver.c ) TARGET_LINK_LIBRARIES( fsl_api_driver ${PACKAGE_PREFIX}fslio) diff --git a/Utilities/ITK/Utilities/nifti/examples/Makefile b/Utilities/ITK/Utilities/nifti/examples/Makefile index a41c80f21ce3dd92bb1044beedd4979fcd656734..c5bcb0a419c8864eec63044aed55846746036d44 100644 --- a/Utilities/ITK/Utilities/nifti/examples/Makefile +++ b/Utilities/ITK/Utilities/nifti/examples/Makefile @@ -35,11 +35,14 @@ endif all: fsl_api_driver clean: - rm -f fsl_api_driver + rm -f fsl_api_driver clib_01_read_write fsl_api_driver: fsl_api_driver.c ../lib/libfslio.a $(CC) $(CFLAGS) -o fsl_api_driver fsl_api_driver.c $(FSLIO_INCS) $(NIFTI_INCS) $(ZNZ_INCS) $(FSLIO_LIBS) $(NIFTI_LIBS) $(ZNZ_LIBS) +clib_01_read_write: clib_01_read_write.c + $(CC) $(CFLAGS) -o clib_01_read_write clib_01_read_write.c $(NIFTI_INCS) $(ZNZ_INCS) $(NIFTI_LIBS) $(ZNZ_LIBS) + help: @echo "all: make the fsl_api_driver program" @echo "clean: rm the fsl_api_driver program" diff --git a/Utilities/ITK/Utilities/nifti/fsliolib/CMakeLists.txt b/Utilities/ITK/Utilities/nifti/fsliolib/CMakeLists.txt index fa242624f6d427e35a1284b898c7b0da171ff3d3..632b2d9b4c5657688cb6bb9bbf44d005ee8d86d3 100644 --- a/Utilities/ITK/Utilities/nifti/fsliolib/CMakeLists.txt +++ b/Utilities/ITK/Utilities/nifti/fsliolib/CMakeLists.txt @@ -1,8 +1,7 @@ #File Generated by Hans J. Johnson #Please contact hans-johnson@uiowa.edu for making enhancments/corrections -PROJECT(FSLIOLIB) -INCLUDE_DIRECTORIES(${NIFTILIB_SOURCE_DIR} ${ZNZLIB_SOURCE_DIR}) +INCLUDE_DIRECTORIES(${NIFTILIB_SOURCE_DIR} ${ZNZLIB_SOURCE_DIR} ) SET(FSLIOLIB_SRC fslio.c) # Michael Hanke 2004-04-25: diff --git a/Utilities/ITK/Utilities/nifti/nifticdf/CMakeLists.txt b/Utilities/ITK/Utilities/nifti/nifticdf/CMakeLists.txt index 35644e30d65aa91e236d083f55073d60f3bcded6..f570536fa757f24ec42e40e60df293194a40b67f 100644 --- a/Utilities/ITK/Utilities/nifti/nifticdf/CMakeLists.txt +++ b/Utilities/ITK/Utilities/nifti/nifticdf/CMakeLists.txt @@ -1,6 +1,5 @@ -PROJECT(NIFTICDFLIB) -INCLUDE_DIRECTORIES(${NIFTILIB_SOURCE_DIR}) +INCLUDE_DIRECTORIES(${NIFTI_SOURCE_DIR}/niftilib) #INCLUDE_DIRECTORIES(/usr/include/nifti) SET(NIFTICDFLIB_SRC nifticdf.c) diff --git a/Utilities/ITK/Utilities/nifti/niftilib/CMakeLists.txt b/Utilities/ITK/Utilities/nifti/niftilib/CMakeLists.txt index 3ba36152dd90d4e409001ed2ca20b7e645c7348e..379d8b34de3bdfe2d0a4f68a1a70d3c14b4235ee 100644 --- a/Utilities/ITK/Utilities/nifti/niftilib/CMakeLists.txt +++ b/Utilities/ITK/Utilities/nifti/niftilib/CMakeLists.txt @@ -1,8 +1,7 @@ #File Generated by Hans J. Johnson #Please contact hans-johnson@uiowa.edu for making enhancments/corrections -PROJECT(NIFTILIB) -INCLUDE_DIRECTORIES(${ZNZLIB_SOURCE_DIR}) +INCLUDE_DIRECTORIES(${NIFTI_SOURCE_DIR}/znzlib) SET(NIFTILIB_SRC nifti1_io.c) SET(NIFTI_NIFTILIB_NAME ${PACKAGE_PREFIX}niftiio) diff --git a/Utilities/ITK/Utilities/nifti/niftilib/nifti1_io.c b/Utilities/ITK/Utilities/nifti/niftilib/nifti1_io.c index 26a6f1d47f563e4fa8d785b084f15cacb6be8604..ec16fc3f83c209cc55a038139c62db5e535a71ee 100644 --- a/Utilities/ITK/Utilities/nifti/niftilib/nifti1_io.c +++ b/Utilities/ITK/Utilities/nifti/niftilib/nifti1_io.c @@ -28,7 +28,7 @@ */ /*! global history and version strings, for printing */ -static char * gni_history[] = +static char const * const gni_history[] = { "----------------------------------------------------------------------\n" "history (of nifti library changes):\n" @@ -321,15 +321,27 @@ static char * gni_history[] = " - also swap UNUSED fields in nifti_1_header struct\n", "1.36 07 Oct 2008 [rickr]\n", " - added nifti_NBL_matches_nim() check for write_bricks()\n" + "1.37 10 Mar 2009 [rickr]\n", + " - H Johnson cast updates (06 Feb)\n" + " - added NIFTI_ECODE_PYPICKLE for PyNIfTI (06 Feb)\n" + " - added NIFTI_ECODEs 18-28 for the LONI MiND group\n" + "1.38 28 Apr 2009 [rickr]\n", + " - uppercase extensions are now valid (requested by M. Coursolle)\n" + " - nifti_set_allow_upper_fext controls this option (req by C. Ooi)\n" + "1.39 23 Jun 2009 [rickr]: added 4 checks of alloc() returns\n", "----------------------------------------------------------------------\n" }; -static char gni_version[] = "nifti library version 1.36 (7 Oct, 2008)"; +static const char gni_version[] = "nifti library version 1.39 (23 June, 2009)"; -/*! global nifti options structure */ -static nifti_global_options g_opts = { 1, 0 }; +/*! global nifti options structure - init with defaults */ +static nifti_global_options g_opts = { + 1, /* debug level */ + 0, /* skip_blank_ext - skip extender if no extensions */ + 1 /* allow_upper_fext - allow uppercase file extensions */ +}; /*! global nifti types structure list (per type, ordered oldest to newest) */ -static nifti_type_ele nifti_type_list[] = { +static const nifti_type_ele nifti_type_list[] = { /* type nbyper swapsize name */ { 0, 0, 0, "DT_UNKNOWN" }, { 0, 0, 0, "DT_NONE" }, @@ -406,6 +418,14 @@ static int make_pivot_list(nifti_image * nim, const int dims[], int pivots[], int prods[], int * nprods ); /* misc */ +static int compare_strlist (const char * str, char ** strlist, int len); +static int fileext_compare (const char * test_ext, const char * known_ext); +static int fileext_n_compare (const char * test_ext, + const char * known_ext, size_t maxlen); +static int is_mixedcase (const char * str); +static int is_uppercase (const char * str); +static int make_lowercase (char * str); +static int make_uppercase (char * str); static int need_nhdr_swap (short dim0, int hdrsize); static int print_hex_vals (const char * data, int nbytes, FILE * fp); static int unescape_string (char *str); /* string utility functions */ @@ -834,6 +854,9 @@ static int nifti_load_NBL_bricks( nifti_image * nim , int * slist, int * sindex, if( rv != NBL->bsize ){ fprintf(stderr,"** failed to read brick %d from file '%s'\n", isrc, nim->iname ? nim->iname : nim->fname); + if( g_opts.debug > 1 ) + fprintf(stderr," read %u of %u bytes)\n", + (unsigned int)rv, (unsigned int)NBL->bsize); return -1; } fposn += NBL->bsize; @@ -1126,8 +1149,17 @@ int nifti_disp_matrix_orient( const char * mesg, mat44 mat ) *//*--------------------------------------------------------------------*/ char *nifti_strdup(const char *str) { - char *dup= (char *)malloc( strlen(str)+1 ); - if (dup) strcpy(dup,str); + char *dup; + + if( !str ) return NULL; /* allow calls passing NULL */ + + dup = (char *)malloc(strlen(str) + 1); + + /* check for failure */ + if( dup ) strcpy(dup, str); + else fprintf(stderr,"** nifti_strdup: failed to alloc %u bytes\n", + (unsigned int)strlen(str)+1); + return dup; } @@ -1144,7 +1176,7 @@ char *nifti_strdup(const char *str) \sa NIFTI1_DATATYPES group in nifti1.h *//*-------------------------------------------------------------------------*/ -char *nifti_datatype_string( int dt ) +char const * nifti_datatype_string( int dt ) { switch( dt ){ case DT_UNKNOWN: return "UNKNOWN" ; @@ -1213,7 +1245,7 @@ int nifti_is_inttype( int dt ) \sa NIFTI1_UNITS group in nifti1.h *//*-------------------------------------------------------------------------*/ -char *nifti_units_string( int uu ) +char const *nifti_units_string( int uu ) { switch( uu ){ case NIFTI_UNITS_METER: return "m" ; @@ -1241,7 +1273,7 @@ char *nifti_units_string( int uu ) \sa NIFTI1_XFORM_CODES group in nifti1.h *//*-------------------------------------------------------------------------*/ -char *nifti_xform_string( int xx ) +char const *nifti_xform_string( int xx ) { switch( xx ){ case NIFTI_XFORM_SCANNER_ANAT: return "Scanner Anat" ; @@ -1264,7 +1296,7 @@ char *nifti_xform_string( int xx ) \sa NIFTI1_INTENT_CODES group in nifti1.h *//*-------------------------------------------------------------------------*/ -char *nifti_intent_string( int ii ) +char const *nifti_intent_string( int ii ) { switch( ii ){ case NIFTI_INTENT_CORREL: return "Correlation statistic" ; @@ -1320,7 +1352,7 @@ char *nifti_intent_string( int ii ) \sa NIFTI1_SLICE_ORDER group in nifti1.h *//*-------------------------------------------------------------------------*/ -char *nifti_slice_string( int ss ) +char const *nifti_slice_string( int ss ) { switch( ss ){ case NIFTI_SLICE_SEQ_INC: return "sequential_increasing" ; @@ -1345,7 +1377,7 @@ char *nifti_slice_string( int ss ) \sa NIFTI_L2R in nifti1_io.h *//*-------------------------------------------------------------------------*/ -char *nifti_orientation_string( int ii ) +char const *nifti_orientation_string( int ii ) { switch( ii ){ case NIFTI_L2R: return "Left-to-Right" ; @@ -2422,6 +2454,8 @@ int nifti_fileexists(const char* fname) /*----------------------------------------------------------------------*/ /*! return whether the filename is valid + + Note: uppercase extensions are now valid. 27 Apr 2009 [rickr] The name is considered valid if the file basename has length greater than zero, AND one of the valid nifti extensions is provided. @@ -2437,7 +2471,7 @@ int nifti_fileexists(const char* fname) *//*--------------------------------------------------------------------*/ int nifti_is_complete_filename(const char* fname) { - char * ext; + const char * ext; /* check input file(s) for sanity */ if( fname == NULL || *fname == '\0' ){ @@ -2463,6 +2497,9 @@ int nifti_is_complete_filename(const char* fname) /*----------------------------------------------------------------------*/ /*! return whether the filename is valid + + Allow uppercase extensions as valid. 27 Apr 2009 [rickr] + Any .gz extension case must match the base extension case. The name is considered valid if its length is positive, excluding any nifti filename extension. @@ -2478,7 +2515,7 @@ int nifti_is_complete_filename(const char* fname) *//*--------------------------------------------------------------------*/ int nifti_validfilename(const char* fname) { - char * ext; + const char * ext; /* check input file(s) for sanity */ if( fname == NULL || *fname == '\0' ){ @@ -2505,32 +2542,65 @@ int nifti_validfilename(const char* fname) or any of them followed by .gz. Note that '.' is part of the extension. + Uppercase extensions are also valid, but not mixed case. + \return a pointer to the extension (within the filename), or NULL *//*--------------------------------------------------------------------*/ -char * nifti_find_file_extension( const char * name ) +const char * nifti_find_file_extension( const char * name ) { - char * ext; + const char * ext; + char extcopy[8]; int len; + char extnii[8] = ".nii"; /* modifiable, for possible uppercase */ + char exthdr[8] = ".hdr"; /* (leave space for .gz) */ + char extimg[8] = ".img"; + char extnia[8] = ".nia"; + char extgz[4] = ".gz"; + char * elist[4] = { NULL, NULL, NULL, NULL}; + + /* stupid compiler... */ + elist[0] = extnii; elist[1] = exthdr; elist[2] = extimg; elist[3] = extnia; if ( ! name ) return NULL; len = (int)strlen(name); if ( len < 4 ) return NULL; - ext = (char *)name + len - 4; + ext = name + len - 4; + + /* make manipulation copy, and possibly convert to lowercase */ + strcpy(extcopy, ext); + if( g_opts.allow_upper_fext ) make_lowercase(extcopy); - if ( (strcmp(ext, ".hdr") == 0) || (strcmp(ext, ".img") == 0) || - (strcmp(ext, ".nia") == 0) || (strcmp(ext, ".nii") == 0) ) - return ext; + /* if it look like a basic extension, fail or return it */ + if( compare_strlist(extcopy, elist, 4) >= 0 ) { + if( is_mixedcase(ext) ) { + fprintf(stderr,"** mixed case extension '%s' is not valid\n", ext); + return NULL; + } + else return ext; + } #ifdef HAVE_ZLIB if ( len < 7 ) return NULL; - ext = (char *)name + len - 7; + ext = name + len - 7; + + /* make manipulation copy, and possibly convert to lowercase */ + strcpy(extcopy, ext); + if( g_opts.allow_upper_fext ) make_lowercase(extcopy); + + /* go after .gz extensions using the modifiable strings */ + strcat(elist[0], extgz); strcat(elist[1], extgz); strcat(elist[2], extgz); + + if( compare_strlist(extcopy, elist, 3) >= 0 ) { + if( is_mixedcase(ext) ) { + fprintf(stderr,"** mixed case extension '%s' is not valid\n", ext); + return NULL; + } + else return ext; + } - if ( (strcmp(ext, ".hdr.gz") == 0) || (strcmp(ext, ".img.gz") == 0) || - (strcmp(ext, ".nii.gz") == 0) ) - return ext; #endif if( g_opts.debug > 1 ) @@ -2551,7 +2621,7 @@ int nifti_is_gzfile(const char* fname) int len; len = (int)strlen(fname); if (len < 3) return 0; /* so we don't search before the name */ - if (strcmp(fname + strlen(fname) - 3,".gz")==0) { return 1; } + if (fileext_compare(fname + strlen(fname) - 3,".gz")==0) { return 1; } } #endif return 0; @@ -2576,12 +2646,16 @@ int nifti_compiled_with_zlib(void) *//*--------------------------------------------------------------------*/ char * nifti_makebasename(const char* fname) { - char *basename, *ext; + char *basename; + const char *ext; basename=nifti_strdup(fname); ext = nifti_find_file_extension(basename); - if ( ext ) *ext = '\0'; /* clear out extension */ + if ( ext ) + { + basename[strlen(basename)-strlen(ext)] = '\0'; /* clear out extension */ + } return basename; /* in either case */ } @@ -2608,20 +2682,35 @@ void nifti_set_skip_blank_ext( int skip ) g_opts.skip_blank_ext = skip ? 1 : 0; } +/*----------------------------------------------------------------------*/ +/*! set nifti's global allow_upper_fext flag 28 Apr 2009 [rickr] + + explicitly set to 0 or 1 +*//*--------------------------------------------------------------------*/ +void nifti_set_allow_upper_fext( int allow ) +{ + g_opts.allow_upper_fext = allow ? 1 : 0; +} + /*----------------------------------------------------------------------*/ /*! check current directory for existing header file \return filename of header on success and NULL if no appropriate file could be found + If fname has an uppercase extension, check for uppercase files. + NB: it allocates memory for hdrname which should be freed when no longer required *//*-------------------------------------------------------------------*/ char * nifti_findhdrname(const char* fname) { - char *basename, *hdrname, *ext; + char *basename, *hdrname; + const char *ext; char elist[2][5] = { ".hdr", ".nii" }; - int efirst; + char extzip[4] = ".gz"; + int efirst = 1; /* init to .nii extension */ + int eisupper = 0; /* init to lowercase extensions */ /**- check input file(s) for sanity */ if( !nifti_validfilename(fname) ) return NULL; @@ -2632,12 +2721,18 @@ char * nifti_findhdrname(const char* fname) /**- return filename if it has a valid extension and exists (except if it is an .img file (and maybe .gz)) */ ext = nifti_find_file_extension(fname); + + if( ext ) eisupper = is_uppercase(ext); /* do we look for uppercase? */ + + /* if the file exists and is a valid header name (not .img), return it */ if ( ext && nifti_fileexists(fname) ) { - if ( strncmp(ext,".img",4) != 0 ){ + /* allow for uppercase extension */ + if ( fileext_n_compare(ext,".img",4) != 0 ){ hdrname = nifti_strdup(fname); free(basename); return hdrname; - } + } else + efirst = 0; /* note for below */ } /* So the requested name is a basename, contains .img, or does not exist. */ @@ -2648,8 +2743,14 @@ char * nifti_findhdrname(const char* fname) /* if we get more extension choices, this could be a loop */ - if ( ext && strncmp(ext,".img",4) == 0 ) efirst = 0; - else efirst = 1; + /* note: efirst is 0 in the case of ".img" */ + + /* if the user passed an uppercase entension (.IMG), search for uppercase */ + if( eisupper ) { + make_uppercase(elist[0]); + make_uppercase(elist[1]); + make_uppercase(extzip); + } hdrname = (char *)calloc(sizeof(char),strlen(basename)+8); if( !hdrname ){ @@ -2662,7 +2763,7 @@ char * nifti_findhdrname(const char* fname) strcat(hdrname,elist[efirst]); if (nifti_fileexists(hdrname)) { free(basename); return hdrname; } #ifdef HAVE_ZLIB - strcat(hdrname,".gz"); + strcat(hdrname,extzip); if (nifti_fileexists(hdrname)) { free(basename); return hdrname; } #endif @@ -2674,7 +2775,7 @@ char * nifti_findhdrname(const char* fname) strcat(hdrname,elist[efirst]); if (nifti_fileexists(hdrname)) { free(basename); return hdrname; } #ifdef HAVE_ZLIB - strcat(hdrname,".gz"); + strcat(hdrname,extzip); if (nifti_fileexists(hdrname)) { free(basename); return hdrname; } #endif @@ -2695,12 +2796,19 @@ char * nifti_findhdrname(const char* fname) \return filename of data/img file on success and NULL if no appropriate file could be found + If fname has a valid, uppercase extension, apply all extensions as + uppercase. + NB: it allocates memory for the image filename, which should be freed when no longer required *//*---------------------------------------------------------------------*/ char * nifti_findimgname(const char* fname , int nifti_type) { - char *basename, *imgname, ext[2][5] = { ".nii", ".img" }; + /* store all extensions as strings, in case we need to go uppercase */ + char *basename, *imgname, elist[2][5] = { ".nii", ".img" }; + char extzip[4] = ".gz"; + char extnia[5] = ".nia"; + const char *ext; int first; /* first extension to use */ /* check input file(s) for sanity */ @@ -2714,10 +2822,19 @@ char * nifti_findimgname(const char* fname , int nifti_type) return NULL; } + /* if we are looking for uppercase, apply the fact now */ + ext = nifti_find_file_extension(fname); + if( ext && is_uppercase(ext) ) { + make_uppercase(elist[0]); + make_uppercase(elist[1]); + make_uppercase(extzip); + make_uppercase(extnia); + } + /* only valid extension for ASCII type is .nia, handle first */ if( nifti_type == NIFTI_FTYPE_ASCII ){ strcpy(imgname,basename); - strcat(imgname,".nia"); + strcat(imgname,extnia); if (nifti_fileexists(imgname)) { free(basename); return imgname; } } else { @@ -2731,20 +2848,20 @@ char * nifti_findimgname(const char* fname , int nifti_type) else first = 1; /* should match .img */ strcpy(imgname,basename); - strcat(imgname,ext[first]); + strcat(imgname,elist[first]); if (nifti_fileexists(imgname)) { free(basename); return imgname; } #ifdef HAVE_ZLIB /* then also check for .gz */ - strcat(imgname,".gz"); + strcat(imgname,extzip); if (nifti_fileexists(imgname)) { free(basename); return imgname; } #endif /* failed to find image file with expected extension, try the other */ strcpy(imgname,basename); - strcat(imgname,ext[1-first]); /* can do this with only 2 choices */ + strcat(imgname,elist[1-first]); /* can do this with only 2 choices */ if (nifti_fileexists(imgname)) { free(basename); return imgname; } #ifdef HAVE_ZLIB /* then also check for .gz */ - strcat(imgname,".gz"); + strcat(imgname,extzip); if (nifti_fileexists(imgname)) { free(basename); return imgname; } #endif } @@ -2773,7 +2890,13 @@ char * nifti_findimgname(const char* fname , int nifti_type) char * nifti_makehdrname(const char * prefix, int nifti_type, int check, int comp) { - char * iname, * ext; + char * iname; + const char * ext; + char extnii[5] = ".nii"; /* modifiable, for possible uppercase */ + char exthdr[5] = ".hdr"; + char extimg[5] = ".img"; + char extnia[5] = ".nia"; + char extgz[5] = ".gz"; if( !nifti_validfilename(prefix) ) return NULL; @@ -2784,16 +2907,27 @@ char * nifti_makehdrname(const char * prefix, int nifti_type, int check, /* use any valid extension */ if( (ext = nifti_find_file_extension(iname)) != NULL ){ - if( strncmp(ext,".img",4) == 0 ) - memcpy(ext,".hdr",4); /* then convert img name to hdr */ + /* if uppercase, convert all extensions */ + if( is_uppercase(ext) ) { + make_uppercase(extnii); + make_uppercase(exthdr); + make_uppercase(extimg); + make_uppercase(extnia); + make_uppercase(extgz); + } + + if( strncmp(ext,extimg,4) == 0 ) + { + memcpy(&(iname[strlen(iname)-strlen(ext)]),exthdr,4); /* then convert img name to hdr */ + } } - /* otherwise, make one up an */ - else if( nifti_type == NIFTI_FTYPE_NIFTI1_1 ) strcat(iname, ".nii"); - else if( nifti_type == NIFTI_FTYPE_ASCII ) strcat(iname, ".nia"); - else strcat(iname, ".hdr"); + /* otherwise, make one up */ + else if( nifti_type == NIFTI_FTYPE_NIFTI1_1 ) strcat(iname, extnii); + else if( nifti_type == NIFTI_FTYPE_ASCII ) strcat(iname, extnia); + else strcat(iname, exthdr); -#ifdef HAVE_ZLIB /* then also check for .gz */ - if( comp && (!ext || !strstr(iname,".gz")) ) strcat(iname,".gz"); +#ifdef HAVE_ZLIB /* if compression is requested, make sure of suffix */ + if( comp && (!ext || !strstr(iname,extgz)) ) strcat(iname,extgz); #endif /* check for existence failure */ @@ -2826,7 +2960,13 @@ char * nifti_makehdrname(const char * prefix, int nifti_type, int check, char * nifti_makeimgname(const char * prefix, int nifti_type, int check, int comp) { - char * iname, * ext; + char * iname; + const char * ext; + char extnii[5] = ".nii"; /* modifiable, for possible uppercase */ + char exthdr[5] = ".hdr"; + char extimg[5] = ".img"; + char extnia[5] = ".nia"; + char extgz[5] = ".gz"; if( !nifti_validfilename(prefix) ) return NULL; @@ -2837,16 +2977,27 @@ char * nifti_makeimgname(const char * prefix, int nifti_type, int check, /* use any valid extension */ if( (ext = nifti_find_file_extension(iname)) != NULL ){ - if( strncmp(ext,".hdr",4) == 0 ) - memcpy(ext,".img",4); /* then convert hdr name to img */ + /* if uppercase, convert all extensions */ + if( is_uppercase(ext) ) { + make_uppercase(extnii); + make_uppercase(exthdr); + make_uppercase(extimg); + make_uppercase(extnia); + make_uppercase(extgz); + } + + if( strncmp(ext,exthdr,4) == 0 ) + { + memcpy(&(iname[strlen(iname)-strlen(ext)]),extimg,4); /* then convert hdr name to img */ + } } /* otherwise, make one up */ - else if( nifti_type == NIFTI_FTYPE_NIFTI1_1 ) strcat(iname, ".nii"); - else if( nifti_type == NIFTI_FTYPE_ASCII ) strcat(iname, ".nia"); - else strcat(iname, ".img"); + else if( nifti_type == NIFTI_FTYPE_NIFTI1_1 ) strcat(iname, extnii); + else if( nifti_type == NIFTI_FTYPE_ASCII ) strcat(iname, extnia); + else strcat(iname, extimg); -#ifdef HAVE_ZLIB /* then also check for .gz */ - if( comp && (!ext || !strstr(iname,".gz")) ) strcat(iname,".gz"); +#ifdef HAVE_ZLIB /* if compression is requested, make sure of suffix */ + if( comp && (!ext || !strstr(iname,extgz)) ) strcat(iname,extgz); #endif /* check for existence failure */ @@ -2933,7 +3084,8 @@ int nifti_set_filenames( nifti_image * nim, const char * prefix, int check, int nifti_type_and_names_match( nifti_image * nim, int show_warn ) { char func[] = "nifti_type_and_names_match"; - char * ext_h, * ext_i; /* header and image filename extensions */ + const char * ext_h; /* header filename extension */ + const char * ext_i; /* image filename extension */ int errs = 0; /* error counter */ /* sanity checks */ @@ -2979,14 +3131,14 @@ int nifti_type_and_names_match( nifti_image * nim, int show_warn ) /* general tests */ if( nim->nifti_type == NIFTI_FTYPE_NIFTI1_1 ){ /* .nii */ - if( strncmp(ext_h,".nii",4) ) { + if( fileext_n_compare(ext_h,".nii",4) ) { if( show_warn ) fprintf(stderr, "-d NIFTI_FTYPE 1, but no .nii extension in header filename, %s\n", nim->fname); errs++; } - if( strncmp(ext_i,".nii",4) ) { + if( fileext_n_compare(ext_i,".nii",4) ) { if( show_warn ) fprintf(stderr, "-d NIFTI_FTYPE 1, but no .nii extension in image filename, %s\n", @@ -3004,13 +3156,13 @@ int nifti_type_and_names_match( nifti_image * nim, int show_warn ) else if( (nim->nifti_type == NIFTI_FTYPE_NIFTI1_2) || /* .hdr/.img */ (nim->nifti_type == NIFTI_FTYPE_ANALYZE) ) { - if( strncmp(ext_h,".hdr",4) != 0 ){ + if( fileext_n_compare(ext_h,".hdr",4) != 0 ){ if( show_warn ) fprintf(stderr,"-d no '.hdr' extension, but NIFTI type is %d, %s\n", nim->nifti_type, nim->fname); errs++; } - if( strncmp(ext_i,".img",4) != 0 ){ + if( fileext_n_compare(ext_i,".img",4) != 0 ){ if( show_warn ) fprintf(stderr,"-d no '.img' extension, but NIFTI type is %d, %s\n", nim->nifti_type, nim->iname); @@ -3022,6 +3174,125 @@ int nifti_type_and_names_match( nifti_image * nim, int show_warn ) return 1; } +/* like strcmp, but also check against capitalization of known_ext + * (test as local string, with max length 7) */ +static int fileext_compare(const char * test_ext, const char * known_ext) +{ + char caps[8] = ""; + size_t c,len; + /* if equal, don't need to check case (store to avoid multiple calls) */ + const int cmp = strcmp(test_ext, known_ext); + if( cmp == 0 ) return cmp; + + /* if anything odd, use default */ + if( !test_ext || !known_ext ) return cmp; + + len = strlen(known_ext); + if( len > 7 ) return cmp; + + /* if here, strings are different but need to check upper-case */ + + for(c = 0; c < len; c++ ) caps[c] = toupper(known_ext[c]); + caps[c] = '\0'; + + return strcmp(test_ext, caps); +} + +/* like strncmp, but also check against capitalization of known_ext + * (test as local string, with max length 7) */ +static int fileext_n_compare(const char * test_ext, + const char * known_ext, size_t maxlen) +{ + char caps[8] = ""; + size_t c,len; + /* if equal, don't need to check case (store to avoid multiple calls) */ + const int cmp = strncmp(test_ext, known_ext, maxlen); + if( cmp == 0 ) return cmp; + + /* if anything odd, use default */ + if( !test_ext || !known_ext ) return cmp; + + len = strlen(known_ext); + if( len > maxlen ) len = maxlen; /* ignore anything past maxlen */ + if( len > 7 ) return cmp; + + /* if here, strings are different but need to check upper-case */ + for(c = 0; c < len; c++ ) caps[c] = toupper(known_ext[c]); + caps[c] = '\0'; + + return strncmp(test_ext, caps, maxlen); +} + +/* return 1 if there are uppercase but no lowercase */ +static int is_uppercase(const char * str) +{ + size_t c; + int hasupper = 0; + + if( !str || !*str ) return 0; + + for(c = 0; c < strlen(str); c++ ) { + if( islower(str[c]) ) return 0; + if( !hasupper && isupper(str[c]) ) hasupper = 1; + } + + return hasupper; +} + +/* return 1 if there are both uppercase and lowercase characters */ +static int is_mixedcase(const char * str) +{ + size_t c; + int hasupper = 0, haslower = 0; + + if( !str || !*str ) return 0; + + for(c = 0; c < strlen(str); c++ ) { + if( !haslower && islower(str[c]) ) haslower = 1; + if( !hasupper && isupper(str[c]) ) hasupper = 1; + + if( haslower && hasupper ) return 1; + } + + return 0; +} + +/* convert any lowercase chars to uppercase */ +static int make_uppercase(char * str) +{ + size_t c; + + if( !str || !*str ) return 0; + + for(c = 0; c < strlen(str); c++ ) + if( islower(str[c]) ) str[c] = toupper(str[c]); + + return 0; +} + +/* convert any uppercase chars to lowercase */ +static int make_lowercase(char * str) +{ + size_t c; + if( !str || !*str ) return 0; + + for(c = 0; c < strlen(str); c++ ) + if( isupper(str[c]) ) str[c] = tolower(str[c]); + + return 0; +} + +/* run strcmp against of list of strings + * return index of equality, if found + * else return -1 */ +static int compare_strlist(const char * str, char ** strlist, int len) +{ + int c; + if( len <= 0 || !str || !strlist ) return -1; + for( c = 0; c < len; c++ ) + if( strlist[c] && !strcmp(str, strlist[c]) ) return c; + return -1; +} /*--------------------------------------------------------------------------*/ /*! check whether the given type is on the "approved" list @@ -3107,7 +3378,7 @@ int nifti_set_type_from_names( nifti_image * nim ) fprintf(stderr,"-d verify nifti_type from filenames: %d",nim->nifti_type); /* type should be NIFTI_FTYPE_ASCII if extension is .nia */ - if( (strcmp(nifti_find_file_extension( nim->fname ),".nia")==0) ) { + if( (fileext_compare(nifti_find_file_extension(nim->fname),".nia")==0)){ nim->nifti_type = NIFTI_FTYPE_ASCII; } else { /* not too picky here, do what must be done, and then verify */ @@ -3309,7 +3580,7 @@ nifti_image* nifti_convert_nhdr2nim(struct nifti_1_header nhdr, int is_nifti , is_onefile ; nifti_image *nim; - nim = (nifti_image *) calloc( 1 , sizeof(nifti_image) ) ; + nim = (nifti_image *)calloc( 1 , sizeof(nifti_image) ) ; if( !nim ) ERREX("failed to allocate nifti image"); /* be explicit with pointers */ @@ -4804,7 +5075,7 @@ size_t nifti_write_buffer(znzFile fp, const void *buffer, size_t numbytes) fprintf(stderr,"** ERROR: nifti_write_buffer: null file pointer\n"); return 0; } - ss = znzwrite( (void*)buffer , 1 , numbytes , fp ) ; + ss = znzwrite( (const void*)buffer , 1 , numbytes , fp ) ; return ss; } @@ -6076,7 +6347,7 @@ nifti_image *nifti_image_from_ascii( const char *str, int * bytes_read ) /* create empty image struct */ - nim = (nifti_image *) calloc( 1 , sizeof(nifti_image) ) ; + nim = (nifti_image *)calloc( 1 , sizeof(nifti_image) ) ; if( !nim ){ fprintf(stderr,"** NIFA: failed to alloc nifti_image\n"); return NULL; @@ -6451,7 +6722,7 @@ int nifti_read_collapsed_image( nifti_image * nim, const int dims [8], /** - check pointers for sanity */ if( !nim || !dims || !data ){ fprintf(stderr,"** nifti_RCI: bad params %p, %p, %p\n", - (void *)nim, (void *)dims, (void *)data); + (void *)nim, (const void *)dims, (void *)data); return -1; } @@ -6803,15 +7074,15 @@ static int rci_read_data(nifti_image * nim, int * pivots, int * prods, */ static int rci_alloc_mem(void ** data, int prods[8], int nprods, int nbyper ) { - int size, index; + int size, memindex; if( nbyper < 0 || nprods < 1 || nprods > 8 ){ fprintf(stderr,"** rci_am: bad params, %d, %d\n", nbyper, nprods); return -1; } - for( index = 0, size = 1; index < nprods; index++ ) - size *= prods[index]; + for( memindex = 0, size = 1; memindex < nprods; memindex++ ) + size *= prods[memindex]; size *= nbyper; @@ -6842,19 +7113,19 @@ static int rci_alloc_mem(void ** data, int prods[8], int nprods, int nbyper ) static int make_pivot_list(nifti_image * nim, const int dims[], int pivots[], int prods[], int * nprods ) { - int len, index; + int len, dim_index; len = 0; - index = nim->dim[0]; - while( index > 0 ){ + dim_index = nim->dim[0]; + while( dim_index > 0 ){ prods[len] = 1; - while( index > 0 && (nim->dim[index] == 1 || dims[index] == -1) ){ - prods[len] *= nim->dim[index]; - index--; + while( dim_index > 0 && (nim->dim[dim_index] == 1 || dims[dim_index] == -1) ){ + prods[len] *= nim->dim[dim_index]; + dim_index--; } - pivots[len] = index; + pivots[len] = dim_index; len++; - index--; /* fine, let it drop out at -1 */ + dim_index--; /* fine, let it drop out at -1 */ } /* make sure to include 0 as a pivot (instead of just 1, if it is) */ @@ -6868,9 +7139,9 @@ static int make_pivot_list(nifti_image * nim, const int dims[], int pivots[], if( g_opts.debug > 2 ){ fprintf(stderr,"+d pivot list created, pivots :"); - for(index = 0; index < len; index++) fprintf(stderr," %d", pivots[index]); + for(dim_index = 0; dim_index < len; dim_index++) fprintf(stderr," %d", pivots[dim_index]); fprintf(stderr,", prods :"); - for(index = 0; index < len; index++) fprintf(stderr," %d", prods[index]); + for(dim_index = 0; dim_index < len; dim_index++) fprintf(stderr," %d", prods[dim_index]); fputc('\n',stderr); } @@ -6920,7 +7191,11 @@ int * nifti_get_intlist( int nvals , const char * str ) if( str == NULL || str[0] == '\0' ) return NULL ; /* skip initial '[' or '{' */ - subv = (int *) malloc( sizeof(int) * 2 ) ; + subv = (int *)malloc( sizeof(int) * 2 ) ; + if( !subv ) { + fprintf(stderr,"** nifti_get_intlist: failed alloc of 2 ints\n"); + return NULL; + } subv[0] = nout = 0 ; ipos = 0 ; @@ -6967,7 +7242,12 @@ int * nifti_get_intlist( int nvals , const char * str ) if( str[ipos] == ',' || ISEND(str[ipos]) ){ nout++ ; - subv = (int *) realloc( (char *)subv , sizeof(int) * (nout+1) ) ; + subv = (int *)realloc( (char *)subv , sizeof(int) * (nout+1) ) ; + if( !subv ) { + fprintf(stderr,"** nifti_get_intlist: failed realloc of %d ints\n", + nout+1); + return NULL; + } subv[0] = nout ; subv[nout] = ibot ; if( ISEND(str[ipos]) ) break ; /* done */ @@ -7014,7 +7294,7 @@ int * nifti_get_intlist( int nvals , const char * str ) istep = (ibot <= itop) ? 1 : -1 ; - while( isspace((int) str[ipos]) ) ipos++ ; /* skip blanks */ + while( isspace((int) str[ipos]) ) ipos++ ; /* skip blanks */ /**- check if we have a non-default loop step */ @@ -7038,14 +7318,19 @@ int * nifti_get_intlist( int nvals , const char * str ) for( ii=ibot ; (ii-itop)*istep <= 0 ; ii += istep ){ nout++ ; - subv = (int *) realloc( (char *)subv , sizeof(int) * (nout+1) ) ; + subv = (int *)realloc( (char *)subv , sizeof(int) * (nout+1) ) ; + if( !subv ) { + fprintf(stderr,"** nifti_get_intlist: failed realloc of %d ints\n", + nout+1); + return NULL; + } subv[0] = nout ; subv[nout] = ii ; } /**- check if we have a comma to skip over */ - while( isspace((int) str[ipos]) ) ipos++ ; /* skip blanks */ + while( isspace((int) str[ipos]) ) ipos++ ; /* skip blanks */ if( str[ipos] == ',' ) ipos++ ; /* skip commas */ } /* end of loop through selector string */ @@ -7085,7 +7370,7 @@ int nifti_datatype_from_string( const char * name ) * corresponding macro label as a string. The dtype code is the * macro value defined in nifti1.h. *//*-------------------------------------------------------------------*/ -char * nifti_datatype_to_string( int dtype ) +const char * nifti_datatype_to_string( int dtype ) { int tablen = sizeof(nifti_type_list)/sizeof(nifti_type_ele); int c; @@ -7170,7 +7455,7 @@ int nifti_test_datatype_sizes(int verb) *//*-------------------------------------------------------------------*/ int nifti_disp_type_list( int which ) { - char * style; + const char * style; int tablen = sizeof(nifti_type_list)/sizeof(nifti_type_ele); int lwhich, c; diff --git a/Utilities/ITK/Utilities/nifti/niftilib/nifti1_io.h b/Utilities/ITK/Utilities/nifti/niftilib/nifti1_io.h index 5e5d73573f2991e74ad1e012d93323b721c6684b..2a8ad3e3d1cd7ce82897e09add359405a9d15e88 100644 --- a/Utilities/ITK/Utilities/nifti/niftilib/nifti1_io.h +++ b/Utilities/ITK/Utilities/nifti/niftilib/nifti1_io.h @@ -244,12 +244,12 @@ typedef struct { /*****************************************************************************/ /*--------------- Prototypes of functions defined in this file --------------*/ -char *nifti_datatype_string ( int dt ) ; -char *nifti_units_string ( int uu ) ; -char *nifti_intent_string ( int ii ) ; -char *nifti_xform_string ( int xx ) ; -char *nifti_slice_string ( int ss ) ; -char *nifti_orientation_string( int ii ) ; +char const * nifti_datatype_string ( int dt ) ; +char const *nifti_units_string ( int uu ) ; +char const *nifti_intent_string ( int ii ) ; +char const *nifti_xform_string ( int xx ) ; +char const *nifti_slice_string ( int ss ) ; +char const *nifti_orientation_string( int ii ) ; int nifti_is_inttype( int dt ) ; @@ -270,7 +270,7 @@ void nifti_swap_Nbytes ( int n , int siz , void *ar ) ; int nifti_datatype_is_valid (int dtype, int for_nifti); int nifti_datatype_from_string(const char * name); -char * nifti_datatype_to_string (int dtype); +const char * nifti_datatype_to_string (int dtype); int nifti_get_filesize( const char *pathname ) ; void swap_nifti_header ( struct nifti_1_header *h , int is_nifti ) ; @@ -322,13 +322,14 @@ char * nifti_makehdrname (const char * prefix, int nifti_type, int check, char * nifti_makeimgname (const char * prefix, int nifti_type, int check, int comp); int is_nifti_file (const char *hname); -char * nifti_find_file_extension(const char * name); +const char * nifti_find_file_extension(const char * name); int nifti_is_complete_filename(const char* fname); int nifti_validfilename(const char* fname); int disp_nifti_1_header(const char * info, const nifti_1_header * hp ) ; void nifti_set_debug_level( int level ) ; void nifti_set_skip_blank_ext( int skip ) ; +void nifti_set_allow_upper_fext( int allow ) ; int valid_nifti_brick_list(nifti_image * nim , int nbricks, const int * blist, int disp_error); @@ -448,9 +449,20 @@ int valid_nifti_extensions(const nifti_image *nim); /~fissell/NIFTI_ECODE_WORKFLOW_FWDS /NIFTI_ECODE_WORKFLOW_FWDS.html */ -#define NIFTI_ECODE_FREESURFER 14 /* http://surfer.nmr.mgh.harvard.edu */ +#define NIFTI_ECODE_FREESURFER 14 /* http://surfer.nmr.mgh.harvard.edu */ -#define NIFTI_MAX_ECODE 14 /******* maximum extension code *******/ +#define NIFTI_ECODE_PYPICKLE 16 /* embedded Python objects + http://niftilib.sourceforge.net + /pynifti */ + + /* LONI MiND codes: http://www.loni.ucla.edu/twiki/bin/view/Main/MiND */ +#define NIFTI_ECODE_MIND_IDENT 18 /* Vishal Patel: vishal.patel@ucla.edu*/ +#define NIFTI_ECODE_B_VALUE 20 +#define NIFTI_ECODE_SPHERICAL_DIRECTION 22 +#define NIFTI_ECODE_DT_COMPONENT 24 +#define NIFTI_ECODE_SHC_DEGREEORDER 26 /* end LONI MiND codes */ + +#define NIFTI_MAX_ECODE 26 /******* maximum extension code *******/ /* nifti_type file codes */ #define NIFTI_FTYPE_ANALYZE 0 @@ -465,15 +477,16 @@ int valid_nifti_extensions(const nifti_image *nim); #ifdef _NIFTI1_IO_C_ typedef struct { - int debug; /*!< debug level for status reports */ - int skip_blank_ext; /*!< skip extender if no extensions */ + int debug; /*!< debug level for status reports */ + int skip_blank_ext; /*!< skip extender if no extensions */ + int allow_upper_fext; /*!< allow uppercase file extensions */ } nifti_global_options; typedef struct { int type; /* should match the NIFTI_TYPE_ #define */ int nbyper; /* bytes per value, matches nifti_image */ int swapsize; /* bytes per swap piece, matches nifti_image */ - char * name; /* text string to match #define */ + char const * const name; /* text string to match #define */ } nifti_type_ele; #undef LNI_FERR /* local nifti file error, to be compact and repetative */ diff --git a/Utilities/ITK/Utilities/nifti/utils/CMakeLists.txt b/Utilities/ITK/Utilities/nifti/utils/CMakeLists.txt index d4e5e785fab21f0e74e104ffd8e4d15657c4846c..c1e1ccce42c0ec8e1aa8222ff060a9ba77f05206 100644 --- a/Utilities/ITK/Utilities/nifti/utils/CMakeLists.txt +++ b/Utilities/ITK/Utilities/nifti/utils/CMakeLists.txt @@ -1,8 +1,7 @@ #File Generated by Hans J. Johnson #Please contact hans-johnson@uiowa.edu for making enhancments/corrections -PROJECT(NIFTIUTILS) -INCLUDE_DIRECTORIES(${NIFTILIB_SOURCE_DIR} ${ZNZLIB_SOURCE_DIR} ${NIFTICDFLIB_SOURCE_DIR}) +INCLUDE_DIRECTORIES(${NIFTI_SOURCE_DIR}/niftilib ${NIFTI_SOURCE_DIR}/znzlib ${NIFTI_SOURCE_DIR}/nifticdf) ADD_EXECUTABLE(${PACKAGE_PREFIX}nifti_stats nifti_stats.c) ADD_EXECUTABLE(${PACKAGE_PREFIX}nifti_tool nifti_tool.c) @@ -24,50 +23,47 @@ IF(NOT NIFTI_INSTALL_NO_DEVELOPMENT) DESTINATION ${NIFTI_INSTALL_INCLUDE_DIR} COMPONENT Development) ENDIF(NOT NIFTI_INSTALL_NO_DEVELOPMENT) -ADD_TEST(${PACKAGE_PREFIX}nifti1_test_help ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti1_test) -ADD_TEST(${PACKAGE_PREFIX}nifti1_test_n1 ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti1_test -n1 ${NIFTI_SOURCE_DIR}/Testing/Data/ATestReferenceImageForReadingAndWriting.nii.gz ${NIFTIUTILS_BINARY_DIR}/n1 ) -ADD_TEST(${PACKAGE_PREFIX}nifti1_test_n2 ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti1_test -n2 ${NIFTI_SOURCE_DIR}/Testing/Data/ATestReferenceImageForReadingAndWriting.nii.gz ${NIFTIUTILS_BINARY_DIR}/n2 ) -ADD_TEST(${PACKAGE_PREFIX}nifti1_test_a2 ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti1_test -a2 ${NIFTI_SOURCE_DIR}/Testing/Data/ATestReferenceImageForReadingAndWriting.nii.gz ${NIFTIUTILS_BINARY_DIR}/a2 ) -ADD_TEST(${PACKAGE_PREFIX}nifti1_test_zn1 ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti1_test -zn1 ${NIFTI_SOURCE_DIR}/Testing/Data/ATestReferenceImageForReadingAndWriting.nii.gz ${NIFTIUTILS_BINARY_DIR}/zn1 ) -ADD_TEST(${PACKAGE_PREFIX}nifti1_test_zn2 ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti1_test -zn2 ${NIFTI_SOURCE_DIR}/Testing/Data/ATestReferenceImageForReadingAndWriting.nii.gz ${NIFTIUTILS_BINARY_DIR}/zn2 ) -ADD_TEST(${PACKAGE_PREFIX}nifti1_test_za2 ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti1_test -za2 ${NIFTI_SOURCE_DIR}/Testing/Data/ATestReferenceImageForReadingAndWriting.nii.gz ${NIFTIUTILS_BINARY_DIR}/za2 ) +ADD_TEST(${PACKAGE_PREFIX}nifti1_test_help ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti1_test) +ADD_TEST(${PACKAGE_PREFIX}nifti1_test_n1 ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti1_test -n1 ${NIFTI_SOURCE_DIR}/Testing/Data/ATestReferenceImageForReadingAndWriting.nii.gz ${NIFTI_BINARY_DIR}/utils/n1 ) +ADD_TEST(${PACKAGE_PREFIX}nifti1_test_n2 ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti1_test -n2 ${NIFTI_SOURCE_DIR}/Testing/Data/ATestReferenceImageForReadingAndWriting.nii.gz ${NIFTI_BINARY_DIR}/utils/n2 ) +ADD_TEST(${PACKAGE_PREFIX}nifti1_test_a2 ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti1_test -a2 ${NIFTI_SOURCE_DIR}/Testing/Data/ATestReferenceImageForReadingAndWriting.nii.gz ${NIFTI_BINARY_DIR}/utils/a2 ) +ADD_TEST(${PACKAGE_PREFIX}nifti1_test_zn1 ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti1_test -zn1 ${NIFTI_SOURCE_DIR}/Testing/Data/ATestReferenceImageForReadingAndWriting.nii.gz ${NIFTI_BINARY_DIR}/utils/zn1 ) +ADD_TEST(${PACKAGE_PREFIX}nifti1_test_zn2 ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti1_test -zn2 ${NIFTI_SOURCE_DIR}/Testing/Data/ATestReferenceImageForReadingAndWriting.nii.gz ${NIFTI_BINARY_DIR}/utils/zn2 ) +ADD_TEST(${PACKAGE_PREFIX}nifti1_test_za2 ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti1_test -za2 ${NIFTI_SOURCE_DIR}/Testing/Data/ATestReferenceImageForReadingAndWriting.nii.gz ${NIFTI_BINARY_DIR}/utils/za2 ) -#The help screens always return 1; ADD_TEST(${PACKAGE_PREFIX}nifti_tool_help ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_tool) -ADD_TEST(${PACKAGE_PREFIX}nifti_tool_n1 ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_tool -disp_hdr -infile ${NIFTIUTILS_BINARY_DIR}/n1 ) -ADD_TEST(${PACKAGE_PREFIX}nifti_tool_n2 ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_tool -disp_hdr -infile ${NIFTIUTILS_BINARY_DIR}/n2 ) -ADD_TEST(${PACKAGE_PREFIX}nifti_tool_a2 ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_tool -disp_hdr -infile ${NIFTIUTILS_BINARY_DIR}/a2 ) -ADD_TEST(${PACKAGE_PREFIX}nifti_tool_zn1 ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_tool -disp_hdr -infile ${NIFTIUTILS_BINARY_DIR}/zn1 ) -ADD_TEST(${PACKAGE_PREFIX}nifti_tool_zn2 ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_tool -disp_hdr -infile ${NIFTIUTILS_BINARY_DIR}/zn2 ) -ADD_TEST(${PACKAGE_PREFIX}nifti_tool_za2 ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_tool -disp_hdr -infile ${NIFTIUTILS_BINARY_DIR}/za2 ) -ADD_TEST(${PACKAGE_PREFIX}nifti_tool_diff_hdr ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_tool -diff_hdr -infile ${NIFTIUTILS_BINARY_DIR}/zn1 ${NIFTIUTILS_BINARY_DIR}/zn1 ) -ADD_TEST(${PACKAGE_PREFIX}nifti_tool_diff_nims ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_tool -diff_nim -infile ${NIFTIUTILS_BINARY_DIR}/zn1 ${NIFTIUTILS_BINARY_DIR}/zn1 ) +#The help screens always return 1; ADD_TEST(${PACKAGE_PREFIX}nifti_tool_help ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_tool) +ADD_TEST(${PACKAGE_PREFIX}nifti_tool_n1 ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_tool -disp_hdr -infile ${NIFTI_BINARY_DIR}/utils/n1 ) +ADD_TEST(${PACKAGE_PREFIX}nifti_tool_n2 ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_tool -disp_hdr -infile ${NIFTI_BINARY_DIR}/utils/n2 ) +ADD_TEST(${PACKAGE_PREFIX}nifti_tool_a2 ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_tool -disp_hdr -infile ${NIFTI_BINARY_DIR}/utils/a2 ) +ADD_TEST(${PACKAGE_PREFIX}nifti_tool_zn1 ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_tool -disp_hdr -infile ${NIFTI_BINARY_DIR}/utils/zn1 ) +ADD_TEST(${PACKAGE_PREFIX}nifti_tool_zn2 ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_tool -disp_hdr -infile ${NIFTI_BINARY_DIR}/utils/zn2 ) +ADD_TEST(${PACKAGE_PREFIX}nifti_tool_za2 ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_tool -disp_hdr -infile ${NIFTI_BINARY_DIR}/utils/za2 ) +ADD_TEST(${PACKAGE_PREFIX}nifti_tool_diff_hdr ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_tool -diff_hdr -infile ${NIFTI_BINARY_DIR}/utils/zn1 ${NIFTI_BINARY_DIR}/utils/zn1 ) +ADD_TEST(${PACKAGE_PREFIX}nifti_tool_diff_nims ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_tool -diff_nim -infile ${NIFTI_BINARY_DIR}/utils/zn1 ${NIFTI_BINARY_DIR}/utils/zn1 ) -ADD_TEST(${PACKAGE_PREFIX}nifti_tool_copy_brick_list ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_tool -cbl -prefix cbl_zn1.nii -infile ${NIFTIUTILS_BINARY_DIR}/zn1.nii.gz[0,1]) -#ADD_TEST(${PACKAGE_PREFIX}nifti_tool_copy_collapsed_image /bin/sh ${NIFTI_SOURCE_DIR}/utils/rmthenrun cci_zn1.nii ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_tool -cci 2 2 2 -1 -1 -1 -1 -prefix cci_zn1.nii -infile ${NIFTIUTILS_BINARY_DIR}/zn1.nii.gz ) -ADD_TEST(${PACKAGE_PREFIX}nifti_tool_disp_ci ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_tool -disp_ci 2 2 2 -1 0 0 0 -infile ${NIFTIUTILS_BINARY_DIR}/zn1.nii.gz ) -ADD_TEST(${PACKAGE_PREFIX}nifti_tool_disp_ts ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_tool -disp_ts 2 2 2 -infile ${NIFTIUTILS_BINARY_DIR}/zn1.nii.gz ) -ADD_TEST(${PACKAGE_PREFIX}nifti_tool_strip_extras ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_tool -strip_extras -infile ${NIFTIUTILS_BINARY_DIR}/zn1.nii.gz ) +ADD_TEST(${PACKAGE_PREFIX}nifti_tool_copy_brick_list ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_tool -cbl -prefix cbl_zn1.nii -infile ${NIFTI_BINARY_DIR}/utils/zn1.nii.gz[0,1]) +#ADD_TEST(${PACKAGE_PREFIX}nifti_tool_copy_collapsed_image /bin/sh ${NIFTI_SOURCE_DIR}/utils/rmthenrun cci_zn1.nii ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_tool -cci 2 2 2 -1 -1 -1 -1 -prefix cci_zn1.nii -infile ${NIFTI_BINARY_DIR}/utils/zn1.nii.gz ) +ADD_TEST(${PACKAGE_PREFIX}nifti_tool_disp_ci ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_tool -disp_ci 2 2 2 -1 0 0 0 -infile ${NIFTI_BINARY_DIR}/utils/zn1.nii.gz ) +ADD_TEST(${PACKAGE_PREFIX}nifti_tool_disp_ts ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_tool -disp_ts 2 2 2 -infile ${NIFTI_BINARY_DIR}/utils/zn1.nii.gz ) +ADD_TEST(${PACKAGE_PREFIX}nifti_tool_strip_extras ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_tool -strip_extras -infile ${NIFTI_BINARY_DIR}/utils/zn1.nii.gz ) # This test needs a file that has extensions to remove -#ADD_TEST(${PACKAGE_PREFIX}nifti_tool_rm_ext /bin/sh ${NIFTI_SOURCE_DIR}/utils/rmthenrun rm_ext.nii ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_tool -rm_ext ALL -prefix rm_ext.nii -infile ${NIFTIUTILS_BINARY_DIR}/zn1.nii.gz ) +#ADD_TEST(${PACKAGE_PREFIX}nifti_tool_rm_ext /bin/sh ${NIFTI_SOURCE_DIR}/utils/rmthenrun rm_ext.nii ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_tool -rm_ext ALL -prefix rm_ext.nii -infile ${NIFTI_BINARY_DIR}/utils/zn1.nii.gz ) -ADD_TEST(${PACKAGE_PREFIX}nifti_tool_check_hdr ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_tool -check_hdr -infile ${NIFTIUTILS_BINARY_DIR}/za2 ) -ADD_TEST(${PACKAGE_PREFIX}nifti_tool_check_nim ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_tool -check_nim -infile ${NIFTIUTILS_BINARY_DIR}/za2 ) +ADD_TEST(${PACKAGE_PREFIX}nifti_tool_check_hdr ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_tool -check_hdr -infile ${NIFTI_BINARY_DIR}/utils/za2 ) +ADD_TEST(${PACKAGE_PREFIX}nifti_tool_check_nim ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_tool -check_nim -infile ${NIFTI_BINARY_DIR}/utils/za2 ) FOREACH(DISTRIBUTION CORREL TTEST FTEST ZSCORE CHISQ BETA BINOM GAMMA POISSON NORMAL FTEST_NONC CHISQ_NONC LOGISTIC LAPLACE UNIFORM TTEST_NONC WEIBULL CHI INVGAUSS EXTVAL PVAL LOGPVAL LOG10PVAL ) - ADD_TEST(${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_stats 0:4:1 ${DISTRIBUTION}) - ADD_TEST(q${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_stats -q 0:4:1 ${DISTRIBUTION}) - ADD_TEST(q1${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_stats -q 0:4:1 ${DISTRIBUTION} 1 1 1) - ADD_TEST(d${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_stats -d 0:4:1 ${DISTRIBUTION}) - ADD_TEST(d1${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_stats -d 0:4:1 ${DISTRIBUTION} 1 1 1) - ADD_TEST(1${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_stats -1 0:4:1 ${DISTRIBUTION}) - ADD_TEST(11${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_stats -1 0:4:1 ${DISTRIBUTION} 1 1 1) - ADD_TEST(z${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_stats -z 0:4:1 ${DISTRIBUTION}) - ADD_TEST(z1${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_stats -z 0:4:1 ${DISTRIBUTION} 1 1 1) - ADD_TEST(h${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_stats -h 0:4:1 ${DISTRIBUTION}) - ADD_TEST(h1${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTIUTILS_BINARY_DIR}/${PACKAGE_PREFIX}nifti_stats -h 0:4:1 ${DISTRIBUTION} 1 1 1) + ADD_TEST(${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_stats 0:4:1 ${DISTRIBUTION}) + ADD_TEST(q${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_stats -q 0:4:1 ${DISTRIBUTION}) + ADD_TEST(q1${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_stats -q 0:4:1 ${DISTRIBUTION} 1 1 1) + ADD_TEST(d${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_stats -d 0:4:1 ${DISTRIBUTION}) + ADD_TEST(d1${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_stats -d 0:4:1 ${DISTRIBUTION} 1 1 1) + ADD_TEST(1${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_stats -1 0:4:1 ${DISTRIBUTION}) + ADD_TEST(11${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_stats -1 0:4:1 ${DISTRIBUTION} 1 1 1) + ADD_TEST(z${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_stats -z 0:4:1 ${DISTRIBUTION}) + ADD_TEST(z1${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_stats -z 0:4:1 ${DISTRIBUTION} 1 1 1) + ADD_TEST(h${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_stats -h 0:4:1 ${DISTRIBUTION}) + ADD_TEST(h1${PACKAGE_PREFIX}nifti_stats_${DISTRIBUTION}_test ${NIFTI_BINARY_DIR}/utils/${PACKAGE_PREFIX}nifti_stats -h 0:4:1 ${DISTRIBUTION} 1 1 1) ENDFOREACH(DISTRIBUTION) - - - diff --git a/Utilities/ITK/Utilities/nifti/znzlib/CMakeLists.txt b/Utilities/ITK/Utilities/nifti/znzlib/CMakeLists.txt index ae24f605e73583d9426bf9cadb077bcaa703a3e8..e925b2e81e5d3229ff85ad99daba2d47b84b3bb3 100644 --- a/Utilities/ITK/Utilities/nifti/znzlib/CMakeLists.txt +++ b/Utilities/ITK/Utilities/nifti/znzlib/CMakeLists.txt @@ -1,6 +1,5 @@ #File Generated by Hans J. Johnson #Please contact hans-johnson@uiowa.edu for making enhancments/corrections -PROJECT(ZNZLIB) SET(ZNZLIB_SRC znzlib.c) INCLUDE_REGULAR_EXPRESSION("^.*$") diff --git a/Utilities/ITK/Utilities/vxl/core/testlib/tests/CMakeLists.txt b/Utilities/ITK/Utilities/vxl/core/testlib/tests/CMakeLists.txt index 6cfd1477bcd85bb2471b9b17c0c9be77a5bc0edd..e18423fcda10fe90b942b25d048c86e9eb23e490 100644 --- a/Utilities/ITK/Utilities/vxl/core/testlib/tests/CMakeLists.txt +++ b/Utilities/ITK/Utilities/vxl/core/testlib/tests/CMakeLists.txt @@ -1,5 +1,4 @@ # This is core/testlib/tests/CMakeLists.txt -SET(EXECUTABLE_OUTPUT_PATH ${vxl_BINARY_DIR}/core/testlib/tests) ADD_EXECUTABLE( testlib_test_all test_driver.cxx diff --git a/Utilities/ITK/Utilities/vxl/core/vnl/CMakeLists.txt b/Utilities/ITK/Utilities/vxl/core/vnl/CMakeLists.txt index 44bb93fbe809e4145a3bcf0ce3a93d25b7ba54cb..7d336d426b67bbcd5bbc6f3ebb1863fbc3f53fef 100644 --- a/Utilities/ITK/Utilities/vxl/core/vnl/CMakeLists.txt +++ b/Utilities/ITK/Utilities/vxl/core/vnl/CMakeLists.txt @@ -30,8 +30,8 @@ IF( VNL_CONFIG_ENABLE_SSE2_ROUNDING ) "Please rerun the cmake configure step" ) ELSE( VXL_SSE2_HARDWARE_SUPPORT_POSSIBLE ) MESSAGE( SEND_ERROR "Cannot have VNL_CONFIG_ENABLE_SSE2_ROUNDING because" - " there is no SSE2 hardware support" ) - SET(VNL_CONFIG_ENABLE_SSE2_ROUNDING 0) + " there is no SSE2 hardware support. VNL_CONFIG_ENABLE_SSE2_ROUNDING is thus forced to OFF" ) + SET(VNL_CONFIG_ENABLE_SSE2_ROUNDING "OFF" CACHE BOOL "Enable Streaming SIMD Extensions 2 implementation of rounding (hardware dependant)." FORCE) ENDIF( VXL_SSE2_HARDWARE_SUPPORT_POSSIBLE ) ENDIF( NOT VXL_HAS_SSE2_HARDWARE_SUPPORT ) ENDIF( VNL_CONFIG_ENABLE_SSE2_ROUNDING ) diff --git a/Utilities/ITK/Utilities/vxl/core/vnl/Templates/vnl_matrix_fixed+double.5.5-.cxx b/Utilities/ITK/Utilities/vxl/core/vnl/Templates/vnl_matrix_fixed+double.5.5-.cxx new file mode 100644 index 0000000000000000000000000000000000000000..62c5c70f2604c9d56a41b791f2aab66108c2f8fa --- /dev/null +++ b/Utilities/ITK/Utilities/vxl/core/vnl/Templates/vnl_matrix_fixed+double.5.5-.cxx @@ -0,0 +1,2 @@ +#include <vnl/vnl_matrix_fixed.txx> +VNL_MATRIX_FIXED_INSTANTIATE(double,5,5); diff --git a/Utilities/ITK/Utilities/vxl/core/vnl/tests/test_math.cxx b/Utilities/ITK/Utilities/vxl/core/vnl/tests/test_math.cxx index 96e727956ccfd74315018ace75f67b85afa813ab..32db802e1f3e22bf98e6a6de12a62794e3e6cb5c 100644 --- a/Utilities/ITK/Utilities/vxl/core/vnl/tests/test_math.cxx +++ b/Utilities/ITK/Utilities/vxl/core/vnl/tests/test_math.cxx @@ -7,13 +7,16 @@ static -void check_pointer( const void * ) +void check_pointer( const void *) { } static void test_static_const_definition() { + // The Intel compiler has problems resolving static consts with this test + // as it stands +#if !defined(__INTEL_COMPILER) check_pointer( &vnl_math::e ); check_pointer( &vnl_math::log2e ); check_pointer( &vnl_math::log10e ); @@ -29,6 +32,7 @@ void test_static_const_definition() check_pointer( &vnl_math::sqrt1_2 ); check_pointer( &vnl_math::eps ); check_pointer( &vnl_math::sqrteps ); +#endif } void test_math() diff --git a/Utilities/ITK/Utilities/vxl/core/vnl/tests/test_numeric_traits.cxx b/Utilities/ITK/Utilities/vxl/core/vnl/tests/test_numeric_traits.cxx index 919d6c419eb5fa7fac742e9491ecdc22f74f34db..7cef7812b6918b2b618a64d130a08fdc408dcf5d 100644 --- a/Utilities/ITK/Utilities/vxl/core/vnl/tests/test_numeric_traits.cxx +++ b/Utilities/ITK/Utilities/vxl/core/vnl/tests/test_numeric_traits.cxx @@ -26,7 +26,9 @@ void test_static_const_definition() check_pointer( &vnl_numeric_traits< Type >::maxval );\ check_pointer( &vnl_numeric_traits< const Type >::maxval );\ } while (false) - + // The Intel compiler has problems resolving static consts with this test + // as it stands +#if !defined(__INTEL_COMPILER) ALL(bool); ALL(char); ALL(unsigned char); @@ -43,6 +45,7 @@ void test_static_const_definition() ONE_ZERO( vcl_complex<float> ); ONE_ZERO( vcl_complex<double> ); ONE_ZERO( vcl_complex<long double> ); +#endif #undef ONE_ZERO #undef ALL diff --git a/Utilities/ITK/Utilities/vxl/core/vnl/vnl_diag_matrix.h b/Utilities/ITK/Utilities/vxl/core/vnl/vnl_diag_matrix.h index 4c54c6a5d41f405a46dddd96ac26bf4c7c4fa776..672506cdc630864638858bfe3d2022689efdca49 100644 --- a/Utilities/ITK/Utilities/vxl/core/vnl/vnl_diag_matrix.h +++ b/Utilities/ITK/Utilities/vxl/core/vnl/vnl_diag_matrix.h @@ -78,7 +78,14 @@ class vnl_diag_matrix return (i != j) ? T(0) : diagonal_[i]; } - inline T& operator () (unsigned i, unsigned j) { + inline T& operator () (unsigned i, +//Need to avoid compiler bug by not supplying the value of j unless checking the assert. +#ifdef NDEBUG +unsigned +#else +unsigned j +#endif +) { assert(i == j); return diagonal_[i]; } diff --git a/Utilities/ITK/Utilities/vxl/core/vnl/vnl_math.cxx b/Utilities/ITK/Utilities/vxl/core/vnl/vnl_math.cxx index 6890c5f50eb324eb4e7ca957e22b5bb01c206924..948a7d9353b93fa814a3dc2512840ba15b939b82 100644 --- a/Utilities/ITK/Utilities/vxl/core/vnl/vnl_math.cxx +++ b/Utilities/ITK/Utilities/vxl/core/vnl/vnl_math.cxx @@ -92,6 +92,7 @@ const double vnl_math::pi_over_4 VCL_STATIC_CONST_INIT_FLOAT_DEFN( 0.78539 const double vnl_math::one_over_pi VCL_STATIC_CONST_INIT_FLOAT_DEFN( 0.31830988618379067154 ); const double vnl_math::two_over_pi VCL_STATIC_CONST_INIT_FLOAT_DEFN( 0.63661977236758134308 ); const double vnl_math::two_over_sqrtpi VCL_STATIC_CONST_INIT_FLOAT_DEFN( 1.12837916709551257390 ); +const double vnl_math::one_over_sqrt2pi VCL_STATIC_CONST_INIT_FLOAT_DEFN( 0.39894228040143267794 ); const double vnl_math::sqrt2 VCL_STATIC_CONST_INIT_FLOAT_DEFN( 1.41421356237309504880 ); const double vnl_math::sqrt1_2 VCL_STATIC_CONST_INIT_FLOAT_DEFN( 0.70710678118654752440 ); diff --git a/Utilities/ITK/Utilities/vxl/core/vnl/vnl_math.h b/Utilities/ITK/Utilities/vxl/core/vnl/vnl_math.h index 87cb41744cd2282bc808d61a8e26c116601c6620..5e956027bd9ed1720d089c7ed65867beca57a179 100644 --- a/Utilities/ITK/Utilities/vxl/core/vnl/vnl_math.h +++ b/Utilities/ITK/Utilities/vxl/core/vnl/vnl_math.h @@ -44,7 +44,7 @@ #endif // Figure out when the fast implementation can be used -#if VNL_CONFIG_ENABLE_SSE2_ROUNDING && (!defined(__GCCXML__)) +#if VNL_CONFIG_ENABLE_SSE2_ROUNDING && (!defined(__GCCXML__)) && defined(__SSE2__) # if !VXL_HAS_EMMINTRIN_H # error "Required file emmintrin.h for SSE2 not found" # else @@ -54,9 +54,9 @@ #else # define USE_SSE2_IMPL 0 #endif -// Turn on fast impl when using GCC with the following exception: -// GCCXML, PPC, PPC64 -#if defined(__GNUC__) && (!defined(__GCCXML__)) && (!defined(__ppc__)) && (!defined(__ppc64__)) +// Turn on fast impl when using GCC on x86 platform with the following exception: +// GCCXML +#if defined(__GNUC__) && (!defined(__GCCXML__)) && (defined(__i386__) || defined(__i386) || defined(__x86_64__) || defined(__x86_64)) # define GCC_USE_FAST_IMPL 1 #else # define GCC_USE_FAST_IMPL 0 diff --git a/Utilities/ITK/Utilities/vxl/core/vnl/vnl_sse.h b/Utilities/ITK/Utilities/vxl/core/vnl/vnl_sse.h index 152d2a816b9fd0c8af19a985788f067d11241ad0..84a55b7b8cc8409eb68886ba067318a475b7abbf 100755 --- a/Utilities/ITK/Utilities/vxl/core/vnl/vnl_sse.h +++ b/Utilities/ITK/Utilities/vxl/core/vnl/vnl_sse.h @@ -53,27 +53,39 @@ #if VNL_CONFIG_ENABLE_SSE2 && VXL_HAS_MM_MALLOC # define VNL_SSE_ALLOC(n,s,a) _mm_malloc(n*s,a) # define VNL_SSE_FREE(v,n,s) _mm_free(v) +//! Custom memory deallocation function to free 16 byte aligned of data +VNL_SSE_FORCE_INLINE void vnl_sse_dealloc(void* mem, unsigned , unsigned ) { VNL_SSE_FREE(mem,n,size); } #elif VNL_CONFIG_ENABLE_SSE2 && VXL_HAS_ALIGNED_MALLOC # include <malloc.h> # define VNL_SSE_ALLOC(n,s,a) _aligned_malloc(n*s,a) # define VNL_SSE_FREE(v,n,s) _aligned_free(v) +//! Custom memory deallocation function to free 16 byte aligned of data +VNL_SSE_FORCE_INLINE void vnl_sse_dealloc(void* mem, unsigned , unsigned ) { VNL_SSE_FREE(mem,n,size); } #elif VNL_CONFIG_ENABLE_SSE2 && VXL_HAS_MINGW_ALIGNED_MALLOC # include <malloc.h> # define VNL_SSE_ALLOC(n,s,a) __mingw_aligned_malloc(n*s,a) # define VNL_SSE_FREE(v,n,s) __mingw_aligned_free(v) +//! Custom memory deallocation function to free 16 byte aligned of data +VNL_SSE_FORCE_INLINE void vnl_sse_dealloc(void* mem, unsigned , unsigned ) { VNL_SSE_FREE(mem,n,size); } #elif VNL_CONFIG_ENABLE_SSE2 && VXL_HAS_POSIX_MEMALIGN # include <vcl_cstdlib.h> # define VNL_SSE_ALLOC(n,s,a) memalign(a,n*s) # define VNL_SSE_FREE(v,n,s) free(v) +//! Custom memory deallocation function to free 16 byte aligned of data +VNL_SSE_FORCE_INLINE void vnl_sse_dealloc(void* mem, unsigned , unsigned ) { VNL_SSE_FREE(mem,n,size); } #else //sse2 disabled or could not get memory alignment support, use slower unaligned based intrinsics # define VNL_SSE_HEAP_STORE(pf) _mm_storeu_##pf # define VNL_SSE_HEAP_LOAD(pf) _mm_loadu_##pf # if VNL_CONFIG_THREAD_SAFE # define VNL_SSE_ALLOC(n,s,a) new char[n*s] # define VNL_SSE_FREE(v,n,s) delete [] static_cast<char*>(v) +//! Custom memory deallocation function to free 16 byte aligned of data +VNL_SSE_FORCE_INLINE void vnl_sse_dealloc(void* mem, unsigned , unsigned ) { VNL_SSE_FREE(mem,n,size); } # else # define VNL_SSE_ALLOC(n,s,a) vnl_alloc::allocate((n == 0) ? 8 : (n * s)); # define VNL_SSE_FREE(v,n,s) if (v) vnl_alloc::deallocate(v, (n == 0) ? 8 : (n * s)); +//! Custom memory deallocation function to free 16 byte aligned of data +VNL_SSE_FORCE_INLINE void vnl_sse_dealloc(void* mem, unsigned n, unsigned size) { VNL_SSE_FREE(mem,n,size); } # endif #endif @@ -95,11 +107,6 @@ VNL_SSE_FORCE_INLINE void* vnl_sse_alloc(unsigned n, unsigned size) return VNL_SSE_ALLOC(n,size,16); } -//! Custom memory deallocation function to free 16 byte aligned of data -VNL_SSE_FORCE_INLINE void vnl_sse_dealloc(void* mem, unsigned n, unsigned size) -{ - VNL_SSE_FREE(mem,n,size); -} //avoid inlining when debugging #ifndef NDEBUG diff --git a/Utilities/ITK/Utilities/vxl/v3p/netlib/tests/CMakeLists.txt b/Utilities/ITK/Utilities/vxl/v3p/netlib/tests/CMakeLists.txt index dbffcffa566cf30d5dd120dc7605536aac47160e..579656fc97e6fecaccd5a367a41285fb5e935467 100644 --- a/Utilities/ITK/Utilities/vxl/v3p/netlib/tests/CMakeLists.txt +++ b/Utilities/ITK/Utilities/vxl/v3p/netlib/tests/CMakeLists.txt @@ -1,5 +1,3 @@ -SET(EXECUTABLE_OUTPUT_PATH ${vxl_BINARY_DIR}/v3p/netlib/tests) - IF(BUILD_TESTING) # test ADD_EXECUTABLE( netlib_lbfgs_example lbfgs-example.c ) diff --git a/Utilities/ITK/Utilities/vxl/v3p/netlib/v3p_f2c_mangle.h b/Utilities/ITK/Utilities/vxl/v3p/netlib/v3p_f2c_mangle.h index 78201690af8494da72e9bea3b272ffa1cc085132..b23b74a607ed2906e1e4ee7430de4fdbe58932b0 100644 --- a/Utilities/ITK/Utilities/vxl/v3p/netlib/v3p_f2c_mangle.h +++ b/Utilities/ITK/Utilities/vxl/v3p/netlib/v3p_f2c_mangle.h @@ -5,6 +5,9 @@ /* Functions */ #define F77_aloc v3p_netlib_F77_aloc #define exit_ v3p_netlib_exit_ +#if defined(c_abs) +#undef c_abs +#endif #define c_abs v3p_netlib_c_abs #define c_div v3p_netlib_c_div #define c_sqrt v3p_netlib_c_sqrt diff --git a/Utilities/ITK/Utilities/vxl/vcl/tests/CMakeLists.txt b/Utilities/ITK/Utilities/vxl/vcl/tests/CMakeLists.txt index 65b0143d5a6a4575fb81e9a9d225eee4779a4b24..74fe59a4ac4cee9f340ac3d697d750d4ebbac31c 100644 --- a/Utilities/ITK/Utilities/vxl/vcl/tests/CMakeLists.txt +++ b/Utilities/ITK/Utilities/vxl/vcl/tests/CMakeLists.txt @@ -1,7 +1,5 @@ # vcl/tests/CMakeLists.txt -SET(EXECUTABLE_OUTPUT_PATH ${vxl_BINARY_DIR}/vcl/tests) - # Avoid adding more test executables here, in order to keep the number # of projects small. (This is a concern for IDEs like Visual Studio.) # Try to follow one of the other tests, like test_algorithm.cxx, diff --git a/Utilities/ITK/Wrapping/CSwig/pythonfiles_install.cmake.in b/Utilities/ITK/Wrapping/CSwig/pythonfiles_install.cmake.in index 2be82b443f012abcf52c6b21265a1601688f1dfa..bc0c7562c6e4ecd6f1424f561aa560e6a1fd6d1a 100644 --- a/Utilities/ITK/Wrapping/CSwig/pythonfiles_install.cmake.in +++ b/Utilities/ITK/Wrapping/CSwig/pythonfiles_install.cmake.in @@ -10,5 +10,4 @@ MESSAGE(STATUS "Installing generated python files.") FILE(INSTALL DESTINATION "@CMAKE_INSTALL_PREFIX@@ITK_INSTALL_LIB_DIR@" TYPE FILE - COMPONENTS "RuntimeLibraries" FILES ${ITK_PYTHON_FILES}) diff --git a/Utilities/ITK/Wrapping/ExplicitITK/Modules/Common/wrap_itkConstNeighborhoodIterator.cmake b/Utilities/ITK/Wrapping/ExplicitITK/Modules/Common/wrap_itkConstNeighborhoodIterator.cmake index ad2b6ebab537cf4a6a3d7f838c938bb80b1a9776..a48fb9d340d010fce8c61d909eeb04c6fa4b7ad5 100644 --- a/Utilities/ITK/Wrapping/ExplicitITK/Modules/Common/wrap_itkConstNeighborhoodIterator.cmake +++ b/Utilities/ITK/Wrapping/ExplicitITK/Modules/Common/wrap_itkConstNeighborhoodIterator.cmake @@ -4,7 +4,7 @@ WRAP_TEMPLATE("ID2ZFID2" "Templates::ImageD2,Templates::ZeroFluxNeumannBoundaryC WRAP_TEMPLATE("IF4ZFID4" "Templates::ImageF4,Templates::ZeroFluxNeumannBoundaryConditionIF4") WRAP_TEMPLATE("IF2ZFIF2" "Templates::ImageF2,Templates::ZeroFluxNeumannBoundaryConditionIF2") WRAP_TEMPLATE("IF3ZFIF3" "Templates::ImageF3,Templates::ZeroFluxNeumannBoundaryConditionIF3") -WRAP_TEMPLATE("IS2ZFIS2" "Templates::ImageS2,Templates::ZeroFluxNeumannBoundaryConditionIS2") +WRAP_TEMPLATE("ISS2ZFISS2" "Templates::ImageSS2,Templates::ZeroFluxNeumannBoundaryConditionISS2") WRAP_TEMPLATE("ISI2ZFISI2" "Templates::ImageSI2,Templates::ZeroFluxNeumannBoundaryConditionISI2") WRAP_TEMPLATE("IUC2ZFIUC2" "Templates::ImageUC2,Templates::ZeroFluxNeumannBoundaryConditionIUC2") WRAP_TEMPLATE("IUC3ZFIUC3" "Templates::ImageUC3,Templates::ZeroFluxNeumannBoundaryConditionIUC3") diff --git a/Utilities/ITK/Wrapping/ExplicitITK/Modules/Common/wrap_itkMatrix.cmake b/Utilities/ITK/Wrapping/ExplicitITK/Modules/Common/wrap_itkMatrix.cmake index 25f3182626f38d8d3a2149970bf23d8fa6d32646..13c7e5170edfcb856e65e252f6ddf85e22b9210d 100644 --- a/Utilities/ITK/Wrapping/ExplicitITK/Modules/Common/wrap_itkMatrix.cmake +++ b/Utilities/ITK/Wrapping/ExplicitITK/Modules/Common/wrap_itkMatrix.cmake @@ -1,7 +1,9 @@ WRAP_CLASS("itk::Matrix") +WRAP_TEMPLATE("D11" "double,1,1") WRAP_TEMPLATE("D22" "double,2,2") -WRAP_TEMPLATE("D44" "double,4,4") WRAP_TEMPLATE("D33" "double,3,3") +WRAP_TEMPLATE("D44" "double,4,4") +WRAP_TEMPLATE("D55" "double,5,5") WRAP_TEMPLATE("D66" "double,6,6") WRAP_TEMPLATE("F33" "float,3,3") END_WRAP_CLASS() diff --git a/Utilities/ITK/Wrapping/WrapITK/ExternalProjects/PyBuffer/itkPyBuffer.txx b/Utilities/ITK/Wrapping/WrapITK/ExternalProjects/PyBuffer/itkPyBuffer.txx index 0abfddc1e134329029b8c86f486c51df10f620df..07e2099ef7d4a41af55c0cf9ac77d3885feab23a 100644 --- a/Utilities/ITK/Wrapping/WrapITK/ExternalProjects/PyBuffer/itkPyBuffer.txx +++ b/Utilities/ITK/Wrapping/WrapITK/ExternalProjects/PyBuffer/itkPyBuffer.txx @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkPyBuffer.txx,v $ Language: C++ - Date: $Date: 2009-05-22 16:39:34 $ - Version: $Revision: 1.2 $ + Date: $Date: 2009-06-23 21:53:24 $ + Version: $Revision: 1.3 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -130,9 +130,10 @@ PyBuffer<TImage> importImageFilterWillOwnTheBuffer ); importer->Update(); - importer->SetReleaseDataFlag( true ); + ImagePointer output = importer->GetOutput(); + output->DisconnectPipeline(); - return ImagePointer(importer->GetOutput()); + return output; } template<class TImage> diff --git a/Utilities/ITK/Wrapping/WrapITK/Modules/VXLNumerics/CMakeLists.txt b/Utilities/ITK/Wrapping/WrapITK/Modules/VXLNumerics/CMakeLists.txt index 304a4b96f7e24432ced675de44d23de595cc3eec..e5471e3c0053751b597287e9df42180aae541c7a 100644 --- a/Utilities/ITK/Wrapping/WrapITK/Modules/VXLNumerics/CMakeLists.txt +++ b/Utilities/ITK/Wrapping/WrapITK/Modules/VXLNumerics/CMakeLists.txt @@ -6,7 +6,7 @@ SET(WRAPPER_LIBRARY_GROUPS vnl_vector ) -SET(WRAPPER_LIBRARY_LINK_LIBRARIES itkvnl itkvnl_inst) +SET(WRAPPER_LIBRARY_LINK_LIBRARIES ITKCommon) # don't include all the default include for that module SET(include_save ${WRAPPER_DEFAULT_INCLUDE}) diff --git a/Utilities/ITK/Wrapping/WrapITK/Modules/VXLNumerics/wrap_vnl_matrix_fixed.cmake b/Utilities/ITK/Wrapping/WrapITK/Modules/VXLNumerics/wrap_vnl_matrix_fixed.cmake index c41bf1e65734f796243f46c361e1d046fd4f4bd0..67d3a5830b0a5654945b3b26ab44851f4d0e2d40 100644 --- a/Utilities/ITK/Wrapping/WrapITK/Modules/VXLNumerics/wrap_vnl_matrix_fixed.cmake +++ b/Utilities/ITK/Wrapping/WrapITK/Modules/VXLNumerics/wrap_vnl_matrix_fixed.cmake @@ -1,6 +1,7 @@ # auto include feature must be disable because the class is not in the file # with the same name SET(WRAPPER_AUTO_INCLUDE_HEADERS OFF) +WRAP_INCLUDE("vnl/vnl_vector_fixed.h") WRAP_INCLUDE("vnl/vnl_matrix_fixed.h") WRAP_CLASS("vnl_matrix_fixed") diff --git a/Utilities/ITK/itkConfigure.h.in b/Utilities/ITK/itkConfigure.h.in index 02d90e51e31f0d14fbf4be69113f5b3ccf953c12..ad3448223071a3b3466056a8b88e634595ab8fa2 100644 --- a/Utilities/ITK/itkConfigure.h.in +++ b/Utilities/ITK/itkConfigure.h.in @@ -3,8 +3,8 @@ Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkConfigure.h.in,v $ Language: C++ - Date: $Date: 2009-05-07 14:03:33 $ - Version: $Revision: 1.32 $ + Date: $Date: 2009-06-16 07:58:46 $ + Version: $Revision: 1.33 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. @@ -85,7 +85,6 @@ #cmakedefine ITK_USE_ORIENTED_IMAGE_DIRECTION #cmakedefine ITK_IMAGE_BEHAVES_AS_ORIENTED_IMAGE #cmakedefine ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY -#cmakedefine ITK_USE_PORTABLE_ROUND #cmakedefine ITK_USE_REGION_VALIDATION_IN_ITERATORS #cmakedefine ITK_USE_TEMPLATE_META_PROGRAMMING_LOOP_UNROLLING #cmakedefine ITK_USE_DEPRECATED_LEVELSET_INTERPOLATION